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 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546
|
#! /usr/bin/env python3
#
# Copyright (c) 2021-2023 Universidade de BrasÃlia
#
# SPDX-License-Identifier: GPL-2.0-only
#
# Author: Gabriel Ferreira <gabrielcarvfer@gmail.com>
"""!
Test suite for the ns3 wrapper script
"""
import glob
import os
import platform
import re
import shutil
import subprocess
import sys
import unittest
from functools import partial
# Get path containing ns3
ns3_path = os.path.dirname(os.path.abspath(os.sep.join([__file__, "../../"])))
ns3_lock_filename = os.path.join(ns3_path, ".lock-ns3_%s_build" % sys.platform)
ns3_script = os.sep.join([ns3_path, "ns3"])
ns3rc_script = os.sep.join([ns3_path, ".ns3rc"])
usual_outdir = os.sep.join([ns3_path, "build"])
usual_lib_outdir = os.sep.join([usual_outdir, "lib"])
# Move the current working directory to the ns-3-dev folder
os.chdir(ns3_path)
# Cmake commands
num_threads = max(1, os.cpu_count() - 1)
cmake_build_project_command = "cmake --build {cmake_cache} -j".format(
ns3_path=ns3_path, cmake_cache=os.path.abspath(os.path.join(ns3_path, "cmake-cache"))
)
cmake_build_target_command = partial(
"cmake --build {cmake_cache} -j {jobs} --target {target}".format,
jobs=num_threads,
cmake_cache=os.path.abspath(os.path.join(ns3_path, "cmake-cache")),
)
win32 = sys.platform == "win32"
macos = sys.platform == "darwin"
platform_makefiles = "MinGW Makefiles" if win32 else "Unix Makefiles"
ext = ".exe" if win32 else ""
arch = platform.machine()
def run_ns3(args, env=None, generator=platform_makefiles):
"""!
Runs the ns3 wrapper script with arguments
@param args: string containing arguments that will get split before calling ns3
@param env: environment variables dictionary
@param generator: CMake generator
@return tuple containing (error code, stdout and stderr)
"""
if "clean" in args:
possible_leftovers = ["contrib/borked", "contrib/calibre"]
for leftover in possible_leftovers:
if os.path.exists(leftover):
shutil.rmtree(leftover, ignore_errors=True)
if " -G " in args:
args = args.format(generator=generator)
if env is None:
env = {}
# Disable colored output by default during tests
env["CLICOLOR"] = "0"
return run_program(ns3_script, args, python=True, env=env)
# Adapted from https://github.com/metabrainz/picard/blob/master/picard/util/__init__.py
def run_program(program, args, python=False, cwd=ns3_path, env=None):
"""!
Runs a program with the given arguments and returns a tuple containing (error code, stdout and stderr)
@param program: program to execute (or python script)
@param args: string containing arguments that will get split before calling the program
@param python: flag indicating whether the program is a python script
@param cwd: the working directory used that will be the root folder for the execution
@param env: environment variables dictionary
@return tuple containing (error code, stdout and stderr)
"""
if type(args) != str:
raise Exception("args should be a string")
# Include python interpreter if running a python script
if python:
arguments = [sys.executable, program]
else:
arguments = [program]
if args != "":
arguments.extend(re.findall(r'(?:".*?"|\S)+', args)) # noqa
for i in range(len(arguments)):
arguments[i] = arguments[i].replace('"', "")
# Forward environment variables used by the ns3 script
current_env = os.environ.copy()
# Add different environment variables
if env:
current_env.update(env)
# Call program with arguments
ret = subprocess.run(
arguments,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=cwd, # run process from the ns-3-dev path
env=current_env,
)
# Return (error code, stdout and stderr)
return (
ret.returncode,
ret.stdout.decode(sys.stdout.encoding),
ret.stderr.decode(sys.stderr.encoding),
)
def get_programs_list():
"""!
Extracts the programs list from .lock-ns3
@return list of programs.
"""
values = {}
with open(ns3_lock_filename, encoding="utf-8") as f:
exec(f.read(), globals(), values)
programs_list = values["ns3_runnable_programs"]
# Add .exe suffix to programs if on Windows
if win32:
programs_list = list(map(lambda x: x + ext, programs_list))
return programs_list
def get_libraries_list(lib_outdir=usual_lib_outdir):
"""!
Gets a list of built libraries
@param lib_outdir: path containing libraries
@return list of built libraries.
"""
libraries = glob.glob(lib_outdir + "/*", recursive=True)
return list(filter(lambda x: "scratch-nested-subdir-lib" not in x, libraries))
def get_headers_list(outdir=usual_outdir):
"""!
Gets a list of header files
@param outdir: path containing headers
@return list of headers.
"""
return glob.glob(outdir + "/**/*.h", recursive=True)
def read_lock_entry(entry):
"""!
Read interesting entries from the .lock-ns3 file
@param entry: entry to read from .lock-ns3
@return value of the requested entry.
"""
values = {}
with open(ns3_lock_filename, encoding="utf-8") as f:
exec(f.read(), globals(), values)
return values.get(entry, None)
def get_test_enabled():
"""!
Check if tests are enabled in the .lock-ns3
@return bool.
"""
return read_lock_entry("ENABLE_TESTS")
def get_enabled_modules():
"""
Check if tests are enabled in the .lock-ns3
@return list of enabled modules (prefixed with 'ns3-').
"""
return read_lock_entry("NS3_ENABLED_MODULES")
class DockerContainerManager:
"""!
Python-on-whales wrapper for Docker-based ns-3 tests
"""
def __init__(self, currentTestCase: unittest.TestCase, containerName: str = "ubuntu:latest"):
"""!
Create and start container with containerName in the current ns-3 directory
@param self: the current DockerContainerManager instance
@param currentTestCase: the test case instance creating the DockerContainerManager
@param containerName: name of the container image to be used
"""
global DockerException
try:
from python_on_whales import docker
from python_on_whales.exceptions import DockerException
except ModuleNotFoundError:
docker = None # noqa
DockerException = None # noqa
currentTestCase.skipTest("python-on-whales was not found")
# Import rootless docker settings from .bashrc
with open(os.path.expanduser("~/.bashrc"), "r", encoding="utf-8") as f:
docker_settings = re.findall("(DOCKER_.*=.*)", f.read())
if docker_settings:
for setting in docker_settings:
key, value = setting.split("=")
os.environ[key] = value
del setting, key, value
# Check if we can use Docker (docker-on-docker is a pain)
try:
docker.ps()
except DockerException as e:
currentTestCase.skipTest(f"python-on-whales returned:{e.__str__()}")
# Create Docker client instance and start it
## The Python-on-whales container instance
self.container = docker.run(
containerName,
interactive=True,
detach=True,
tty=False,
volumes=[(ns3_path, "/ns-3-dev")],
)
# Redefine the execute command of the container
def split_exec(docker_container, cmd):
return docker_container._execute(cmd.split(), workdir="/ns-3-dev")
self.container._execute = self.container.execute
self.container.execute = partial(split_exec, self.container)
def __enter__(self):
"""!
Return the managed container when entiring the block "with DockerContainerManager() as container"
@param self: the current DockerContainerManager instance
@return container managed by DockerContainerManager.
"""
return self.container
def __exit__(self, exc_type, exc_val, exc_tb):
"""!
Clean up the managed container at the end of the block "with DockerContainerManager() as container"
@param self: the current DockerContainerManager instance
@param exc_type: unused parameter
@param exc_val: unused parameter
@param exc_tb: unused parameter
@return None
"""
self.container.stop()
self.container.remove()
class NS3UnusedSourcesTestCase(unittest.TestCase):
"""!
ns-3 tests related to checking if source files were left behind, not being used by CMake
"""
## dictionary containing directories with .cc source files # noqa
directory_and_files = {}
def setUp(self):
"""!
Scan all C++ source files and add them to a list based on their path
@return None
"""
for root, dirs, files in os.walk(ns3_path):
if "gitlab-ci-local" in root:
continue
for name in files:
if name.endswith(".cc"):
path = os.path.join(root, name)
directory = os.path.dirname(path)
if directory not in self.directory_and_files:
self.directory_and_files[directory] = []
self.directory_and_files[directory].append(path)
def test_01_UnusedExampleSources(self):
"""!
Test if all example source files are being used in their respective CMakeLists.txt
@return None
"""
unused_sources = set()
for example_directory in self.directory_and_files.keys():
# Skip non-example directories
if os.sep + "examples" not in example_directory:
continue
# Skip directories without a CMakeLists.txt
if not os.path.exists(os.path.join(example_directory, "CMakeLists.txt")):
continue
# Open the examples CMakeLists.txt and read it
with open(
os.path.join(example_directory, "CMakeLists.txt"), "r", encoding="utf-8"
) as f:
cmake_contents = f.read()
# For each file, check if it is in the CMake contents
for file in self.directory_and_files[example_directory]:
# We remove the .cc because some examples sources can be written as ${example_name}.cc
if os.path.basename(file).replace(".cc", "") not in cmake_contents:
unused_sources.add(file)
self.assertListEqual([], list(unused_sources))
def test_02_UnusedModuleSources(self):
"""!
Test if all module source files are being used in their respective CMakeLists.txt
@return None
"""
unused_sources = set()
for directory in self.directory_and_files.keys():
# Skip examples and bindings directories
is_not_module = not ("src" in directory or "contrib" in directory)
is_example = os.sep + "examples" in directory
is_bindings = os.sep + "bindings" in directory
if is_not_module or is_bindings or is_example:
continue
# We can be in one of the module subdirectories (helper, model, test, bindings, etc)
# Navigate upwards until we hit a CMakeLists.txt
cmake_path = os.path.join(directory, "CMakeLists.txt")
while not os.path.exists(cmake_path):
parent_directory = os.path.dirname(os.path.dirname(cmake_path))
cmake_path = os.path.join(parent_directory, os.path.basename(cmake_path))
# Open the module CMakeLists.txt and read it
with open(cmake_path, "r", encoding="utf-8") as f:
cmake_contents = f.read()
# For each file, check if it is in the CMake contents
for file in self.directory_and_files[directory]:
if os.path.basename(file) not in cmake_contents:
unused_sources.add(file)
# Remove temporary exceptions
exceptions = [
"win32-system-wall-clock-ms.cc", # Should be removed with MR784
]
for exception in exceptions:
for unused_source in unused_sources:
if os.path.basename(unused_source) == exception:
unused_sources.remove(unused_source)
break
self.assertListEqual([], list(unused_sources))
def test_03_UnusedUtilsSources(self):
"""!
Test if all utils source files are being used in their respective CMakeLists.txt
@return None
"""
unused_sources = set()
for directory in self.directory_and_files.keys():
# Skip directories that are not utils
is_module = "src" in directory or "contrib" in directory
if os.sep + "utils" not in directory or is_module:
continue
# We can be in one of the module subdirectories (helper, model, test, bindings, etc)
# Navigate upwards until we hit a CMakeLists.txt
cmake_path = os.path.join(directory, "CMakeLists.txt")
while not os.path.exists(cmake_path):
parent_directory = os.path.dirname(os.path.dirname(cmake_path))
cmake_path = os.path.join(parent_directory, os.path.basename(cmake_path))
# Open the module CMakeLists.txt and read it
with open(cmake_path, "r", encoding="utf-8") as f:
cmake_contents = f.read()
# For each file, check if it is in the CMake contents
for file in self.directory_and_files[directory]:
if os.path.basename(file) not in cmake_contents:
unused_sources.add(file)
self.assertListEqual([], list(unused_sources))
class NS3DependenciesTestCase(unittest.TestCase):
"""!
ns-3 tests related to dependencies
"""
def test_01_CheckIfIncludedHeadersMatchLinkedModules(self):
"""!
Checks if headers from different modules (src/A, contrib/B) that are included by
the current module (src/C) source files correspond to the list of linked modules
LIBNAME C
LIBRARIES_TO_LINK A (missing B)
@return None
"""
modules = {}
headers_to_modules = {}
module_paths = glob.glob(ns3_path + "/src/*/") + glob.glob(ns3_path + "/contrib/*/")
for path in module_paths:
# Open the module CMakeLists.txt and read it
cmake_path = os.path.join(path, "CMakeLists.txt")
with open(cmake_path, "r", encoding="utf-8") as f:
cmake_contents = f.readlines()
module_name = os.path.relpath(path, ns3_path)
module_name_nodir = module_name.replace("src/", "").replace("contrib/", "")
modules[module_name_nodir] = {
"sources": set(),
"headers": set(),
"libraries": set(),
"included_headers": set(),
"included_libraries": set(),
}
# Separate list of source files and header files
for line in cmake_contents:
source_file_path = re.findall(r"\b(?:[^\s]+\.[ch]{1,2})\b", line.strip())
if not source_file_path:
continue
source_file_path = source_file_path[0]
base_name = os.path.basename(source_file_path)
if not os.path.exists(os.path.join(path, source_file_path)):
continue
if ".h" in source_file_path:
# Register all module headers as module headers and sources
modules[module_name_nodir]["headers"].add(base_name)
modules[module_name_nodir]["sources"].add(base_name)
# Register the header as part of the current module
headers_to_modules[base_name] = module_name_nodir
if ".cc" in source_file_path:
# Register the source file as part of the current module
modules[module_name_nodir]["sources"].add(base_name)
if ".cc" in source_file_path or ".h" in source_file_path:
# Extract includes from headers and source files and then add to a list of included headers
source_file = os.path.join(ns3_path, module_name, source_file_path)
with open(source_file, "r", encoding="utf-8") as f:
source_contents = f.read()
modules[module_name_nodir]["included_headers"].update(
map(
lambda x: x.replace("ns3/", ""),
re.findall('#include.*["|<](.*)["|>]', source_contents),
)
)
continue
# Extract libraries linked to the module
modules[module_name_nodir]["libraries"].update(
re.findall(r"\${lib(.*?)}", "".join(cmake_contents))
)
modules[module_name_nodir]["libraries"] = list(
filter(
lambda x: x
not in ["raries_to_link", module_name_nodir, module_name_nodir + "-obj"],
modules[module_name_nodir]["libraries"],
)
)
# Now that we have all the information we need, check if we have all the included libraries linked
all_project_headers = set(headers_to_modules.keys())
sys.stderr.flush()
print(file=sys.stderr)
for module in sorted(modules):
external_headers = modules[module]["included_headers"].difference(all_project_headers)
project_headers_included = modules[module]["included_headers"].difference(
external_headers
)
modules[module]["included_libraries"] = set(
[headers_to_modules[x] for x in project_headers_included]
).difference({module})
diff = modules[module]["included_libraries"].difference(modules[module]["libraries"])
# Find graph with least amount of edges based on included_libraries
def recursive_check_dependencies(checked_module):
# Remove direct explicit dependencies
for module_to_link in modules[checked_module]["included_libraries"]:
modules[checked_module]["included_libraries"] = set(
modules[checked_module]["included_libraries"]
) - set(modules[module_to_link]["included_libraries"])
for module_to_link in modules[checked_module]["included_libraries"]:
recursive_check_dependencies(module_to_link)
# Remove unnecessary implicit dependencies
def is_implicitly_linked(searched_module, current_module):
if len(modules[current_module]["included_libraries"]) == 0:
return False
if searched_module in modules[current_module]["included_libraries"]:
return True
for module in modules[current_module]["included_libraries"]:
if is_implicitly_linked(searched_module, module):
return True
return False
from itertools import combinations
implicitly_linked = set()
for dep1, dep2 in combinations(modules[checked_module]["included_libraries"], 2):
if is_implicitly_linked(dep1, dep2):
implicitly_linked.add(dep1)
if is_implicitly_linked(dep2, dep1):
implicitly_linked.add(dep2)
modules[checked_module]["included_libraries"] = (
set(modules[checked_module]["included_libraries"]) - implicitly_linked
)
for module in modules:
recursive_check_dependencies(module)
# Print findings
for module in sorted(modules):
if module == "test":
continue
minimal_linking_set = ", ".join(modules[module]["included_libraries"])
unnecessarily_linked = ", ".join(
set(modules[module]["libraries"]) - set(modules[module]["included_libraries"])
)
missing_linked = ", ".join(
set(modules[module]["included_libraries"]) - set(modules[module]["libraries"])
)
if unnecessarily_linked:
print(f"Module '{module}' unnecessarily linked: {unnecessarily_linked}.")
if missing_linked:
print(f"Module '{module}' missing linked: {missing_linked}.")
if unnecessarily_linked or missing_linked:
print(f"Module '{module}' minimal linking set: {minimal_linking_set}.")
self.assertTrue(True)
class NS3StyleTestCase(unittest.TestCase):
"""!
ns-3 tests to check if the source code, whitespaces and CMake formatting
are according to the coding style
"""
## Holds the original diff, which must be maintained by each and every case tested # noqa
starting_diff = None
## Holds the GitRepo's repository object # noqa
repo = None
def setUp(self) -> None:
"""!
Import GitRepo and load the original diff state of the repository before the tests
@return None
"""
if not NS3StyleTestCase.starting_diff:
if shutil.which("git") is None:
self.skipTest("Git is not available")
try:
import git.exc # noqa
from git import Repo # noqa
except ImportError:
self.skipTest("GitPython is not available")
try:
repo = Repo(ns3_path) # noqa
except git.exc.InvalidGitRepositoryError: # noqa
self.skipTest("ns-3 directory does not contain a .git directory")
hcommit = repo.head.commit # noqa
NS3StyleTestCase.starting_diff = hcommit.diff(None)
NS3StyleTestCase.repo = repo
if NS3StyleTestCase.starting_diff is None:
self.skipTest("Unmet dependencies")
def test_01_CheckCMakeFormat(self):
"""!
Check if there is any difference between tracked file after
applying cmake-format
@return None
"""
for required_program in ["cmake", "cmake-format"]:
if shutil.which(required_program) is None:
self.skipTest("%s was not found" % required_program)
# Configure ns-3 to get the cmake-format target
return_code, stdout, stderr = run_ns3("configure")
self.assertEqual(return_code, 0)
# Build/run cmake-format
return_code, stdout, stderr = run_ns3("build cmake-format")
self.assertEqual(return_code, 0)
# Clean the ns-3 configuration
return_code, stdout, stderr = run_ns3("clean")
self.assertEqual(return_code, 0)
# Check if the diff still is the same
new_diff = NS3StyleTestCase.repo.head.commit.diff(None)
self.assertEqual(NS3StyleTestCase.starting_diff, new_diff)
class NS3CommonSettingsTestCase(unittest.TestCase):
"""!
ns3 tests related to generic options
"""
def setUp(self):
"""!
Clean configuration/build artifacts before common commands
@return None
"""
super().setUp()
# No special setup for common test cases other than making sure we are working on a clean directory.
run_ns3("clean")
def test_01_NoOption(self):
"""!
Test not passing any arguments to
@return None
"""
return_code, stdout, stderr = run_ns3("")
self.assertEqual(return_code, 1)
self.assertIn("You need to configure ns-3 first: try ./ns3 configure", stdout)
def test_02_NoTaskLines(self):
"""!
Test only passing --quiet argument to ns3
@return None
"""
return_code, stdout, stderr = run_ns3("--quiet")
self.assertEqual(return_code, 1)
self.assertIn("You need to configure ns-3 first: try ./ns3 configure", stdout)
def test_03_CheckConfig(self):
"""!
Test only passing 'show config' argument to ns3
@return None
"""
return_code, stdout, stderr = run_ns3("show config")
self.assertEqual(return_code, 1)
self.assertIn("You need to configure ns-3 first: try ./ns3 configure", stdout)
def test_04_CheckProfile(self):
"""!
Test only passing 'show profile' argument to ns3
@return None
"""
return_code, stdout, stderr = run_ns3("show profile")
self.assertEqual(return_code, 1)
self.assertIn("You need to configure ns-3 first: try ./ns3 configure", stdout)
def test_05_CheckVersion(self):
"""!
Test only passing 'show version' argument to ns3
@return None
"""
return_code, stdout, stderr = run_ns3("show version")
self.assertEqual(return_code, 1)
self.assertIn("You need to configure ns-3 first: try ./ns3 configure", stdout)
class NS3ConfigureBuildProfileTestCase(unittest.TestCase):
"""!
ns3 tests related to build profiles
"""
def setUp(self):
"""!
Clean configuration/build artifacts before testing configuration settings
@return None
"""
super().setUp()
# No special setup for common test cases other than making sure we are working on a clean directory.
run_ns3("clean")
def test_01_Debug(self):
"""!
Test the debug build
@return None
"""
return_code, stdout, stderr = run_ns3(
'configure -G "{generator}" -d debug --enable-verbose'
)
self.assertEqual(return_code, 0)
self.assertIn("Build profile : debug", stdout)
self.assertIn("Build files have been written to", stdout)
# Build core to check if profile suffixes match the expected.
return_code, stdout, stderr = run_ns3("build core")
self.assertEqual(return_code, 0)
self.assertIn("Built target core", stdout)
libraries = get_libraries_list()
self.assertGreater(len(libraries), 0)
self.assertIn("core-debug", libraries[0])
def test_02_Release(self):
"""!
Test the release build
@return None
"""
return_code, stdout, stderr = run_ns3('configure -G "{generator}" -d release')
self.assertEqual(return_code, 0)
self.assertIn("Build profile : release", stdout)
self.assertIn("Build files have been written to", stdout)
def test_03_Optimized(self):
"""!
Test the optimized build
@return None
"""
return_code, stdout, stderr = run_ns3(
'configure -G "{generator}" -d optimized --enable-verbose'
)
self.assertEqual(return_code, 0)
self.assertIn("Build profile : optimized", stdout)
self.assertIn("Build files have been written to", stdout)
# Build core to check if profile suffixes match the expected
return_code, stdout, stderr = run_ns3("build core")
self.assertEqual(return_code, 0)
self.assertIn("Built target core", stdout)
libraries = get_libraries_list()
self.assertGreater(len(libraries), 0)
self.assertIn("core-optimized", libraries[0])
def test_04_Typo(self):
"""!
Test a build type with a typo
@return None
"""
return_code, stdout, stderr = run_ns3('configure -G "{generator}" -d Optimized')
self.assertEqual(return_code, 2)
self.assertIn("invalid choice: 'Optimized'", stderr)
def test_05_TYPO(self):
"""!
Test a build type with another typo
@return None
"""
return_code, stdout, stderr = run_ns3('configure -G "{generator}" -d OPTIMIZED')
self.assertEqual(return_code, 2)
self.assertIn("invalid choice: 'OPTIMIZED'", stderr)
def test_06_OverwriteDefaultSettings(self):
"""!
Replace settings set by default (e.g. ASSERT/LOGs enabled in debug builds and disabled in default ones)
@return None
"""
return_code, _, _ = run_ns3("clean")
self.assertEqual(return_code, 0)
return_code, stdout, stderr = run_ns3('configure -G "{generator}" --dry-run -d debug')
self.assertEqual(return_code, 0)
self.assertIn(
"-DCMAKE_BUILD_TYPE=debug -DNS3_ASSERT=ON -DNS3_LOG=ON -DNS3_WARNINGS_AS_ERRORS=ON -DNS3_NATIVE_OPTIMIZATIONS=OFF",
stdout,
)
return_code, stdout, stderr = run_ns3(
'configure -G "{generator}" --dry-run -d debug --disable-asserts --disable-logs --disable-werror'
)
self.assertEqual(return_code, 0)
self.assertIn(
"-DCMAKE_BUILD_TYPE=debug -DNS3_NATIVE_OPTIMIZATIONS=OFF -DNS3_ASSERT=OFF -DNS3_LOG=OFF -DNS3_WARNINGS_AS_ERRORS=OFF",
stdout,
)
return_code, stdout, stderr = run_ns3('configure -G "{generator}" --dry-run')
self.assertEqual(return_code, 0)
self.assertIn(
"-DCMAKE_BUILD_TYPE=default -DNS3_ASSERT=ON -DNS3_LOG=ON -DNS3_WARNINGS_AS_ERRORS=OFF -DNS3_NATIVE_OPTIMIZATIONS=OFF",
stdout,
)
return_code, stdout, stderr = run_ns3(
'configure -G "{generator}" --dry-run --enable-asserts --enable-logs --enable-werror'
)
self.assertEqual(return_code, 0)
self.assertIn(
"-DCMAKE_BUILD_TYPE=default -DNS3_ASSERT=ON -DNS3_LOG=ON -DNS3_NATIVE_OPTIMIZATIONS=OFF -DNS3_ASSERT=ON -DNS3_LOG=ON -DNS3_WARNINGS_AS_ERRORS=ON",
stdout,
)
class NS3BaseTestCase(unittest.TestCase):
"""!
Generic test case with basic function inherited by more complex tests.
"""
def config_ok(self, return_code, stdout, stderr):
"""!
Check if configuration for release mode worked normally
@param return_code: return code from CMake
@param stdout: output from CMake.
@param stderr: error from CMake.
@return None
"""
self.assertEqual(return_code, 0)
self.assertIn("Build profile : release", stdout)
self.assertIn("Build files have been written to", stdout)
self.assertNotIn("uninitialized variable", stderr)
def setUp(self):
"""!
Clean configuration/build artifacts before testing configuration and build settings
After configuring the build as release,
check if configuration worked and check expected output files.
@return None
"""
super().setUp()
if os.path.exists(ns3rc_script):
os.remove(ns3rc_script)
# Reconfigure from scratch before each test
run_ns3("clean")
return_code, stdout, stderr = run_ns3(
'configure -G "{generator}" -d release --enable-verbose'
)
self.config_ok(return_code, stdout, stderr)
# Check if .lock-ns3 exists, then read to get list of executables.
self.assertTrue(os.path.exists(ns3_lock_filename))
## ns3_executables holds a list of executables in .lock-ns3 # noqa
self.ns3_executables = get_programs_list()
# Check if .lock-ns3 exists than read to get the list of enabled modules.
self.assertTrue(os.path.exists(ns3_lock_filename))
## ns3_modules holds a list to the modules enabled stored in .lock-ns3 # noqa
self.ns3_modules = get_enabled_modules()
class NS3ConfigureTestCase(NS3BaseTestCase):
"""!
Test ns3 configuration options
"""
def setUp(self):
"""!
Reuse cleaning/release configuration from NS3BaseTestCase if flag is cleaned
@return None
"""
super().setUp()
def test_01_Examples(self):
"""!
Test enabling and disabling examples
@return None
"""
return_code, stdout, stderr = run_ns3('configure -G "{generator}" --enable-examples')
# This just tests if we didn't break anything, not that we actually have enabled anything.
self.config_ok(return_code, stdout, stderr)
# If nothing went wrong, we should have more executables in the list after enabling the examples.
## ns3_executables
self.assertGreater(len(get_programs_list()), len(self.ns3_executables))
# Now we disabled them back.
return_code, stdout, stderr = run_ns3('configure -G "{generator}" --disable-examples')
# This just tests if we didn't break anything, not that we actually have enabled anything.
self.config_ok(return_code, stdout, stderr)
# Then check if they went back to the original list.
self.assertEqual(len(get_programs_list()), len(self.ns3_executables))
def test_02_Tests(self):
"""!
Test enabling and disabling tests
@return None
"""
# Try enabling tests
return_code, stdout, stderr = run_ns3('configure -G "{generator}" --enable-tests')
self.config_ok(return_code, stdout, stderr)
# Then try building the libcore test
return_code, stdout, stderr = run_ns3("build core-test")
# If nothing went wrong, this should have worked
self.assertEqual(return_code, 0)
self.assertIn("Built target core-test", stdout)
# Now we disabled the tests
return_code, stdout, stderr = run_ns3('configure -G "{generator}" --disable-tests')
self.config_ok(return_code, stdout, stderr)
# Now building the library test should fail
return_code, stdout, stderr = run_ns3("build core-test")
# Then check if they went back to the original list
self.assertEqual(return_code, 1)
self.assertIn("Target to build does not exist: core-test", stdout)
def test_03_EnableModules(self):
"""!
Test enabling specific modules
@return None
"""
# Try filtering enabled modules to network+Wi-Fi and their dependencies
return_code, stdout, stderr = run_ns3(
"configure -G \"{generator}\" --enable-modules='network;wifi'"
)
self.config_ok(return_code, stdout, stderr)
# At this point we should have fewer modules
enabled_modules = get_enabled_modules()
## ns3_modules
self.assertLess(len(get_enabled_modules()), len(self.ns3_modules))
self.assertIn("ns3-network", enabled_modules)
self.assertIn("ns3-wifi", enabled_modules)
# Try enabling only core
return_code, stdout, stderr = run_ns3(
"configure -G \"{generator}\" --enable-modules='core'"
)
self.config_ok(return_code, stdout, stderr)
self.assertIn("ns3-core", get_enabled_modules())
# Try cleaning the list of enabled modules to reset to the normal configuration.
return_code, stdout, stderr = run_ns3("configure -G \"{generator}\" --enable-modules=''")
self.config_ok(return_code, stdout, stderr)
# At this point we should have the same amount of modules that we had when we started.
self.assertEqual(len(get_enabled_modules()), len(self.ns3_modules))
def test_04_DisableModules(self):
"""!
Test disabling specific modules
@return None
"""
# Try filtering disabled modules to disable lte and modules that depend on it.
return_code, stdout, stderr = run_ns3(
"configure -G \"{generator}\" --disable-modules='lte;wifi'"
)
self.config_ok(return_code, stdout, stderr)
# At this point we should have fewer modules.
enabled_modules = get_enabled_modules()
self.assertLess(len(enabled_modules), len(self.ns3_modules))
self.assertNotIn("ns3-lte", enabled_modules)
self.assertNotIn("ns3-wifi", enabled_modules)
# Try cleaning the list of enabled modules to reset to the normal configuration.
return_code, stdout, stderr = run_ns3("configure -G \"{generator}\" --disable-modules=''")
self.config_ok(return_code, stdout, stderr)
# At this point we should have the same amount of modules that we had when we started.
self.assertEqual(len(get_enabled_modules()), len(self.ns3_modules))
def test_05_EnableModulesComma(self):
"""!
Test enabling comma-separated (waf-style) examples
@return None
"""
# Try filtering enabled modules to network+Wi-Fi and their dependencies.
return_code, stdout, stderr = run_ns3(
"configure -G \"{generator}\" --enable-modules='network,wifi'"
)
self.config_ok(return_code, stdout, stderr)
# At this point we should have fewer modules.
enabled_modules = get_enabled_modules()
self.assertLess(len(get_enabled_modules()), len(self.ns3_modules))
self.assertIn("ns3-network", enabled_modules)
self.assertIn("ns3-wifi", enabled_modules)
# Try cleaning the list of enabled modules to reset to the normal configuration.
return_code, stdout, stderr = run_ns3("configure -G \"{generator}\" --enable-modules=''")
self.config_ok(return_code, stdout, stderr)
# At this point we should have the same amount of modules that we had when we started.
self.assertEqual(len(get_enabled_modules()), len(self.ns3_modules))
def test_06_DisableModulesComma(self):
"""!
Test disabling comma-separated (waf-style) examples
@return None
"""
# Try filtering disabled modules to disable lte and modules that depend on it.
return_code, stdout, stderr = run_ns3(
"configure -G \"{generator}\" --disable-modules='lte,mpi'"
)
self.config_ok(return_code, stdout, stderr)
# At this point we should have fewer modules.
enabled_modules = get_enabled_modules()
self.assertLess(len(enabled_modules), len(self.ns3_modules))
self.assertNotIn("ns3-lte", enabled_modules)
self.assertNotIn("ns3-mpi", enabled_modules)
# Try cleaning the list of enabled modules to reset to the normal configuration.
return_code, stdout, stderr = run_ns3("configure -G \"{generator}\" --disable-modules=''")
self.config_ok(return_code, stdout, stderr)
# At this point we should have the same amount of modules that we had when we started.
self.assertEqual(len(get_enabled_modules()), len(self.ns3_modules))
def test_07_Ns3rc(self):
"""!
Test loading settings from the ns3rc config file
@return None
"""
class ns3rc_str: # noqa
## python-based ns3rc template # noqa
ns3rc_python_template = "# ! /usr/bin/env python\
\
# A list of the modules that will be enabled when ns-3 is run.\
# Modules that depend on the listed modules will be enabled also.\
#\
# All modules can be enabled by choosing 'all_modules'.\
modules_enabled = [{modules}]\
\
# Set this equal to true if you want examples to be run.\
examples_enabled = {examples}\
\
# Set this equal to true if you want tests to be run.\
tests_enabled = {tests}\
"
## cmake-based ns3rc template # noqa
ns3rc_cmake_template = "set(ns3rc_tests_enabled {tests})\
\nset(ns3rc_examples_enabled {examples})\
\nset(ns3rc_enabled_modules {modules})\
"
## map ns3rc templates to types # noqa
ns3rc_templates = {"python": ns3rc_python_template, "cmake": ns3rc_cmake_template}
def __init__(self, type_ns3rc):
## type contains the ns3rc variant type (deprecated python-based or current cmake-based)
self.type = type_ns3rc
def format(self, **args):
# Convert arguments from python-based ns3rc format to CMake
if self.type == "cmake":
args["modules"] = (
args["modules"].replace("'", "").replace('"', "").replace(",", " ")
)
args["examples"] = "ON" if args["examples"] == "True" else "OFF"
args["tests"] = "ON" if args["tests"] == "True" else "OFF"
formatted_string = ns3rc_str.ns3rc_templates[self.type].format(**args)
# Return formatted string
return formatted_string
@staticmethod
def types():
return ns3rc_str.ns3rc_templates.keys()
for ns3rc_type in ns3rc_str.types():
# Replace default format method from string with a custom one
ns3rc_template = ns3rc_str(ns3rc_type)
# Now we repeat the command line tests but with the ns3rc file.
with open(ns3rc_script, "w", encoding="utf-8") as f:
f.write(ns3rc_template.format(modules="'lte'", examples="False", tests="True"))
# Reconfigure.
run_ns3("clean")
return_code, stdout, stderr = run_ns3(
'configure -G "{generator}" -d release --enable-verbose'
)
self.config_ok(return_code, stdout, stderr)
# Check.
enabled_modules = get_enabled_modules()
self.assertLess(len(get_enabled_modules()), len(self.ns3_modules))
self.assertIn("ns3-lte", enabled_modules)
self.assertTrue(get_test_enabled())
self.assertLessEqual(
len(get_programs_list()), len(self.ns3_executables) + (win32 or macos)
)
# Replace the ns3rc file with the wifi module, enabling examples and disabling tests
with open(ns3rc_script, "w", encoding="utf-8") as f:
f.write(ns3rc_template.format(modules="'wifi'", examples="True", tests="False"))
# Reconfigure
return_code, stdout, stderr = run_ns3('configure -G "{generator}"')
self.config_ok(return_code, stdout, stderr)
# Check
enabled_modules = get_enabled_modules()
self.assertLess(len(get_enabled_modules()), len(self.ns3_modules))
self.assertIn("ns3-wifi", enabled_modules)
self.assertFalse(get_test_enabled())
self.assertGreater(len(get_programs_list()), len(self.ns3_executables))
# Replace the ns3rc file with multiple modules
with open(ns3rc_script, "w", encoding="utf-8") as f:
f.write(
ns3rc_template.format(
modules="'core','network'", examples="True", tests="False"
)
)
# Reconfigure
return_code, stdout, stderr = run_ns3('configure -G "{generator}"')
self.config_ok(return_code, stdout, stderr)
# Check
enabled_modules = get_enabled_modules()
self.assertLess(len(get_enabled_modules()), len(self.ns3_modules))
self.assertIn("ns3-core", enabled_modules)
self.assertIn("ns3-network", enabled_modules)
self.assertFalse(get_test_enabled())
self.assertGreater(len(get_programs_list()), len(self.ns3_executables))
# Replace the ns3rc file with multiple modules,
# in various different ways and with comments
with open(ns3rc_script, "w", encoding="utf-8") as f:
if ns3rc_type == "python":
f.write(
ns3rc_template.format(
modules="""'core', #comment
'lte',
#comment2,
#comment3
'network', 'internet','wifi'""",
examples="True",
tests="True",
)
)
else:
f.write(
ns3rc_template.format(
modules="'core', 'lte', 'network', 'internet', 'wifi'",
examples="True",
tests="True",
)
)
# Reconfigure
return_code, stdout, stderr = run_ns3('configure -G "{generator}"')
self.config_ok(return_code, stdout, stderr)
# Check
enabled_modules = get_enabled_modules()
self.assertLess(len(get_enabled_modules()), len(self.ns3_modules))
self.assertIn("ns3-core", enabled_modules)
self.assertIn("ns3-internet", enabled_modules)
self.assertIn("ns3-lte", enabled_modules)
self.assertIn("ns3-wifi", enabled_modules)
self.assertTrue(get_test_enabled())
self.assertGreater(len(get_programs_list()), len(self.ns3_executables))
# Then we roll back by removing the ns3rc config file
os.remove(ns3rc_script)
# Reconfigure
return_code, stdout, stderr = run_ns3('configure -G "{generator}"')
self.config_ok(return_code, stdout, stderr)
# Check
self.assertEqual(len(get_enabled_modules()), len(self.ns3_modules))
self.assertFalse(get_test_enabled())
self.assertEqual(len(get_programs_list()), len(self.ns3_executables))
def test_08_DryRun(self):
"""!
Test dry-run (printing commands to be executed instead of running them)
@return None
"""
run_ns3("clean")
# Try dry-run before and after the positional commands (outputs should match)
for positional_command in ["configure", "build", "clean"]:
return_code, stdout, stderr = run_ns3("--dry-run %s" % positional_command)
return_code1, stdout1, stderr1 = run_ns3("%s --dry-run" % positional_command)
self.assertEqual(return_code, return_code1)
self.assertEqual(stdout, stdout1)
self.assertEqual(stderr, stderr1)
run_ns3("clean")
# Build target before using below
run_ns3('configure -G "{generator}" -d release --enable-verbose')
run_ns3("build scratch-simulator")
# Run all cases and then check outputs
return_code0, stdout0, stderr0 = run_ns3("--dry-run run scratch-simulator")
return_code1, stdout1, stderr1 = run_ns3("run scratch-simulator")
return_code2, stdout2, stderr2 = run_ns3("--dry-run run scratch-simulator --no-build")
return_code3, stdout3, stderr3 = run_ns3("run scratch-simulator --no-build")
# Return code and stderr should be the same for all of them.
self.assertEqual(sum([return_code0, return_code1, return_code2, return_code3]), 0)
self.assertEqual([stderr0, stderr1, stderr2, stderr3], [""] * 4)
scratch_path = None
for program in get_programs_list():
if "scratch-simulator" in program and "subdir" not in program:
scratch_path = program
break
# Scratches currently have a 'scratch_' prefix in their CMake targets
# Case 0: dry-run + run (should print commands to build target and then run)
self.assertIn(cmake_build_target_command(target="scratch_scratch-simulator"), stdout0)
self.assertIn(scratch_path, stdout0)
# Case 1: run (should print only make build message)
self.assertNotIn(cmake_build_target_command(target="scratch_scratch-simulator"), stdout1)
self.assertIn("Built target", stdout1)
self.assertNotIn(scratch_path, stdout1)
# Case 2: dry-run + run-no-build (should print commands to run the target)
self.assertIn("The following commands would be executed:", stdout2)
self.assertIn(scratch_path, stdout2)
# Case 3: run-no-build (should print the target output only)
self.assertNotIn("Finished executing the following commands:", stdout3)
self.assertNotIn(scratch_path, stdout3)
def test_09_PropagationOfReturnCode(self):
"""!
Test if ns3 is propagating back the return code from the executables called with the run command
@return None
"""
# From this point forward we are reconfiguring in debug mode
return_code, _, _ = run_ns3("clean")
self.assertEqual(return_code, 0)
return_code, _, _ = run_ns3('configure -G "{generator}" --enable-examples --enable-tests')
self.assertEqual(return_code, 0)
# Build necessary executables
return_code, stdout, stderr = run_ns3("build command-line-example test-runner")
self.assertEqual(return_code, 0)
# Now some tests will succeed normally
return_code, stdout, stderr = run_ns3(
'run "test-runner --test-name=command-line" --no-build'
)
self.assertEqual(return_code, 0)
# Now some tests will fail during NS_COMMANDLINE_INTROSPECTION
return_code, stdout, stderr = run_ns3(
'run "test-runner --test-name=command-line" --no-build',
env={"NS_COMMANDLINE_INTROSPECTION": ".."},
)
self.assertNotEqual(return_code, 0)
# Cause a sigsegv
sigsegv_example = os.path.join(ns3_path, "scratch", "sigsegv.cc")
with open(sigsegv_example, "w", encoding="utf-8") as f:
f.write(
"""
int main (int argc, char *argv[])
{
char *s = "hello world"; *s = 'H';
return 0;
}
"""
)
return_code, stdout, stderr = run_ns3("run sigsegv")
if win32:
self.assertEqual(return_code, 4294967295) # unsigned -1
self.assertIn("sigsegv-default.exe' returned non-zero exit status", stdout)
else:
self.assertEqual(return_code, 245)
self.assertIn("sigsegv-default' died with <Signals.SIGSEGV: 11>", stdout)
# Cause an abort
abort_example = os.path.join(ns3_path, "scratch", "abort.cc")
with open(abort_example, "w", encoding="utf-8") as f:
f.write(
"""
#include "ns3/core-module.h"
using namespace ns3;
int main (int argc, char *argv[])
{
NS_ABORT_IF(true);
return 0;
}
"""
)
return_code, stdout, stderr = run_ns3("run abort")
if win32:
self.assertNotEqual(return_code, 0)
self.assertIn("abort-default.exe' returned non-zero exit status", stdout)
else:
self.assertEqual(return_code, 250)
self.assertIn("abort-default' died with <Signals.SIGABRT: 6>", stdout)
os.remove(sigsegv_example)
os.remove(abort_example)
def test_10_CheckConfig(self):
"""!
Test passing 'show config' argument to ns3 to get the configuration table
@return None
"""
return_code, stdout, stderr = run_ns3("show config")
self.assertEqual(return_code, 0)
self.assertIn("Summary of ns-3 settings", stdout)
def test_11_CheckProfile(self):
"""!
Test passing 'show profile' argument to ns3 to get the build profile
@return None
"""
return_code, stdout, stderr = run_ns3("show profile")
self.assertEqual(return_code, 0)
self.assertIn("Build profile: release", stdout)
def test_12_CheckVersion(self):
"""!
Test passing 'show version' argument to ns3 to get the build version
@return None
"""
if shutil.which("git") is None:
self.skipTest("git is not available")
return_code, _, _ = run_ns3('configure -G "{generator}" --enable-build-version')
self.assertEqual(return_code, 0)
return_code, stdout, stderr = run_ns3("show version")
self.assertEqual(return_code, 0)
self.assertIn("ns-3 version:", stdout)
def test_13_Scratches(self):
"""!
Test if CMake target names for scratches and ns3 shortcuts
are working correctly
@return None
"""
test_files = [
"scratch/main.cc",
"scratch/empty.cc",
"scratch/subdir1/main.cc",
"scratch/subdir2/main.cc",
"scratch/main.test.dots.in.name.cc",
]
backup_files = ["scratch/.main.cc"] # hidden files should be ignored
# Create test scratch files
for path in test_files + backup_files:
filepath = os.path.join(ns3_path, path)
os.makedirs(os.path.dirname(filepath), exist_ok=True)
with open(filepath, "w", encoding="utf-8") as f:
if "main" in path:
f.write("int main (int argc, char *argv[]){}")
else:
# no main function will prevent this target from
# being created, we should skip it and continue
# processing without crashing
f.write("")
# Reload the cmake cache to pick them up
# It will fail because the empty scratch has no main function
return_code, stdout, stderr = run_ns3('configure -G "{generator}"')
self.assertEqual(return_code, 1)
# Remove the empty.cc file and try again
empty = "scratch/empty.cc"
os.remove(empty)
test_files.remove(empty)
return_code, stdout, stderr = run_ns3('configure -G "{generator}"')
self.assertEqual(return_code, 0)
# Try to build them with ns3 and cmake
for path in test_files + backup_files:
path = path.replace(".cc", "")
return_code1, stdout1, stderr1 = run_program(
"cmake",
"--build . --target %s -j %d" % (path.replace("/", "_"), num_threads),
cwd=os.path.join(ns3_path, "cmake-cache"),
)
return_code2, stdout2, stderr2 = run_ns3("build %s" % path)
if "main" in path and ".main" not in path:
self.assertEqual(return_code1, 0)
self.assertEqual(return_code2, 0)
else:
self.assertEqual(return_code1, 2)
self.assertEqual(return_code2, 1)
# Try to run them
for path in test_files:
path = path.replace(".cc", "")
return_code, stdout, stderr = run_ns3("run %s --no-build" % path)
if "main" in path:
self.assertEqual(return_code, 0)
else:
self.assertEqual(return_code, 1)
run_ns3("clean")
with DockerContainerManager(self, "ubuntu:22.04") as container:
container.execute("apt-get update")
container.execute("apt-get install -y python3 cmake g++ ninja-build")
try:
container.execute(
"./ns3 configure --enable-modules=core,network,internet -- -DCMAKE_CXX_COMPILER=/usr/bin/g++"
)
except DockerException as e:
self.fail()
for path in test_files:
path = path.replace(".cc", "")
try:
container.execute(f"./ns3 run {path}")
except DockerException as e:
if "main" in path:
self.fail()
run_ns3("clean")
# Delete the test files and reconfigure to clean them up
for path in test_files + backup_files:
source_absolute_path = os.path.join(ns3_path, path)
os.remove(source_absolute_path)
if "empty" in path or ".main" in path:
continue
filename = os.path.basename(path).replace(".cc", "")
executable_absolute_path = os.path.dirname(os.path.join(ns3_path, "build", path))
if os.path.exists(executable_absolute_path):
executable_name = list(
filter(lambda x: filename in x, os.listdir(executable_absolute_path))
)[0]
os.remove(os.path.join(executable_absolute_path, executable_name))
if not os.listdir(os.path.dirname(path)):
os.rmdir(os.path.dirname(source_absolute_path))
return_code, stdout, stderr = run_ns3('configure -G "{generator}"')
self.assertEqual(return_code, 0)
def test_14_MpiCommandTemplate(self):
"""!
Test if ns3 is inserting additional arguments by MPICH and OpenMPI to run on the CI
@return None
"""
# Skip test if mpi is not installed
if shutil.which("mpiexec") is None or win32:
self.skipTest("Mpi is not available")
return_code, stdout, stderr = run_ns3('configure -G "{generator}" --enable-examples')
self.assertEqual(return_code, 0)
executables = get_programs_list()
# Ensure sample simulator was built
return_code, stdout, stderr = run_ns3("build sample-simulator")
self.assertEqual(return_code, 0)
# Get executable path
sample_simulator_path = list(filter(lambda x: "sample-simulator" in x, executables))[0]
mpi_command = '--dry-run run sample-simulator --command-template="mpiexec -np 2 %s"'
non_mpi_command = '--dry-run run sample-simulator --command-template="echo %s"'
# Get the commands to run sample-simulator in two processes with mpi
return_code, stdout, stderr = run_ns3(mpi_command)
self.assertEqual(return_code, 0)
self.assertIn("mpiexec -np 2 %s" % sample_simulator_path, stdout)
# Get the commands to run sample-simulator in two processes with mpi, now with the environment variable
return_code, stdout, stderr = run_ns3(mpi_command)
self.assertEqual(return_code, 0)
if os.getenv("USER", "") == "root":
if shutil.which("ompi_info"):
self.assertIn(
"mpiexec --allow-run-as-root --oversubscribe -np 2 %s" % sample_simulator_path,
stdout,
)
else:
self.assertIn(
"mpiexec --allow-run-as-root -np 2 %s" % sample_simulator_path, stdout
)
else:
self.assertIn("mpiexec -np 2 %s" % sample_simulator_path, stdout)
# Now we repeat for the non-mpi command
return_code, stdout, stderr = run_ns3(non_mpi_command)
self.assertEqual(return_code, 0)
self.assertIn("echo %s" % sample_simulator_path, stdout)
# Again the non-mpi command, with the MPI_CI environment variable set
return_code, stdout, stderr = run_ns3(non_mpi_command)
self.assertEqual(return_code, 0)
self.assertIn("echo %s" % sample_simulator_path, stdout)
return_code, stdout, stderr = run_ns3('configure -G "{generator}" --disable-examples')
self.assertEqual(return_code, 0)
def test_15_InvalidLibrariesToLink(self):
"""!
Test if CMake and ns3 fail in the expected ways when:
- examples from modules or general examples fail if they depend on a
library with a name shorter than 4 characters or are disabled when
a library is nonexistent
- a module library passes the configuration but fails to build due to
a missing library
@return None
"""
os.makedirs("contrib/borked", exist_ok=True)
os.makedirs("contrib/borked/examples", exist_ok=True)
# Test if configuration succeeds and building the module library fails
with open("contrib/borked/examples/CMakeLists.txt", "w", encoding="utf-8") as f:
f.write("")
for invalid_or_nonexistent_library in ["", "gsd", "lib", "libfi", "calibre"]:
with open("contrib/borked/CMakeLists.txt", "w", encoding="utf-8") as f:
f.write(
"""
build_lib(
LIBNAME borked
SOURCE_FILES ${PROJECT_SOURCE_DIR}/build-support/empty.cc
LIBRARIES_TO_LINK ${libcore} %s
)
"""
% invalid_or_nonexistent_library
)
return_code, stdout, stderr = run_ns3('configure -G "{generator}" --enable-examples')
if invalid_or_nonexistent_library in ["", "gsd", "libfi", "calibre"]:
self.assertEqual(return_code, 0)
elif invalid_or_nonexistent_library in ["lib"]:
self.assertEqual(return_code, 1)
self.assertIn("Invalid library name: %s" % invalid_or_nonexistent_library, stderr)
else:
pass
return_code, stdout, stderr = run_ns3("build borked")
if invalid_or_nonexistent_library in [""]:
self.assertEqual(return_code, 0)
elif invalid_or_nonexistent_library in ["lib"]:
self.assertEqual(return_code, 2) # should fail due to invalid library name
self.assertIn("Invalid library name: %s" % invalid_or_nonexistent_library, stderr)
elif invalid_or_nonexistent_library in ["gsd", "libfi", "calibre"]:
self.assertEqual(return_code, 2) # should fail due to missing library
if "lld" in stdout + stderr:
self.assertIn(
"unable to find library -l%s" % invalid_or_nonexistent_library, stderr
)
elif "mold" in stdout + stderr:
self.assertIn("library not found: %s" % invalid_or_nonexistent_library, stderr)
elif macos:
self.assertIn(
"library not found for -l%s" % invalid_or_nonexistent_library, stderr
)
else:
self.assertIn("cannot find -l%s" % invalid_or_nonexistent_library, stderr)
else:
pass
# Now test if the example can be built with:
# - no additional library (should work)
# - invalid library names (should fail to configure)
# - valid library names but nonexistent libraries (should not create a target)
with open("contrib/borked/CMakeLists.txt", "w", encoding="utf-8") as f:
f.write(
"""
build_lib(
LIBNAME borked
SOURCE_FILES ${PROJECT_SOURCE_DIR}/build-support/empty.cc
LIBRARIES_TO_LINK ${libcore}
)
"""
)
for invalid_or_nonexistent_library in ["", "gsd", "lib", "libfi", "calibre"]:
with open("contrib/borked/examples/CMakeLists.txt", "w", encoding="utf-8") as f:
f.write(
"""
build_lib_example(
NAME borked-example
SOURCE_FILES ${PROJECT_SOURCE_DIR}/build-support/empty-main.cc
LIBRARIES_TO_LINK ${libborked} %s
)
"""
% invalid_or_nonexistent_library
)
return_code, stdout, stderr = run_ns3('configure -G "{generator}"')
if invalid_or_nonexistent_library in ["", "gsd", "libfi", "calibre"]:
self.assertEqual(return_code, 0) # should be able to configure
elif invalid_or_nonexistent_library in ["lib"]:
self.assertEqual(return_code, 1) # should fail to even configure
self.assertIn("Invalid library name: %s" % invalid_or_nonexistent_library, stderr)
else:
pass
return_code, stdout, stderr = run_ns3("build borked-example")
if invalid_or_nonexistent_library in [""]:
self.assertEqual(return_code, 0) # should be able to build
elif invalid_or_nonexistent_library in ["libf"]:
self.assertEqual(return_code, 2) # should fail due to missing configuration
self.assertIn("Invalid library name: %s" % invalid_or_nonexistent_library, stderr)
elif invalid_or_nonexistent_library in ["gsd", "libfi", "calibre"]:
self.assertEqual(return_code, 1) # should fail to find target
self.assertIn("Target to build does not exist: borked-example", stdout)
else:
pass
shutil.rmtree("contrib/borked", ignore_errors=True)
def test_16_LibrariesContainingLib(self):
"""!
Test if CMake can properly handle modules containing "lib",
which is used internally as a prefix for module libraries
@return None
"""
os.makedirs("contrib/calibre", exist_ok=True)
os.makedirs("contrib/calibre/examples", exist_ok=True)
# Now test if we can have a library with "lib" in it
with open("contrib/calibre/examples/CMakeLists.txt", "w", encoding="utf-8") as f:
f.write("")
with open("contrib/calibre/CMakeLists.txt", "w", encoding="utf-8") as f:
f.write(
"""
build_lib(
LIBNAME calibre
SOURCE_FILES ${PROJECT_SOURCE_DIR}/build-support/empty.cc
LIBRARIES_TO_LINK ${libcore}
)
"""
)
return_code, stdout, stderr = run_ns3('configure -G "{generator}"')
# This only checks if configuration passes
self.assertEqual(return_code, 0)
# This checks if the contrib modules were printed correctly
self.assertIn("calibre", stdout)
# This checks not only if "lib" from "calibre" was incorrectly removed,
# but also if the pkgconfig file was generated with the correct name
self.assertNotIn("care", stdout)
self.assertTrue(
os.path.exists(os.path.join(ns3_path, "cmake-cache", "pkgconfig", "ns3-calibre.pc"))
)
# Check if we can build this library
return_code, stdout, stderr = run_ns3("build calibre")
self.assertEqual(return_code, 0)
self.assertIn(cmake_build_target_command(target="calibre"), stdout)
shutil.rmtree("contrib/calibre", ignore_errors=True)
def test_17_CMakePerformanceTracing(self):
"""!
Test if CMake performance tracing works and produces the
cmake_performance_trace.log file
@return None
"""
cmake_performance_trace_log = os.path.join(ns3_path, "cmake_performance_trace.log")
if os.path.exists(cmake_performance_trace_log):
os.remove(cmake_performance_trace_log)
return_code, stdout, stderr = run_ns3("configure --trace-performance")
self.assertEqual(return_code, 0)
if win32:
self.assertIn("--profiling-format=google-trace --profiling-output=", stdout)
else:
self.assertIn(
"--profiling-format=google-trace --profiling-output=./cmake_performance_trace.log",
stdout,
)
self.assertTrue(os.path.exists(cmake_performance_trace_log))
def test_18_CheckBuildVersionAndVersionCache(self):
"""!
Check if ENABLE_BUILD_VERSION and version.cache are working
as expected
@return None
"""
# Create Docker client instance and start it
with DockerContainerManager(self, "ubuntu:22.04") as container:
# Install basic packages
container.execute("apt-get update")
container.execute("apt-get install -y python3 ninja-build cmake g++")
# Clean ns-3 artifacts
container.execute("./ns3 clean")
# Set path to version.cache file
version_cache_file = os.path.join(ns3_path, "src/core/model/version.cache")
# First case: try without a version cache or Git
if os.path.exists(version_cache_file):
os.remove(version_cache_file)
# We need to catch the exception since the command will fail
try:
container.execute("./ns3 configure -G Ninja --enable-build-version")
except DockerException:
pass
self.assertFalse(os.path.exists(os.path.join(ns3_path, "cmake-cache", "build.ninja")))
# Second case: try with a version cache file but without Git (it should succeed)
version_cache_contents = (
"CLOSEST_TAG = '\"ns-3.0.0\"'\n"
"VERSION_COMMIT_HASH = '\"0000000000\"'\n"
"VERSION_DIRTY_FLAG = '0'\n"
"VERSION_MAJOR = '3'\n"
"VERSION_MINOR = '0'\n"
"VERSION_PATCH = '0'\n"
"VERSION_RELEASE_CANDIDATE = '\"\"'\n"
"VERSION_TAG = '\"ns-3.0.0\"'\n"
"VERSION_TAG_DISTANCE = '0'\n"
"VERSION_BUILD_PROFILE = 'debug'\n"
)
with open(version_cache_file, "w", encoding="utf-8") as version:
version.write(version_cache_contents)
# Configuration should now succeed
container.execute("./ns3 clean")
container.execute("./ns3 configure -G Ninja --enable-build-version")
container.execute("./ns3 build core")
self.assertTrue(os.path.exists(os.path.join(ns3_path, "cmake-cache", "build.ninja")))
# And contents of version cache should be unchanged
with open(version_cache_file, "r", encoding="utf-8") as version:
self.assertEqual(version.read(), version_cache_contents)
# Third case: we rename the .git directory temporarily and reconfigure
# to check if it gets configured successfully when Git is found but
# there is not .git history
os.rename(os.path.join(ns3_path, ".git"), os.path.join(ns3_path, "temp_git"))
try:
container.execute("apt-get install -y git")
container.execute("./ns3 clean")
container.execute("./ns3 configure -G Ninja --enable-build-version")
container.execute("./ns3 build core")
except DockerException:
pass
os.rename(os.path.join(ns3_path, "temp_git"), os.path.join(ns3_path, ".git"))
self.assertTrue(os.path.exists(os.path.join(ns3_path, "cmake-cache", "build.ninja")))
# Fourth case: test with Git and git history. Now the version.cache should be replaced.
container.execute("./ns3 clean")
container.execute("./ns3 configure -G Ninja --enable-build-version")
container.execute("./ns3 build core")
self.assertTrue(os.path.exists(os.path.join(ns3_path, "cmake-cache", "build.ninja")))
with open(version_cache_file, "r", encoding="utf-8") as version:
self.assertNotEqual(version.read(), version_cache_contents)
# Remove version cache file if it exists
if os.path.exists(version_cache_file):
os.remove(version_cache_file)
def test_19_FilterModuleExamplesAndTests(self):
"""!
Test filtering in examples and tests from specific modules
@return None
"""
# Try filtering enabled modules to core+network and their dependencies
return_code, stdout, stderr = run_ns3(
'configure -G "{generator}" --enable-examples --enable-tests'
)
self.config_ok(return_code, stdout, stderr)
modules_before_filtering = get_enabled_modules()
programs_before_filtering = get_programs_list()
return_code, stdout, stderr = run_ns3(
"configure -G \"{generator}\" --filter-module-examples-and-tests='core;network'"
)
self.config_ok(return_code, stdout, stderr)
modules_after_filtering = get_enabled_modules()
programs_after_filtering = get_programs_list()
# At this point we should have the same number of modules
self.assertEqual(len(modules_after_filtering), len(modules_before_filtering))
# But less executables
self.assertLess(len(programs_after_filtering), len(programs_before_filtering))
# Try filtering in only core
return_code, stdout, stderr = run_ns3(
"configure -G \"{generator}\" --filter-module-examples-and-tests='core'"
)
self.config_ok(return_code, stdout, stderr)
# At this point we should have the same number of modules
self.assertEqual(len(get_enabled_modules()), len(modules_after_filtering))
# But less executables
self.assertLess(len(get_programs_list()), len(programs_after_filtering))
# Try cleaning the list of enabled modules to reset to the normal configuration.
return_code, stdout, stderr = run_ns3(
"configure -G \"{generator}\" --disable-examples --disable-tests --filter-module-examples-and-tests=''"
)
self.config_ok(return_code, stdout, stderr)
# At this point we should have the same amount of modules that we had when we started.
self.assertEqual(len(get_enabled_modules()), len(self.ns3_modules))
self.assertEqual(len(get_programs_list()), len(self.ns3_executables))
def test_20_CheckFastLinkers(self):
"""!
Check if fast linkers LLD and Mold are correctly found and configured
@return None
"""
run_ns3("clean")
with DockerContainerManager(self, "gcc:12") as container:
# Install basic packages
container.execute("apt-get update")
container.execute("apt-get install -y python3 ninja-build cmake g++ lld")
# Configure should detect and use lld
container.execute("./ns3 configure -G Ninja")
# Check if configuration properly detected lld
self.assertTrue(os.path.exists(os.path.join(ns3_path, "cmake-cache", "build.ninja")))
with open(
os.path.join(ns3_path, "cmake-cache", "build.ninja"), "r", encoding="utf-8"
) as f:
self.assertIn("-fuse-ld=lld", f.read())
# Try to build using the lld linker
try:
container.execute("./ns3 build core")
except DockerException:
self.assertTrue(False, "Build with lld failed")
# Now add mold to the PATH
if not os.path.exists(f"./mold-1.4.2-{arch}-linux.tar.gz"):
container.execute(
f"wget https://github.com/rui314/mold/releases/download/v1.4.2/mold-1.4.2-{arch}-linux.tar.gz"
)
container.execute(
f"tar xzfC mold-1.4.2-{arch}-linux.tar.gz /usr/local --strip-components=1"
)
# Configure should detect and use mold
run_ns3("clean")
container.execute("./ns3 configure -G Ninja")
# Check if configuration properly detected mold
self.assertTrue(os.path.exists(os.path.join(ns3_path, "cmake-cache", "build.ninja")))
with open(
os.path.join(ns3_path, "cmake-cache", "build.ninja"), "r", encoding="utf-8"
) as f:
self.assertIn("-fuse-ld=mold", f.read())
# Try to build using the lld linker
try:
container.execute("./ns3 build core")
except DockerException:
self.assertTrue(False, "Build with mold failed")
# Delete mold leftovers
os.remove(f"./mold-1.4.2-{arch}-linux.tar.gz")
# Disable use of fast linkers
container.execute("./ns3 configure -G Ninja -- -DNS3_FAST_LINKERS=OFF")
# Check if configuration properly disabled lld/mold usage
self.assertTrue(os.path.exists(os.path.join(ns3_path, "cmake-cache", "build.ninja")))
with open(
os.path.join(ns3_path, "cmake-cache", "build.ninja"), "r", encoding="utf-8"
) as f:
self.assertNotIn("-fuse-ld=mold", f.read())
def test_21_ClangTimeTrace(self):
"""!
Check if NS3_CLANG_TIMETRACE feature is working
Clang's -ftime-trace plus ClangAnalyzer report
@return None
"""
run_ns3("clean")
with DockerContainerManager(self, "ubuntu:24.04") as container:
container.execute("apt-get update")
container.execute("apt-get install -y python3 ninja-build cmake clang-18")
# Enable ClangTimeTrace without git (it should fail)
try:
container.execute(
"./ns3 configure -G Ninja --enable-modules=core --enable-examples --enable-tests -- -DCMAKE_CXX_COMPILER=/usr/bin/clang++-18 -DNS3_CLANG_TIMETRACE=ON"
)
except DockerException as e:
self.assertIn("could not find git for clone of ClangBuildAnalyzer", e.stderr)
container.execute("apt-get install -y git")
# Enable ClangTimeTrace without git (it should succeed)
try:
container.execute(
"./ns3 configure -G Ninja --enable-modules=core --enable-examples --enable-tests -- -DCMAKE_CXX_COMPILER=/usr/bin/clang++-18 -DNS3_CLANG_TIMETRACE=ON"
)
except DockerException as e:
self.assertIn("could not find git for clone of ClangBuildAnalyzer", e.stderr)
# Clean leftover time trace report
time_trace_report_path = os.path.join(ns3_path, "ClangBuildAnalyzerReport.txt")
if os.path.exists(time_trace_report_path):
os.remove(time_trace_report_path)
# Build new time trace report
try:
container.execute("./ns3 build timeTraceReport")
except DockerException as e:
self.assertTrue(False, "Failed to build the ClangAnalyzer's time trace report")
# Check if the report exists
self.assertTrue(os.path.exists(time_trace_report_path))
# Now try with GCC, which should fail during the configuration
run_ns3("clean")
container.execute("apt-get install -y g++")
container.execute("apt-get remove -y clang-18")
try:
container.execute(
"./ns3 configure -G Ninja --enable-modules=core --enable-examples --enable-tests -- -DNS3_CLANG_TIMETRACE=ON"
)
self.assertTrue(
False, "ClangTimeTrace requires Clang, but GCC just passed the checks too"
)
except DockerException as e:
self.assertIn("TimeTrace is a Clang feature", e.stderr)
def test_22_NinjaTrace(self):
"""!
Check if NS3_NINJA_TRACE feature is working
Ninja's .ninja_log conversion to about://tracing
json format conversion with Ninjatracing
@return None
"""
run_ns3("clean")
with DockerContainerManager(self, "ubuntu:24.04") as container:
container.execute("apt-get update")
container.execute("apt-get remove -y g++")
container.execute("apt-get install -y python3 cmake g++-11 clang-18")
# Enable Ninja tracing without using the Ninja generator
try:
container.execute(
"./ns3 configure --enable-modules=core --enable-ninja-tracing -- -DCMAKE_CXX_COMPILER=/usr/bin/clang++-18"
)
except DockerException as e:
self.assertIn("Ninjatracing requires the Ninja generator", e.stderr)
# Clean build system leftovers
run_ns3("clean")
container.execute("apt-get install -y ninja-build")
# Enable Ninjatracing support without git (should fail)
try:
container.execute(
"./ns3 configure -G Ninja --enable-modules=core --enable-ninja-tracing -- -DCMAKE_CXX_COMPILER=/usr/bin/clang++-18"
)
except DockerException as e:
self.assertIn("could not find git for clone of NinjaTracing", e.stderr)
container.execute("apt-get install -y git")
# Enable Ninjatracing support with git (it should succeed)
try:
container.execute(
"./ns3 configure -G Ninja --enable-modules=core --enable-ninja-tracing -- -DCMAKE_CXX_COMPILER=/usr/bin/clang++-18"
)
except DockerException as e:
self.assertTrue(False, "Failed to configure with Ninjatracing")
# Clean leftover ninja trace
ninja_trace_path = os.path.join(ns3_path, "ninja_performance_trace.json")
if os.path.exists(ninja_trace_path):
os.remove(ninja_trace_path)
# Build the core module
container.execute("./ns3 build core")
# Build new ninja trace
try:
container.execute("./ns3 build ninjaTrace")
except DockerException as e:
self.assertTrue(False, "Failed to run Ninjatracing's tool to build the trace")
# Check if the report exists
self.assertTrue(os.path.exists(ninja_trace_path))
trace_size = os.stat(ninja_trace_path).st_size
os.remove(ninja_trace_path)
run_ns3("clean")
# Enable Clang TimeTrace feature for more detailed traces
try:
container.execute(
"./ns3 configure -G Ninja --enable-modules=core --enable-ninja-tracing -- -DCMAKE_CXX_COMPILER=/usr/bin/clang++-18 -DNS3_CLANG_TIMETRACE=ON"
)
except DockerException as e:
self.assertTrue(False, "Failed to configure Ninjatracing with Clang's TimeTrace")
# Build the core module
container.execute("./ns3 build core")
# Build new ninja trace
try:
container.execute("./ns3 build ninjaTrace")
except DockerException as e:
self.assertTrue(False, "Failed to run Ninjatracing's tool to build the trace")
self.assertTrue(os.path.exists(ninja_trace_path))
timetrace_size = os.stat(ninja_trace_path).st_size
os.remove(ninja_trace_path)
# Check if timetrace's trace is bigger than the original trace (it should be)
self.assertGreater(timetrace_size, trace_size)
def test_23_PrecompiledHeaders(self):
"""!
Check if precompiled headers are being enabled correctly.
@return None
"""
run_ns3("clean")
# Ubuntu 22.04 ships with:
# - cmake 3.22: does support PCH
# - ccache 4.5: compatible with pch
with DockerContainerManager(self, "ubuntu:22.04") as container:
container.execute("apt-get update")
container.execute("apt-get install -y python3 cmake ccache g++")
try:
container.execute("./ns3 configure")
except DockerException as e:
self.assertTrue(False, "Precompiled headers should have been enabled")
def test_24_CheckTestSettings(self):
"""!
Check for regressions in test object build.
@return None
"""
return_code, stdout, stderr = run_ns3("configure")
self.assertEqual(return_code, 0)
test_module_cache = os.path.join(ns3_path, "cmake-cache", "src", "test")
self.assertFalse(os.path.exists(test_module_cache))
return_code, stdout, stderr = run_ns3("configure --enable-tests")
self.assertEqual(return_code, 0)
self.assertTrue(os.path.exists(test_module_cache))
def test_25_CheckBareConfig(self):
"""!
Check for regressions in a bare ns-3 configuration.
@return None
"""
run_ns3("clean")
with DockerContainerManager(self, "ubuntu:22.04") as container:
container.execute("apt-get update")
container.execute("apt-get install -y python3 cmake g++")
return_code = 0
stdout = ""
try:
stdout = container.execute("./ns3 configure -d release")
except DockerException as e:
return_code = 1
self.config_ok(return_code, stdout, stdout)
run_ns3("clean")
class NS3BuildBaseTestCase(NS3BaseTestCase):
"""!
Tests ns3 regarding building the project
"""
def setUp(self):
"""!
Reuse cleaning/release configuration from NS3BaseTestCase if flag is cleaned
@return None
"""
super().setUp()
self.ns3_libraries = get_libraries_list()
def test_01_BuildExistingTargets(self):
"""!
Try building the core library
@return None
"""
return_code, stdout, stderr = run_ns3("build core")
self.assertEqual(return_code, 0)
self.assertIn("Built target core", stdout)
def test_02_BuildNonExistingTargets(self):
"""!
Try building core-test library without tests enabled
@return None
"""
# tests are not enabled, so the target isn't available
return_code, stdout, stderr = run_ns3("build core-test")
self.assertEqual(return_code, 1)
self.assertIn("Target to build does not exist: core-test", stdout)
def test_03_BuildProject(self):
"""!
Try building the project:
@return None
"""
return_code, stdout, stderr = run_ns3("build")
self.assertEqual(return_code, 0)
self.assertIn("Built target", stdout)
for program in get_programs_list():
self.assertTrue(os.path.exists(program), program)
self.assertIn(cmake_build_project_command, stdout)
def test_04_BuildProjectNoTaskLines(self):
"""!
Try hiding task lines
@return None
"""
return_code, stdout, stderr = run_ns3("--quiet build")
self.assertEqual(return_code, 0)
self.assertIn(cmake_build_project_command, stdout)
def test_05_BreakBuild(self):
"""!
Try removing an essential file to break the build
@return None
"""
# change an essential file to break the build.
attribute_cc_path = os.sep.join([ns3_path, "src", "core", "model", "attribute.cc"])
attribute_cc_bak_path = attribute_cc_path + ".bak"
shutil.move(attribute_cc_path, attribute_cc_bak_path)
# build should break.
return_code, stdout, stderr = run_ns3("build")
self.assertNotEqual(return_code, 0)
# move file back.
shutil.move(attribute_cc_bak_path, attribute_cc_path)
# Build should work again.
return_code, stdout, stderr = run_ns3("build")
self.assertEqual(return_code, 0)
def test_06_TestVersionFile(self):
"""!
Test if changing the version file affects the library names
@return None
"""
run_ns3("build")
self.ns3_libraries = get_libraries_list()
version_file = os.sep.join([ns3_path, "VERSION"])
with open(version_file, "w", encoding="utf-8") as f:
f.write("3-00\n")
# Reconfigure.
return_code, stdout, stderr = run_ns3('configure -G "{generator}"')
self.config_ok(return_code, stdout, stderr)
# Build.
return_code, stdout, stderr = run_ns3("build")
self.assertEqual(return_code, 0)
self.assertIn("Built target", stdout)
# Programs with new versions.
new_programs = get_programs_list()
# Check if they exist.
for program in new_programs:
self.assertTrue(os.path.exists(program))
# Check if we still have the same number of binaries.
self.assertEqual(len(new_programs), len(self.ns3_executables))
# Check if versions changed from 3-dev to 3-00.
libraries = get_libraries_list()
new_libraries = list(set(libraries).difference(set(self.ns3_libraries)))
self.assertEqual(len(new_libraries), len(self.ns3_libraries))
for library in new_libraries:
self.assertNotIn("libns3-dev", library)
self.assertIn("libns3-00", library)
self.assertTrue(os.path.exists(library))
# Restore version file.
with open(version_file, "w", encoding="utf-8") as f:
f.write("3-dev\n")
def test_07_OutputDirectory(self):
"""!
Try setting a different output directory and if everything is
in the right place and still working correctly
@return None
"""
# Re-build to return to the original state.
return_code, stdout, stderr = run_ns3("build")
self.assertEqual(return_code, 0)
## ns3_libraries holds a list of built module libraries # noqa
self.ns3_libraries = get_libraries_list()
## ns3_executables holds a list of executables in .lock-ns3 # noqa
self.ns3_executables = get_programs_list()
# Delete built programs and libraries to check if they were restored later.
for program in self.ns3_executables:
os.remove(program)
for library in self.ns3_libraries:
os.remove(library)
# Reconfigure setting the output folder to ns-3-dev/build/release (both as an absolute path or relative).
absolute_path = os.sep.join([ns3_path, "build", "release"])
relative_path = os.sep.join(["build", "release"])
for different_out_dir in [absolute_path, relative_path]:
return_code, stdout, stderr = run_ns3(
'configure -G "{generator}" --out=%s' % different_out_dir
)
self.config_ok(return_code, stdout, stderr)
self.assertIn(
"Build directory : %s" % absolute_path.replace(os.sep, "/"), stdout
)
# Build
run_ns3("build")
# Check if we have the same number of binaries and that they were built correctly.
new_programs = get_programs_list()
self.assertEqual(len(new_programs), len(self.ns3_executables))
for program in new_programs:
self.assertTrue(os.path.exists(program))
# Check if we have the same number of libraries and that they were built correctly.
libraries = get_libraries_list(os.sep.join([absolute_path, "lib"]))
new_libraries = list(set(libraries).difference(set(self.ns3_libraries)))
self.assertEqual(len(new_libraries), len(self.ns3_libraries))
for library in new_libraries:
self.assertTrue(os.path.exists(library))
# Remove files in the different output dir.
shutil.rmtree(absolute_path)
# Restore original output directory.
return_code, stdout, stderr = run_ns3("configure -G \"{generator}\" --out=''")
self.config_ok(return_code, stdout, stderr)
self.assertIn(
"Build directory : %s" % usual_outdir.replace(os.sep, "/"), stdout
)
# Try re-building.
run_ns3("build")
# Check if we have the same binaries we had at the beginning.
new_programs = get_programs_list()
self.assertEqual(len(new_programs), len(self.ns3_executables))
for program in new_programs:
self.assertTrue(os.path.exists(program))
# Check if we have the same libraries we had at the beginning.
libraries = get_libraries_list()
self.assertEqual(len(libraries), len(self.ns3_libraries))
for library in libraries:
self.assertTrue(os.path.exists(library))
def test_08_InstallationAndUninstallation(self):
"""!
Tries setting a ns3 version, then installing it.
After that, tries searching for ns-3 with CMake's find_package(ns3).
Finally, tries using core library in a 3rd-party project
@return None
"""
# Remove existing libraries from the previous step.
libraries = get_libraries_list()
for library in libraries:
os.remove(library)
# 3-dev version format is not supported by CMake, so we use 3.01.
version_file = os.sep.join([ns3_path, "VERSION"])
with open(version_file, "w", encoding="utf-8") as f:
f.write("3-01\n")
# Reconfigure setting the installation folder to ns-3-dev/build/install.
install_prefix = os.sep.join([ns3_path, "build", "install"])
return_code, stdout, stderr = run_ns3(
'configure -G "{generator}" --prefix=%s' % install_prefix
)
self.config_ok(return_code, stdout, stderr)
# Build.
run_ns3("build")
libraries = get_libraries_list()
headers = get_headers_list()
# Install.
run_ns3("install")
# Find out if libraries were installed to lib or lib64 (Fedora thing).
lib64 = os.path.exists(os.sep.join([install_prefix, "lib64"]))
installed_libdir = os.sep.join([install_prefix, ("lib64" if lib64 else "lib")])
# Make sure all libraries were installed.
installed_libraries = get_libraries_list(installed_libdir)
installed_libraries_list = ";".join(installed_libraries)
for library in libraries:
library_name = os.path.basename(library)
self.assertIn(library_name, installed_libraries_list)
# Make sure all headers were installed.
installed_headers = get_headers_list(install_prefix)
missing_headers = list(
set([os.path.basename(x) for x in headers])
- (set([os.path.basename(x) for x in installed_headers]))
)
self.assertEqual(len(missing_headers), 0)
# Now create a test CMake project and try to find_package ns-3.
test_main_file = os.sep.join([install_prefix, "main.cpp"])
with open(test_main_file, "w", encoding="utf-8") as f:
f.write(
"""
#include <ns3/core-module.h>
using namespace ns3;
int main ()
{
Simulator::Stop (Seconds (1.0));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
"""
)
# We try to use this library without specifying a version,
# specifying ns3-01 (text version with 'dev' is not supported)
# and specifying ns3-00 (a wrong version)
for version in ["", "3.01", "3.00"]:
ns3_import_methods = []
# Import ns-3 libraries with as a CMake package
cmake_find_package_import = """
list(APPEND CMAKE_PREFIX_PATH ./{lib}/cmake/ns3)
find_package(ns3 {version} COMPONENTS core)
target_link_libraries(test PRIVATE ns3::core)
""".format(
lib=("lib64" if lib64 else "lib"), version=version
)
ns3_import_methods.append(cmake_find_package_import)
# Import ns-3 as pkg-config libraries
pkgconfig_import = """
list(APPEND CMAKE_PREFIX_PATH ./)
include(FindPkgConfig)
pkg_check_modules(ns3 REQUIRED IMPORTED_TARGET ns3-core{version})
target_link_libraries(test PUBLIC PkgConfig::ns3)
""".format(
lib=("lib64" if lib64 else "lib"), version="=" + version if version else ""
)
if shutil.which("pkg-config"):
ns3_import_methods.append(pkgconfig_import)
# Test the multiple ways of importing ns-3 libraries
for import_method in ns3_import_methods:
test_cmake_project = (
"""
cmake_minimum_required(VERSION 3.20..3.20)
project(ns3_consumer CXX)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(test main.cpp)
"""
+ import_method
)
test_cmake_project_file = os.sep.join([install_prefix, "CMakeLists.txt"])
with open(test_cmake_project_file, "w", encoding="utf-8") as f:
f.write(test_cmake_project)
# Configure the test project
cmake = shutil.which("cmake")
return_code, stdout, stderr = run_program(
cmake,
'-DCMAKE_BUILD_TYPE=debug -G"{generator}" .'.format(
generator=platform_makefiles
),
cwd=install_prefix,
)
if version == "3.00":
self.assertEqual(return_code, 1)
if import_method == cmake_find_package_import:
self.assertIn(
'Could not find a configuration file for package "ns3" that is compatible',
stderr.replace("\n", ""),
)
elif import_method == pkgconfig_import:
self.assertIn("not found", stderr.replace("\n", ""))
else:
raise Exception("Unknown import type")
else:
self.assertEqual(return_code, 0)
self.assertIn("Build files", stdout)
# Build the test project making use of import ns-3
return_code, stdout, stderr = run_program("cmake", "--build .", cwd=install_prefix)
if version == "3.00":
self.assertEqual(return_code, 2, msg=stdout + stderr)
self.assertGreater(len(stderr), 0)
else:
self.assertEqual(return_code, 0)
self.assertIn("Built target", stdout)
# Try running the test program that imports ns-3
if win32:
test_program = os.path.join(install_prefix, "test.exe")
env_sep = ";" if ";" in os.environ["PATH"] else ":"
env = {
"PATH": env_sep.join(
[os.environ["PATH"], os.path.join(install_prefix, "lib")]
)
}
else:
test_program = "./test"
env = None
return_code, stdout, stderr = run_program(
test_program, "", cwd=install_prefix, env=env
)
self.assertEqual(return_code, 0)
# Uninstall
return_code, stdout, stderr = run_ns3("uninstall")
self.assertIn("Built target uninstall", stdout)
# Restore 3-dev version file
os.remove(version_file)
with open(version_file, "w", encoding="utf-8") as f:
f.write("3-dev\n")
def test_09_Scratches(self):
"""!
Tries to build scratch-simulator and subdir/scratch-simulator-subdir
@return None
"""
# Build.
targets = {
"scratch/scratch-simulator": "scratch-simulator",
"scratch/scratch-simulator.cc": "scratch-simulator",
"scratch-simulator": "scratch-simulator",
"scratch/subdir/scratch-subdir": "subdir_scratch-subdir",
"subdir/scratch-subdir": "subdir_scratch-subdir",
"scratch-subdir": "subdir_scratch-subdir",
}
for target_to_run, target_cmake in targets.items():
# Test if build is working.
build_line = "target scratch_%s" % target_cmake
return_code, stdout, stderr = run_ns3("build %s" % target_to_run)
self.assertEqual(return_code, 0)
self.assertIn(build_line, stdout)
# Test if run is working
return_code, stdout, stderr = run_ns3("run %s --verbose" % target_to_run)
self.assertEqual(return_code, 0)
self.assertIn(build_line, stdout)
stdout = stdout.replace("scratch_%s" % target_cmake, "") # remove build lines
self.assertIn(target_to_run.split("/")[-1].replace(".cc", ""), stdout)
def test_10_AmbiguityCheck(self):
"""!
Test if ns3 can alert correctly in case a shortcut collision happens
@return None
"""
# First enable examples
return_code, stdout, stderr = run_ns3('configure -G "{generator}" --enable-examples')
self.assertEqual(return_code, 0)
# Copy second.cc from the tutorial examples to the scratch folder
shutil.copy("./examples/tutorial/second.cc", "./scratch/second.cc")
# Reconfigure to re-scan the scratches
return_code, stdout, stderr = run_ns3('configure -G "{generator}" --enable-examples')
self.assertEqual(return_code, 0)
# Try to run second and collide
return_code, stdout, stderr = run_ns3("build second")
self.assertEqual(return_code, 1)
self.assertIn(
'Build target "second" is ambiguous. Try one of these: "scratch/second", "examples/tutorial/second"',
stdout.replace(os.sep, "/"),
)
# Try to run scratch/second and succeed
return_code, stdout, stderr = run_ns3("build scratch/second")
self.assertEqual(return_code, 0)
self.assertIn(cmake_build_target_command(target="scratch_second"), stdout)
# Try to run scratch/second and succeed
return_code, stdout, stderr = run_ns3("build tutorial/second")
self.assertEqual(return_code, 0)
self.assertIn(cmake_build_target_command(target="second"), stdout)
# Try to run second and collide
return_code, stdout, stderr = run_ns3("run second")
self.assertEqual(return_code, 1)
self.assertIn(
'Run target "second" is ambiguous. Try one of these: "scratch/second", "examples/tutorial/second"',
stdout.replace(os.sep, "/"),
)
# Try to run scratch/second and succeed
return_code, stdout, stderr = run_ns3("run scratch/second")
self.assertEqual(return_code, 0)
# Try to run scratch/second and succeed
return_code, stdout, stderr = run_ns3("run tutorial/second")
self.assertEqual(return_code, 0)
# Remove second
os.remove("./scratch/second.cc")
def test_11_StaticBuilds(self):
"""!
Test if we can build a static ns-3 library and link it to static programs
@return None
"""
if (not win32) and (arch == "aarch64"):
if platform.libc_ver()[0] == "glibc":
from packaging.version import Version
if Version(platform.libc_ver()[1]) < Version("2.37"):
self.skipTest(
"Static linking on ARM64 requires glibc 2.37 where fPIC was enabled (fpic is limited in number of GOT entries)"
)
# First enable examples and static build
return_code, stdout, stderr = run_ns3(
'configure -G "{generator}" --enable-examples --disable-gtk --enable-static'
)
if win32:
# Configuration should fail explaining Windows
# socket libraries cannot be statically linked
self.assertEqual(return_code, 1)
self.assertIn("Static builds are unsupported on Windows", stderr)
else:
# If configuration passes, we are half way done
self.assertEqual(return_code, 0)
# Then try to build one example
return_code, stdout, stderr = run_ns3("build sample-simulator")
self.assertEqual(return_code, 0)
self.assertIn("Built target", stdout)
# Maybe check the built binary for shared library references? Using objdump, otool, etc
def test_12_CppyyBindings(self):
"""!
Test if we can use python bindings
@return None
"""
try:
import cppyy
except ModuleNotFoundError:
self.skipTest("Cppyy was not found")
# First enable examples and static build
return_code, stdout, stderr = run_ns3(
'configure -G "{generator}" --enable-examples --enable-python-bindings'
)
# If configuration passes, we are half way done
self.assertEqual(return_code, 0)
# Then build and run tests
return_code, stdout, stderr = run_program("test.py", "", python=True)
self.assertEqual(return_code, 0)
# Then try to run a specific test
return_code, stdout, stderr = run_program("test.py", "-p mixed-wired-wireless", python=True)
self.assertEqual(return_code, 0)
# Then try to run a specific test with the full relative path
return_code, stdout, stderr = run_program(
"test.py", "-p ./examples/wireless/mixed-wired-wireless", python=True
)
self.assertEqual(return_code, 0)
def test_13_FetchOptionalComponents(self):
"""!
Test if we had regressions with brite, click and openflow modules
that depend on homonymous libraries
@return None
"""
if shutil.which("git") is None:
self.skipTest("Missing git")
if win32:
self.skipTest("Optional components are not supported on Windows")
# First enable automatic components fetching
return_code, stdout, stderr = run_ns3("configure -- -DNS3_FETCH_OPTIONAL_COMPONENTS=ON")
self.assertEqual(return_code, 0)
# Build the optional components to check if their dependencies were fetched
# and there were no build regressions
return_code, stdout, stderr = run_ns3("build brite click openflow")
self.assertEqual(return_code, 0)
def test_14_LinkContribModuleToSrcModule(self):
"""!
Test if we can link contrib modules to src modules
@return None
"""
if shutil.which("git") is None:
self.skipTest("Missing git")
destination_contrib = os.path.join(ns3_path, "contrib/test-contrib-dependency")
destination_src = os.path.join(ns3_path, "src/test-src-dependent-on-contrib")
# Remove pre-existing directories
if os.path.exists(destination_contrib):
shutil.rmtree(destination_contrib)
if os.path.exists(destination_src):
shutil.rmtree(destination_src)
# Always use a fresh copy
shutil.copytree(
os.path.join(ns3_path, "build-support/test-files/test-contrib-dependency"),
destination_contrib,
)
shutil.copytree(
os.path.join(ns3_path, "build-support/test-files/test-src-dependent-on-contrib"),
destination_src,
)
# Then configure
return_code, stdout, stderr = run_ns3("configure --enable-examples")
self.assertEqual(return_code, 0)
# Build the src module that depend on a contrib module
return_code, stdout, stderr = run_ns3("run source-example")
self.assertEqual(return_code, 0)
# Remove module copies
shutil.rmtree(destination_contrib)
shutil.rmtree(destination_src)
class NS3ExpectedUseTestCase(NS3BaseTestCase):
"""!
Tests ns3 usage in more realistic scenarios
"""
def setUp(self):
"""!
Reuse cleaning/release configuration from NS3BaseTestCase if flag is cleaned
Here examples, tests and documentation are also enabled.
@return None
"""
super().setUp()
# On top of the release build configured by NS3ConfigureTestCase, also enable examples, tests and docs.
return_code, stdout, stderr = run_ns3(
'configure -d release -G "{generator}" --enable-examples --enable-tests'
)
self.config_ok(return_code, stdout, stderr)
# Check if .lock-ns3 exists, then read to get list of executables.
self.assertTrue(os.path.exists(ns3_lock_filename))
## ns3_executables holds a list of executables in .lock-ns3 # noqa
self.ns3_executables = get_programs_list()
# Check if .lock-ns3 exists than read to get the list of enabled modules.
self.assertTrue(os.path.exists(ns3_lock_filename))
## ns3_modules holds a list to the modules enabled stored in .lock-ns3 # noqa
self.ns3_modules = get_enabled_modules()
def test_01_BuildProject(self):
"""!
Try to build the project
@return None
"""
return_code, stdout, stderr = run_ns3("build")
self.assertEqual(return_code, 0)
self.assertIn("Built target", stdout)
for program in get_programs_list():
self.assertTrue(os.path.exists(program))
libraries = get_libraries_list()
for module in get_enabled_modules():
self.assertIn(module.replace("ns3-", ""), ";".join(libraries))
self.assertIn(cmake_build_project_command, stdout)
def test_02_BuildAndRunExistingExecutableTarget(self):
"""!
Try to build and run test-runner
@return None
"""
return_code, stdout, stderr = run_ns3('run "test-runner --list" --verbose')
self.assertEqual(return_code, 0)
self.assertIn("Built target test-runner", stdout)
self.assertIn(cmake_build_target_command(target="test-runner"), stdout)
def test_03_BuildAndRunExistingLibraryTarget(self):
"""!
Try to build and run a library
@return None
"""
return_code, stdout, stderr = run_ns3("run core") # this should not work
self.assertEqual(return_code, 1)
self.assertIn("Couldn't find the specified program: core", stderr)
def test_04_BuildAndRunNonExistingTarget(self):
"""!
Try to build and run an unknown target
@return None
"""
return_code, stdout, stderr = run_ns3("run nonsense") # this should not work
self.assertEqual(return_code, 1)
self.assertIn("Couldn't find the specified program: nonsense", stderr)
def test_05_RunNoBuildExistingExecutableTarget(self):
"""!
Try to run test-runner without building
@return None
"""
return_code, stdout, stderr = run_ns3("build test-runner")
self.assertEqual(return_code, 0)
return_code, stdout, stderr = run_ns3('run "test-runner --list" --no-build --verbose')
self.assertEqual(return_code, 0)
self.assertNotIn("Built target test-runner", stdout)
self.assertNotIn(cmake_build_target_command(target="test-runner"), stdout)
def test_06_RunNoBuildExistingLibraryTarget(self):
"""!
Test ns3 fails to run a library
@return None
"""
return_code, stdout, stderr = run_ns3("run core --no-build") # this should not work
self.assertEqual(return_code, 1)
self.assertIn("Couldn't find the specified program: core", stderr)
def test_07_RunNoBuildNonExistingExecutableTarget(self):
"""!
Test ns3 fails to run an unknown program
@return None
"""
return_code, stdout, stderr = run_ns3("run nonsense --no-build") # this should not work
self.assertEqual(return_code, 1)
self.assertIn("Couldn't find the specified program: nonsense", stderr)
def test_08_RunNoBuildGdb(self):
"""!
Test if scratch simulator is executed through gdb and lldb
@return None
"""
if shutil.which("gdb") is None:
self.skipTest("Missing gdb")
return_code, stdout, stderr = run_ns3("build scratch-simulator")
self.assertEqual(return_code, 0)
return_code, stdout, stderr = run_ns3(
"run scratch-simulator --gdb --verbose --no-build", env={"gdb_eval": "1"}
)
self.assertEqual(return_code, 0)
self.assertIn("scratch-simulator", stdout)
if win32:
self.assertIn("GNU gdb", stdout)
else:
self.assertIn("No debugging symbols found", stdout)
def test_09_RunNoBuildValgrind(self):
"""!
Test if scratch simulator is executed through valgrind
@return None
"""
if shutil.which("valgrind") is None:
self.skipTest("Missing valgrind")
return_code, stdout, stderr = run_ns3("build scratch-simulator")
self.assertEqual(return_code, 0)
return_code, stdout, stderr = run_ns3(
"run scratch-simulator --valgrind --verbose --no-build"
)
self.assertEqual(return_code, 0)
self.assertIn("scratch-simulator", stderr)
self.assertIn("Memcheck", stderr)
def test_10_DoxygenWithBuild(self):
"""!
Test the doxygen target that does trigger a full build
@return None
"""
if shutil.which("doxygen") is None:
self.skipTest("Missing doxygen")
if shutil.which("bash") is None:
self.skipTest("Missing bash")
doc_folder = os.path.abspath(os.sep.join([".", "doc"]))
doxygen_files = ["introspected-command-line.h", "introspected-doxygen.h"]
for filename in doxygen_files:
file_path = os.sep.join([doc_folder, filename])
if os.path.exists(file_path):
os.remove(file_path)
# Rebuilding dot images is super slow, so not removing doxygen products
# doxygen_build_folder = os.sep.join([doc_folder, "html"])
# if os.path.exists(doxygen_build_folder):
# shutil.rmtree(doxygen_build_folder)
return_code, stdout, stderr = run_ns3("docs doxygen")
self.assertEqual(return_code, 0)
self.assertIn(cmake_build_target_command(target="doxygen"), stdout)
self.assertIn("Built target doxygen", stdout)
def test_11_DoxygenWithoutBuild(self):
"""!
Test the doxygen target that doesn't trigger a full build
@return None
"""
if shutil.which("doxygen") is None:
self.skipTest("Missing doxygen")
# Rebuilding dot images is super slow, so not removing doxygen products
# doc_folder = os.path.abspath(os.sep.join([".", "doc"]))
# doxygen_build_folder = os.sep.join([doc_folder, "html"])
# if os.path.exists(doxygen_build_folder):
# shutil.rmtree(doxygen_build_folder)
return_code, stdout, stderr = run_ns3("docs doxygen-no-build")
self.assertEqual(return_code, 0)
self.assertIn(cmake_build_target_command(target="doxygen-no-build"), stdout)
self.assertIn("Built target doxygen-no-build", stdout)
def test_12_SphinxDocumentation(self):
"""!
Test every individual target for Sphinx-based documentation
@return None
"""
if shutil.which("sphinx-build") is None:
self.skipTest("Missing sphinx")
doc_folder = os.path.abspath(os.sep.join([".", "doc"]))
# For each sphinx doc target.
for target in ["installation", "contributing", "manual", "models", "tutorial"]:
# First we need to clean old docs, or it will not make any sense.
doc_build_folder = os.sep.join([doc_folder, target, "build"])
doc_temp_folder = os.sep.join([doc_folder, target, "source-temp"])
if os.path.exists(doc_build_folder):
shutil.rmtree(doc_build_folder)
if os.path.exists(doc_temp_folder):
shutil.rmtree(doc_temp_folder)
# Build
return_code, stdout, stderr = run_ns3("docs %s" % target)
self.assertEqual(return_code, 0, target)
self.assertIn(cmake_build_target_command(target="sphinx_%s" % target), stdout)
self.assertIn("Built target sphinx_%s" % target, stdout)
# Check if the docs output folder exists
doc_build_folder = os.sep.join([doc_folder, target, "build"])
self.assertTrue(os.path.exists(doc_build_folder))
# Check if the all the different types are in place (latex, split HTML and single page HTML)
for build_type in ["latex", "html", "singlehtml"]:
self.assertTrue(os.path.exists(os.sep.join([doc_build_folder, build_type])))
def test_13_Documentation(self):
"""!
Test the documentation target that builds
both doxygen and sphinx based documentation
@return None
"""
if shutil.which("doxygen") is None:
self.skipTest("Missing doxygen")
if shutil.which("sphinx-build") is None:
self.skipTest("Missing sphinx")
doc_folder = os.path.abspath(os.sep.join([".", "doc"]))
# First we need to clean old docs, or it will not make any sense.
# Rebuilding dot images is super slow, so not removing doxygen products
# doxygen_build_folder = os.sep.join([doc_folder, "html"])
# if os.path.exists(doxygen_build_folder):
# shutil.rmtree(doxygen_build_folder)
for target in ["manual", "models", "tutorial"]:
doc_build_folder = os.sep.join([doc_folder, target, "build"])
if os.path.exists(doc_build_folder):
shutil.rmtree(doc_build_folder)
return_code, stdout, stderr = run_ns3("docs all")
self.assertEqual(return_code, 0)
self.assertIn(cmake_build_target_command(target="sphinx"), stdout)
self.assertIn("Built target sphinx", stdout)
self.assertIn(cmake_build_target_command(target="doxygen"), stdout)
self.assertIn("Built target doxygen", stdout)
def test_14_EnableSudo(self):
"""!
Try to set ownership of scratch-simulator from current user to root,
and change execution permissions
@return None
"""
# Test will be skipped if not defined
sudo_password = os.getenv("SUDO_PASSWORD", None)
# Skip test if variable containing sudo password is the default value
if sudo_password is None:
self.skipTest("SUDO_PASSWORD environment variable was not specified")
enable_sudo = read_lock_entry("ENABLE_SUDO")
self.assertFalse(enable_sudo is True)
# First we run to ensure the program was built
return_code, stdout, stderr = run_ns3("run scratch-simulator")
self.assertEqual(return_code, 0)
self.assertIn("Built target scratch_scratch-simulator", stdout)
self.assertIn(cmake_build_target_command(target="scratch_scratch-simulator"), stdout)
scratch_simulator_path = list(
filter(lambda x: x if "scratch-simulator" in x else None, self.ns3_executables)
)[-1]
prev_fstat = os.stat(scratch_simulator_path) # we get the permissions before enabling sudo
# Now try setting the sudo bits from the run subparser
return_code, stdout, stderr = run_ns3(
"run scratch-simulator --enable-sudo", env={"SUDO_PASSWORD": sudo_password}
)
self.assertEqual(return_code, 0)
self.assertIn("Built target scratch_scratch-simulator", stdout)
self.assertIn(cmake_build_target_command(target="scratch_scratch-simulator"), stdout)
fstat = os.stat(scratch_simulator_path)
import stat
# If we are on Windows, these permissions mean absolutely nothing,
# and on Fuse builds they might not make any sense, so we need to skip before failing
likely_fuse_mount = (
(prev_fstat.st_mode & stat.S_ISUID) == (fstat.st_mode & stat.S_ISUID)
) and prev_fstat.st_uid == 0 # noqa
if win32 or likely_fuse_mount:
self.skipTest("Windows or likely a FUSE mount")
# If this is a valid platform, we can continue
self.assertEqual(fstat.st_uid, 0) # check the file was correctly chown'ed by root
self.assertEqual(
fstat.st_mode & stat.S_ISUID, stat.S_ISUID
) # check if normal users can run as sudo
# Now try setting the sudo bits as a post-build step (as set by configure subparser)
return_code, stdout, stderr = run_ns3("configure --enable-sudo")
self.assertEqual(return_code, 0)
# Check if it was properly set in the lock file
enable_sudo = read_lock_entry("ENABLE_SUDO")
self.assertTrue(enable_sudo)
# Remove old executables
for executable in self.ns3_executables:
if os.path.exists(executable):
os.remove(executable)
# Try to build and then set sudo bits as a post-build step
return_code, stdout, stderr = run_ns3("build", env={"SUDO_PASSWORD": sudo_password})
self.assertEqual(return_code, 0)
# Check if commands are being printed for every target
self.assertIn("chown root", stdout)
self.assertIn("chmod u+s", stdout)
for executable in self.ns3_executables:
self.assertIn(os.path.basename(executable), stdout)
# Check scratch simulator yet again
fstat = os.stat(scratch_simulator_path)
self.assertEqual(fstat.st_uid, 0) # check the file was correctly chown'ed by root
self.assertEqual(
fstat.st_mode & stat.S_ISUID, stat.S_ISUID
) # check if normal users can run as sudo
def test_15_CommandTemplate(self):
"""!
Check if command template is working
@return None
"""
# Command templates that are empty or do not have a '%s' should fail
return_code0, stdout0, stderr0 = run_ns3("run sample-simulator --command-template")
self.assertEqual(return_code0, 2)
self.assertIn("argument --command-template: expected one argument", stderr0)
return_code1, stdout1, stderr1 = run_ns3('run sample-simulator --command-template=" "')
return_code2, stdout2, stderr2 = run_ns3('run sample-simulator --command-template " "')
return_code3, stdout3, stderr3 = run_ns3('run sample-simulator --command-template "echo "')
self.assertEqual((return_code1, return_code2, return_code3), (1, 1, 1))
for stderr in [stderr1, stderr2, stderr3]:
self.assertIn("not all arguments converted during string formatting", stderr)
# Command templates with %s should at least continue and try to run the target
return_code4, stdout4, _ = run_ns3(
'run sample-simulator --command-template "%s --PrintVersion" --verbose'
)
return_code5, stdout5, _ = run_ns3(
'run sample-simulator --command-template="%s --PrintVersion" --verbose'
)
self.assertEqual((return_code4, return_code5), (0, 0))
self.assertIn("sample-simulator{ext} --PrintVersion".format(ext=ext), stdout4)
self.assertIn("sample-simulator{ext} --PrintVersion".format(ext=ext), stdout5)
def test_16_ForwardArgumentsToRunTargets(self):
"""!
Check if all flavors of different argument passing to
executable targets are working
@return None
"""
# Test if all argument passing flavors are working
return_code0, stdout0, stderr0 = run_ns3('run "sample-simulator --help" --verbose')
return_code1, stdout1, stderr1 = run_ns3(
'run sample-simulator --command-template="%s --help" --verbose'
)
return_code2, stdout2, stderr2 = run_ns3("run sample-simulator --verbose -- --help")
self.assertEqual((return_code0, return_code1, return_code2), (0, 0, 0))
self.assertIn("sample-simulator{ext} --help".format(ext=ext), stdout0)
self.assertIn("sample-simulator{ext} --help".format(ext=ext), stdout1)
self.assertIn("sample-simulator{ext} --help".format(ext=ext), stdout2)
# Test if the same thing happens with an additional run argument (e.g. --no-build)
return_code0, stdout0, stderr0 = run_ns3('run "sample-simulator --help" --no-build')
return_code1, stdout1, stderr1 = run_ns3(
'run sample-simulator --command-template="%s --help" --no-build'
)
return_code2, stdout2, stderr2 = run_ns3("run sample-simulator --no-build -- --help")
self.assertEqual((return_code0, return_code1, return_code2), (0, 0, 0))
self.assertEqual(stdout0, stdout1)
self.assertEqual(stdout1, stdout2)
self.assertEqual(stderr0, stderr1)
self.assertEqual(stderr1, stderr2)
# Now collect results for each argument individually
return_code0, stdout0, stderr0 = run_ns3('run "sample-simulator --PrintGlobals" --verbose')
return_code1, stdout1, stderr1 = run_ns3('run "sample-simulator --PrintGroups" --verbose')
return_code2, stdout2, stderr2 = run_ns3('run "sample-simulator --PrintTypeIds" --verbose')
self.assertEqual((return_code0, return_code1, return_code2), (0, 0, 0))
self.assertIn("sample-simulator{ext} --PrintGlobals".format(ext=ext), stdout0)
self.assertIn("sample-simulator{ext} --PrintGroups".format(ext=ext), stdout1)
self.assertIn("sample-simulator{ext} --PrintTypeIds".format(ext=ext), stdout2)
# Then check if all the arguments are correctly merged by checking the outputs
cmd = 'run "sample-simulator --PrintGlobals" --command-template="%s --PrintGroups" --verbose -- --PrintTypeIds'
return_code, stdout, stderr = run_ns3(cmd)
self.assertEqual(return_code, 0)
# The order of the arguments is command template,
# arguments passed with the target itself
# and forwarded arguments after the -- separator
self.assertIn(
"sample-simulator{ext} --PrintGroups --PrintGlobals --PrintTypeIds".format(ext=ext),
stdout,
)
# Check if it complains about the missing -- separator
cmd0 = 'run sample-simulator --command-template="%s " --PrintTypeIds'
cmd1 = "run sample-simulator --PrintTypeIds"
return_code0, stdout0, stderr0 = run_ns3(cmd0)
return_code1, stdout1, stderr1 = run_ns3(cmd1)
self.assertEqual((return_code0, return_code1), (1, 1))
self.assertIn("To forward configuration or runtime options, put them after '--'", stderr0)
self.assertIn("To forward configuration or runtime options, put them after '--'", stderr1)
def test_17_RunNoBuildLldb(self):
"""!
Test if scratch simulator is executed through lldb
@return None
"""
if shutil.which("lldb") is None:
self.skipTest("Missing lldb")
return_code, stdout, stderr = run_ns3("build scratch-simulator")
self.assertEqual(return_code, 0)
return_code, stdout, stderr = run_ns3("run scratch-simulator --lldb --verbose --no-build")
self.assertEqual(return_code, 0)
self.assertIn("scratch-simulator", stdout)
self.assertIn("(lldb) target create", stdout)
def test_18_CpmAndVcpkgManagers(self):
"""!
Test if CPM and Vcpkg package managers are working properly
@return None
"""
# Clean the ns-3 configuration
return_code, stdout, stderr = run_ns3("clean")
self.assertEqual(return_code, 0)
# Cleanup VcPkg leftovers
if os.path.exists("vcpkg"):
shutil.rmtree("vcpkg")
# Copy a test module that consumes armadillo
destination_src = os.path.join(ns3_path, "src/test-package-managers")
# Remove pre-existing directories
if os.path.exists(destination_src):
shutil.rmtree(destination_src)
# Always use a fresh copy
shutil.copytree(
os.path.join(ns3_path, "build-support/test-files/test-package-managers"),
destination_src,
)
with DockerContainerManager(self, "ubuntu:22.04") as container:
# Install toolchain
container.execute("apt-get update")
container.execute("apt-get install -y python3 cmake g++ ninja-build")
# Verify that Armadillo is not available and that we did not
# add any new unnecessary dependency when features are not used
try:
container.execute("./ns3 configure -- -DTEST_PACKAGE_MANAGER:STRING=ON")
self.skipTest("Armadillo is already installed")
except DockerException as e:
pass
# Clean cache to prevent dumb errors
return_code, stdout, stderr = run_ns3("clean")
self.assertEqual(return_code, 0)
# Install CPM and VcPkg shared dependency
container.execute("apt-get install -y git")
# Install Armadillo with CPM
try:
container.execute(
"./ns3 configure -- -DNS3_CPM=ON -DTEST_PACKAGE_MANAGER:STRING=CPM"
)
except DockerException as e:
self.fail()
# Try to build module using CPM's Armadillo
try:
container.execute("./ns3 build test-package-managers")
except DockerException as e:
self.fail()
# Clean cache to prevent dumb errors
return_code, stdout, stderr = run_ns3("clean")
self.assertEqual(return_code, 0)
if arch != "aarch64":
# Install VcPkg dependencies
container.execute("apt-get install -y zip unzip tar curl")
# Install Armadillo dependencies
container.execute("apt-get install -y pkg-config gfortran")
# Install VcPkg
try:
container.execute("./ns3 configure -- -DNS3_VCPKG=ON")
except DockerException as e:
self.fail()
# Install Armadillo with VcPkg
try:
container.execute("./ns3 configure -- -DTEST_PACKAGE_MANAGER:STRING=VCPKG")
except DockerException as e:
self.fail()
# Try to build module using VcPkg's Armadillo
try:
container.execute("./ns3 build test-package-managers")
except DockerException as e:
self.fail()
# Remove test module
if os.path.exists(destination_src):
shutil.rmtree(destination_src)
class NS3QualityControlTestCase(unittest.TestCase):
"""!
ns-3 tests to control the quality of the repository over time
"""
def test_01_CheckImageBrightness(self):
"""!
Check if images in the docs are above a brightness threshold.
This should prevent screenshots with dark UI themes.
@return None
"""
if shutil.which("convert") is None:
self.skipTest("Imagemagick was not found")
from pathlib import Path
# Scan for images
image_extensions = ["png", "jpg"]
images = []
for extension in image_extensions:
images += list(Path("./doc").glob("**/figures/*.{ext}".format(ext=extension)))
images += list(Path("./doc").glob("**/figures/**/*.{ext}".format(ext=extension)))
# Get the brightness of an image on a scale of 0-100%
imagemagick_get_image_brightness = 'convert {image} -colorspace HSI -channel b -separate +channel -scale 1x1 -format "%[fx:100*u]" info:'
# We could invert colors of target image to increase its brightness
# convert source.png -channel RGB -negate target.png
brightness_threshold = 50
for image in images:
brightness = subprocess.check_output(
imagemagick_get_image_brightness.format(image=image).split()
)
brightness = float(brightness.decode().strip("'\""))
self.assertGreater(
brightness,
brightness_threshold,
"Image darker than threshold (%d < %d): %s"
% (brightness, brightness_threshold, image),
)
def test_02_CheckForBrokenLogs(self):
"""!
Check if one of the log statements of examples/tests contains/exposes a bug.
@return None
"""
# First enable examples and tests with sanitizers
return_code, stdout, stderr = run_ns3(
'configure -G "{generator}" -d release --enable-examples --enable-tests --enable-sanitizers'
)
self.assertEqual(return_code, 0)
# Then build and run tests setting the environment variable
return_code, stdout, stderr = run_program(
"test.py", "", python=True, env={"TEST_LOGS": "1"}
)
self.assertEqual(return_code, 0)
class NS3QualityControlThatCanFailTestCase(unittest.TestCase):
"""!
ns-3 complementary tests, allowed to fail, to help control
the quality of the repository over time, by checking the
state of URLs listed and more
"""
def test_01_CheckForDeadLinksInSources(self):
"""!
Test if all urls in source files are alive
@return None
"""
# Skip this test if Django is not available
try:
import django
except ImportError:
django = None # noqa
self.skipTest("Django URL validators are not available")
# Skip this test if requests library is not available
try:
import requests
import urllib3
urllib3.disable_warnings()
except ImportError:
requests = None # noqa
self.skipTest("Requests library is not available")
regex = re.compile(r"((http|https)://[^\ \n\)\"\'\}\>\<\]\;\`\\]*)") # noqa
skipped_files = []
whitelisted_urls = {
"https://gitlab.com/your-user-name/ns-3-dev",
"https://www.nsnam.org/release/ns-allinone-3.31.rc1.tar.bz2",
"https://www.nsnam.org/release/ns-allinone-3.X.rcX.tar.bz2",
"https://www.nsnam.org/releases/ns-3-x",
"https://www.nsnam.org/releases/ns-allinone-3.(x-1",
"https://www.nsnam.org/releases/ns-allinone-3.x.tar.bz2",
"https://ns-buildmaster.ee.washington.edu:8010/",
# split due to command-line formatting
"https://cmake.org/cmake/help/latest/manual/cmake-",
"http://www.ieeeghn.org/wiki/index.php/First-Hand:Digital_Television:_The_",
# Dia placeholder xmlns address
"http://www.lysator.liu.se/~alla/dia/",
# Fails due to bad regex
"http://www.ieeeghn.org/wiki/index.php/First-Hand:Digital_Television:_The_Digital_Terrestrial_Television_Broadcasting_(DTTB",
"http://en.wikipedia.org/wiki/Namespace_(computer_science",
"http://en.wikipedia.org/wiki/Bonobo_(component_model",
"http://msdn.microsoft.com/en-us/library/aa365247(v=vs.85",
"https://github.com/rui314/mold/releases/download/v1.4.2/mold-1.4.2-{arch",
"http://www.nsnam.org/bugzilla/show_bug.cgi?id=",
# historical links
"http://www.research.att.com/info/kpv/",
"http://www.research.att.com/~gsf/",
"http://nsnam.isi.edu/nsnam/index.php/Contributed_Code",
"http://scan5.coverity.com/cgi-bin/upload.py",
# terminal output
"https://github.com/Kitware/CMake/releases/download/v3.27.1/cmake-3.27.1-linux-x86_64.tar.gz-",
"http://mirrors.kernel.org/fedora/releases/11/Everything/i386/os/Packages/",
}
# Scan for all URLs in all files we can parse
files_and_urls = set()
unique_urls = set()
for topdir in ["bindings", "doc", "examples", "src", "utils"]:
for root, dirs, files in os.walk(topdir):
# do not parse files in build directories
if "build" in root or "_static" in root or "source-temp" in root or "html" in root:
continue
for file in files:
filepath = os.path.join(root, file)
# skip everything that isn't a file
if not os.path.isfile(filepath):
continue
# skip svg files
if file.endswith(".svg"):
continue
try:
with open(filepath, "r", encoding="utf-8") as f:
matches = regex.findall(f.read())
# Get first group for each match (containing the URL)
# and strip final punctuation or commas in matched links
# commonly found in the docs
urls = list(
map(lambda x: x[0][:-1] if x[0][-1] in ".," else x[0], matches)
)
except UnicodeDecodeError:
skipped_files.append(filepath)
continue
# Search for new unique URLs and add keep track of their associated source file
for url in set(urls) - unique_urls - whitelisted_urls:
unique_urls.add(url)
files_and_urls.add((filepath, url))
# Instantiate the Django URL validator
from django.core.exceptions import ValidationError # noqa
from django.core.validators import URLValidator # noqa
validate_url = URLValidator()
# User agent string to make ACM and Elsevier let us check if links to papers are working
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
# noqa
}
def test_file_url(args):
test_filepath, test_url = args
dead_link_msg = None
# Skip invalid URLs
try:
validate_url(test_url)
except ValidationError:
dead_link_msg = "%s: URL %s, invalid URL" % (test_filepath, test_url)
except Exception as e:
self.assertEqual(False, True, msg=e.__str__())
if dead_link_msg is not None:
return dead_link_msg
tries = 3
# Check if valid URLs are alive
while tries > 0:
# Not verifying the certificate (verify=False) is potentially dangerous
# HEAD checks are not as reliable as GET ones,
# in some cases they may return bogus error codes and reasons
try:
response = requests.get(test_url, verify=False, headers=headers, timeout=50)
# In case of success and redirection
if response.status_code in [200, 301]:
dead_link_msg = None
break
# People use the wrong code, but the reason
# can still be correct
if response.status_code in [302, 308, 500, 503]:
if response.reason.lower() in [
"found",
"moved temporarily",
"permanent redirect",
"ok",
"service temporarily unavailable",
]:
dead_link_msg = None
break
# In case it didn't pass in any of the previous tests,
# set dead_link_msg with the most recent error and try again
dead_link_msg = "%s: URL %s: returned code %d" % (
test_filepath,
test_url,
response.status_code,
)
except requests.exceptions.InvalidURL:
dead_link_msg = "%s: URL %s: invalid URL" % (test_filepath, test_url)
except requests.exceptions.SSLError:
dead_link_msg = "%s: URL %s: SSL error" % (test_filepath, test_url)
except requests.exceptions.TooManyRedirects:
dead_link_msg = "%s: URL %s: too many redirects" % (test_filepath, test_url)
except Exception as e:
try:
error_msg = e.args[0].reason.__str__()
except AttributeError:
error_msg = e.args[0]
dead_link_msg = "%s: URL %s: failed with exception: %s" % (
test_filepath,
test_url,
error_msg,
)
tries -= 1
return dead_link_msg
# Dispatch threads to test multiple URLs concurrently
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=100) as executor:
dead_links = list(executor.map(test_file_url, list(files_and_urls)))
# Filter out None entries
dead_links = list(sorted(filter(lambda x: x is not None, dead_links)))
self.assertEqual(len(dead_links), 0, msg="\n".join(["Dead links found:", *dead_links]))
def test_02_MemoryCheckWithSanitizers(self):
"""!
Test if all tests can be executed without hitting major memory bugs
@return None
"""
return_code, stdout, stderr = run_ns3(
"configure --enable-tests --enable-examples --enable-sanitizers -d optimized"
)
self.assertEqual(return_code, 0)
test_return_code, stdout, stderr = run_program("test.py", "", python=True)
self.assertEqual(test_return_code, 0)
def main():
"""!
Main function
@return None
"""
test_completeness = {
"style": [
NS3UnusedSourcesTestCase,
NS3StyleTestCase,
],
"build": [
NS3CommonSettingsTestCase,
NS3ConfigureBuildProfileTestCase,
NS3ConfigureTestCase,
NS3BuildBaseTestCase,
NS3ExpectedUseTestCase,
],
"complete": [
NS3UnusedSourcesTestCase,
NS3StyleTestCase,
NS3CommonSettingsTestCase,
NS3ConfigureBuildProfileTestCase,
NS3ConfigureTestCase,
NS3BuildBaseTestCase,
NS3ExpectedUseTestCase,
NS3QualityControlTestCase,
],
"extras": [
NS3DependenciesTestCase,
NS3QualityControlThatCanFailTestCase,
],
}
import argparse
parser = argparse.ArgumentParser("Test suite for the ns-3 buildsystem")
parser.add_argument(
"-c", "--completeness", choices=test_completeness.keys(), default="complete"
)
parser.add_argument("-tn", "--test-name", action="store", default=None, type=str)
parser.add_argument("-rtn", "--resume-from-test-name", action="store", default=None, type=str)
parser.add_argument("-q", "--quiet", action="store_true", default=False)
parser.add_argument("-f", "--failfast", action="store_true", default=False)
args = parser.parse_args(sys.argv[1:])
loader = unittest.TestLoader()
suite = unittest.TestSuite()
# Put tests cases in order
for testCase in test_completeness[args.completeness]:
suite.addTests(loader.loadTestsFromTestCase(testCase))
# Filter tests by name
if args.test_name:
# Generate a dictionary of test names and their objects
tests = dict(map(lambda x: (x._testMethodName, x), suite._tests))
tests_to_run = set(map(lambda x: x if args.test_name in x else None, tests.keys()))
tests_to_remove = set(tests) - set(tests_to_run)
for test_to_remove in tests_to_remove:
suite._tests.remove(tests[test_to_remove])
# Filter tests after a specific name (e.g. to restart from a failing test)
if args.resume_from_test_name:
# Generate a dictionary of test names and their objects
tests = dict(map(lambda x: (x._testMethodName, x), suite._tests))
keys = list(tests.keys())
while args.resume_from_test_name not in keys[0] and len(tests) > 0:
suite._tests.remove(tests[keys[0]])
keys.pop(0)
# Before running, check if ns3rc exists and save it
ns3rc_script_bak = ns3rc_script + ".bak"
if os.path.exists(ns3rc_script) and not os.path.exists(ns3rc_script_bak):
shutil.move(ns3rc_script, ns3rc_script_bak)
# Run tests and fail as fast as possible
runner = unittest.TextTestRunner(failfast=args.failfast, verbosity=1 if args.quiet else 2)
runner.run(suite)
# After completing the tests successfully, restore the ns3rc file
if os.path.exists(ns3rc_script_bak):
shutil.move(ns3rc_script_bak, ns3rc_script)
if __name__ == "__main__":
main()
|