Coverage for cogapp/test_cogapp.py: 30.99%

# Coverage for cogapp/test_cogapp.py : 30.99%

## 704 statements 218 run 486 missing 6 excluded 0 partial

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

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 | """ Test cogapp. http://nedbatchelder.com/code/cog Copyright 2004-2015, Ned Batchelder. """ from __future__ import absolute_import import os, os.path, random, re, shutil, stat, sys, tempfile # Use unittest2 if it's available, otherwise unittest. This gives us # back-ported features for 2.6. try: import unittest2 as unittest except ImportError: import unittest from .backward import StringIO, to_bytes, b from .cogapp import Cog, CogOptions, CogGenerator from .cogapp import CogError, CogUsageError, CogGeneratedError from .cogapp import usage, __version__ from .whiteutils import reindentBlock from .makefiles import * TestCase = unittest.TestCase class CogTestsInMemory(TestCase): """ Test cases for cogapp.Cog() """ def testNoCog(self): strings = [ '', ' ', ' \t \t \tx', 'hello', 'the cat\nin the\nhat.', 'Horton\n\tHears A\n\t\tWho' ] for s in strings: self.assertEqual(Cog().processString(s), s) def testSimple(self): infile = """\ Some text. //[[[cog import cog cog.outl("This is line one\\n") cog.outl("This is line two") //]]] gobbledegook. //[[[end]]] epilogue. """ outfile = """\ Some text. //[[[cog import cog cog.outl("This is line one\\n") cog.outl("This is line two") //]]] This is line one This is line two //[[[end]]] epilogue. """ self.assertEqual(Cog().processString(infile), outfile) def testEmptyCog(self): # The cog clause can be totally empty. Not sure why you'd want it, # but it works. infile = """\ hello //[[[cog //]]] //[[[end]]] goodbye """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) def testMultipleCogs(self): # One file can have many cog chunks, even abutting each other. infile = """\ //[[[cog cog.out("chunk1") //]]] chunk1 //[[[end]]] //[[[cog cog.out("chunk2") //]]] chunk2 //[[[end]]] between chunks //[[[cog cog.out("chunk3") //]]] chunk3 //[[[end]]] """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) def testTrimBlankLines(self): infile = """\ //[[[cog cog.out("This is line one\\n", trimblanklines=True) cog.out(''' This is line two ''', dedent=True, trimblanklines=True) cog.outl("This is line three", trimblanklines=True) //]]] This is line one This is line two This is line three //[[[end]]] """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) def testTrimEmptyBlankLines(self): infile = """\ //[[[cog cog.out("This is line one\\n", trimblanklines=True) cog.out(''' This is line two ''', dedent=True, trimblanklines=True) cog.out('', dedent=True, trimblanklines=True) cog.outl("This is line three", trimblanklines=True) //]]] This is line one This is line two This is line three //[[[end]]] """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) def test22EndOfLine(self): # In Python 2.2, this cog file was not parsing because the # last line is indented but didn't end with a newline. infile = """\ //[[[cog import cog for i in range(3): cog.out("%d\\n" % i) //]]] 0 1 2 //[[[end]]] """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) def testIndentedCode(self): infile = """\ first line [[[cog import cog for i in range(3): cog.out("xx%d\\n" % i) ]]] xx0 xx1 xx2 [[[end]]] last line """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) def testPrefixedCode(self): infile = """\ --[[[cog --import cog --for i in range(3): -- cog.out("xx%d\\n" % i) --]]] xx0 xx1 xx2 --[[[end]]] """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) def testPrefixedIndentedCode(self): infile = """\ prologue --[[[cog -- import cog -- for i in range(3): -- cog.out("xy%d\\n" % i) --]]] xy0 xy1 xy2 --[[[end]]] """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) def testBogusPrefixMatch(self): infile = """\ prologue #[[[cog import cog # This comment should not be clobbered by removing the pound sign. for i in range(3): cog.out("xy%d\\n" % i) #]]] xy0 xy1 xy2 #[[[end]]] """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) def testNoFinalNewline(self): # If the cog'ed output has no final newline, # it shouldn't eat up the cog terminator. infile = """\ prologue [[[cog import cog for i in range(3): cog.out("%d" % i) ]]] 012 [[[end]]] epilogue """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) def testNoOutputAtAll(self): # If there is absolutely no cog output, that's ok. infile = """\ prologue [[[cog i = 1 ]]] [[[end]]] epilogue """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) def testPurelyBlankLine(self): # If there is a blank line in the cog code with no whitespace # prefix, that should be OK. infile = """\ prologue [[[cog import sys cog.out("Hello") $ cog.out("There") ]]] HelloThere [[[end]]] epilogue """ infile = reindentBlock(infile.replace('$', '')) self.assertEqual(Cog().processString(infile), infile) def testEmptyOutl(self): # Alexander Belchenko suggested the string argument to outl should # be optional. Does it work? infile = """\ prologue [[[cog cog.outl("x") cog.outl() cog.outl("y") cog.outl(trimblanklines=True) cog.outl("z") ]]] x y z [[[end]]] epilogue """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) def testFirstLineNum(self): infile = """\ fooey [[[cog cog.outl("started at line number %d" % cog.firstLineNum) ]]] started at line number 2 [[[end]]] blah blah [[[cog cog.outl("and again at line %d" % cog.firstLineNum) ]]] and again at line 8 [[[end]]] """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) def testCompactOneLineCode(self): infile = """\ first line hey: [[[cog cog.outl("hello %d" % (3*3*3*3)) ]]] looky! get rid of this! [[[end]]] last line """ outfile = """\ first line hey: [[[cog cog.outl("hello %d" % (3*3*3*3)) ]]] looky! hello 81 [[[end]]] last line """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), reindentBlock(outfile)) def testInsideOutCompact(self): infile = """\ first line hey?: ]]] what is this? [[[cog strange! get rid of this! [[[end]]] last line """ with self.assertRaisesRegexp(CogError, r"infile.txt\(2\): Cog code markers inverted"): Cog().processString(reindentBlock(infile), "infile.txt") def testSharingGlobals(self): infile = """\ first line hey: [[[cog s="hey there" ]]] looky! [[[end]]] more literal junk. [[[cog cog.outl(s) ]]] [[[end]]] last line """ outfile = """\ first line hey: [[[cog s="hey there" ]]] looky! [[[end]]] more literal junk. [[[cog cog.outl(s) ]]] hey there [[[end]]] last line """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), reindentBlock(outfile)) def testAssertInCogCode(self): # Check that we can test assertions in cog code in the test framework. infile = """\ [[[cog assert 1 == 2, "Oops" ]]] [[[end]]] """ infile = reindentBlock(infile) with self.assertRaisesRegexp(AssertionError, "Oops"): Cog().processString(infile) def testCogPrevious(self): # Check that we can access the previous run's output. infile = """\ [[[cog assert cog.previous == "Hello there!\\n", "WTF??" cog.out(cog.previous) cog.outl("Ran again!") ]]] Hello there! [[[end]]] """ outfile = """\ [[[cog assert cog.previous == "Hello there!\\n", "WTF??" cog.out(cog.previous) cog.outl("Ran again!") ]]] Hello there! Ran again! [[[end]]] """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), reindentBlock(outfile)) class CogOptionsTests(TestCase): """ Test the CogOptions class. """ def testEquality(self): o = CogOptions() p = CogOptions() self.assertEqual(o, p) o.parseArgs(['-r']) self.assertNotEqual(o, p) p.parseArgs(['-r']) self.assertEqual(o, p) def testCloning(self): o = CogOptions() o.parseArgs(['-I', 'fooey', '-I', 'booey', '-s', ' /*x*/']) p = o.clone() self.assertEqual(o, p) p.parseArgs(['-I', 'huey', '-D', 'foo=quux']) self.assertNotEqual(o, p) q = CogOptions() q.parseArgs(['-I', 'fooey', '-I', 'booey', '-s', ' /*x*/', '-I', 'huey', '-D', 'foo=quux']) self.assertEqual(p, q) def testCombiningFlags(self): # Single-character flags can be combined. o = CogOptions() o.parseArgs(['-e', '-r', '-z']) p = CogOptions() p.parseArgs(['-erz']) self.assertEqual(o, p) def testMarkers(self): o = CogOptions() o._parse_markers('a b c') self.assertEqual('a', o.sBeginSpec) self.assertEqual('b', o.sEndSpec) self.assertEqual('c', o.sEndOutput) def testMarkersSwitch(self): o = CogOptions() o.parseArgs(['--markers', 'a b c']) self.assertEqual('a', o.sBeginSpec) self.assertEqual('b', o.sEndSpec) self.assertEqual('c', o.sEndOutput) class FileStructureTests(TestCase): """ Test cases to check that we're properly strict about the structure of files. """ def isBad(self, infile, msg=None): infile = reindentBlock(infile) with self.assertRaisesRegexp(CogError, re.escape(msg)): Cog().processString(infile, 'infile.txt') def testBeginNoEnd(self): infile = """\ Fooey #[[[cog cog.outl('hello') """ self.isBad(infile, "infile.txt(2): Cog block begun but never ended.") def testNoEoo(self): infile = """\ Fooey #[[[cog cog.outl('hello') #]]] """ self.isBad(infile, "infile.txt(4): Missing '[[[end]]]' before end of file.") infile2 = """\ Fooey #[[[cog cog.outl('hello') #]]] #[[[cog cog.outl('goodbye') #]]] """ self.isBad(infile2, "infile.txt(5): Unexpected '[[[cog'") def testStartWithEnd(self): infile = """\ #]]] """ self.isBad(infile, "infile.txt(1): Unexpected ']]]'") infile2 = """\ #[[[cog cog.outl('hello') #]]] #[[[end]]] #]]] """ self.isBad(infile2, "infile.txt(5): Unexpected ']]]'") def testStartWithEoo(self): infile = """\ #[[[end]]] """ self.isBad(infile, "infile.txt(1): Unexpected '[[[end]]]'") infile2 = """\ #[[[cog cog.outl('hello') #]]] #[[[end]]] #[[[end]]] """ self.isBad(infile2, "infile.txt(5): Unexpected '[[[end]]]'") def testNoEnd(self): infile = """\ #[[[cog cog.outl("hello") #[[[end]]] """ self.isBad(infile, "infile.txt(3): Unexpected '[[[end]]]'") infile2 = """\ #[[[cog cog.outl('hello') #]]] #[[[end]]] #[[[cog cog.outl("hello") #[[[end]]] """ self.isBad(infile2, "infile.txt(7): Unexpected '[[[end]]]'") def testTwoBegins(self): infile = """\ #[[[cog #[[[cog cog.outl("hello") #]]] #[[[end]]] """ self.isBad(infile, "infile.txt(2): Unexpected '[[[cog'") infile2 = """\ #[[[cog cog.outl("hello") #]]] #[[[end]]] #[[[cog #[[[cog cog.outl("hello") #]]] #[[[end]]] """ self.isBad(infile2, "infile.txt(6): Unexpected '[[[cog'") def testTwoEnds(self): infile = """\ #[[[cog cog.outl("hello") #]]] #]]] #[[[end]]] """ self.isBad(infile, "infile.txt(4): Unexpected ']]]'") infile2 = """\ #[[[cog cog.outl("hello") #]]] #[[[end]]] #[[[cog cog.outl("hello") #]]] #]]] #[[[end]]] """ self.isBad(infile2, "infile.txt(8): Unexpected ']]]'") class CogErrorTests(TestCase): """ Test cases for cog.error(). """ def testErrorMsg(self): infile = """\ [[[cog cog.error("This ain't right!")]]] [[[end]]] """ infile = reindentBlock(infile) with self.assertRaisesRegexp(CogGeneratedError, "This ain't right!"): Cog().processString(infile) def testErrorNoMsg(self): infile = """\ [[[cog cog.error()]]] [[[end]]] """ infile = reindentBlock(infile) with self.assertRaisesRegexp(CogGeneratedError, "Error raised by cog generator."): Cog().processString(infile) def testNoErrorIfErrorNotCalled(self): infile = """\ --[[[cog --import cog --for i in range(3): -- if i > 10: -- cog.error("Something is amiss!") -- cog.out("xx%d\\n" % i) --]]] xx0 xx1 xx2 --[[[end]]] """ infile = reindentBlock(infile) self.assertEqual(Cog().processString(infile), infile) class CogGeneratorGetCodeTests(TestCase): """ Unit tests against CogGenerator to see if its getCode() method works properly. """ def setUp(self): """ All tests get a generator to use, and short same-length names for the functions we're going to use. """ self.gen = CogGenerator() self.m = self.gen.parseMarker self.l = self.gen.parseLine def testEmpty(self): self.m('// [[[cog') self.m('// ]]]') self.assertEqual(self.gen.getCode(), '') def testSimple(self): self.m('// [[[cog') self.l(' print "hello"') self.l(' print "bye"') self.m('// ]]]') self.assertEqual(self.gen.getCode(), 'print "hello"\nprint "bye"') def testCompressed1(self): # For a while, I supported compressed code blocks, but no longer. self.m('// [[[cog: print """') self.l('// hello') self.l('// bye') self.m('// """)]]]') self.assertEqual(self.gen.getCode(), 'hello\nbye') def testCompressed2(self): # For a while, I supported compressed code blocks, but no longer. self.m('// [[[cog: print """') self.l('hello') self.l('bye') self.m('// """)]]]') self.assertEqual(self.gen.getCode(), 'hello\nbye') def testCompressed3(self): # For a while, I supported compressed code blocks, but no longer. self.m('// [[[cog') self.l('print """hello') self.l('bye') self.m('// """)]]]') self.assertEqual(self.gen.getCode(), 'print """hello\nbye') def testCompressed4(self): # For a while, I supported compressed code blocks, but no longer. self.m('// [[[cog: print """') self.l('hello') self.l('bye""")') self.m('// ]]]') self.assertEqual(self.gen.getCode(), 'hello\nbye""")') def testNoCommonPrefixForMarkers(self): # It's important to be able to use #if 0 to hide lines from a # C++ compiler. self.m('#if 0 //[[[cog') self.l('\timport cog, sys') self.l('') self.l('\tprint sys.argv') self.m('#endif //]]]') self.assertEqual(self.gen.getCode(), 'import cog, sys\n\nprint sys.argv') class TestCaseWithTempDir(TestCase): def newCog(self): """ Initialize the cog members for another run. """ # Create a cog engine, and catch its output. self.cog = Cog() self.output = StringIO() self.cog.setOutput(stdout=self.output, stderr=self.output) def setUp(self): # Create a temporary directory. self.tempdir = os.path.join(tempfile.gettempdir(), 'testcog_tempdir_' + str(random.random())[2:]) os.mkdir(self.tempdir) self.olddir = os.getcwd() os.chdir(self.tempdir) self.newCog() def tearDown(self): os.chdir(self.olddir) # Get rid of the temporary directory. shutil.rmtree(self.tempdir) def assertFilesSame(self, sFName1, sFName2): text1 = open(os.path.join(self.tempdir, sFName1), 'rb').read() text2 = open(os.path.join(self.tempdir, sFName2), 'rb').read() self.assertEqual(text1, text2) def assertFileContent(self, sFName, sContent): sAbsName = os.path.join(self.tempdir, sFName) f = open(sAbsName, 'rb') try: sFileContent = f.read() finally: f.close() self.assertEqual(sFileContent, to_bytes(sContent)) class ArgumentHandlingTests(TestCaseWithTempDir): def testArgumentFailure(self): # Return value 2 means usage problem. self.assertEqual(self.cog.main(['argv0', '-j']), 2) output = self.output.getvalue() self.assertIn("option -j not recognized", output) with self.assertRaises(CogUsageError): self.cog.callableMain(['argv0']) with self.assertRaises(CogUsageError): self.cog.callableMain(['argv0', '-j']) def testNoDashOAndAtFile(self): d = { 'cogfiles.txt': """\ # Please run cog """ } makeFiles(d) with self.assertRaises(CogUsageError): self.cog.callableMain(['argv0', '-o', 'foo', '@cogfiles.txt']) def testDashV(self): self.assertEqual(self.cog.main(['argv0', '-v']), 0) output = self.output.getvalue() self.assertEqual('Cog version %s\n' % __version__, output) def producesHelp(self, args): self.newCog() argv = ['argv0'] + args.split() self.assertEqual(self.cog.main(argv), 0) self.assertEqual(usage, self.output.getvalue()) def testDashH(self): # -h or -? anywhere on the command line should just print help. self.producesHelp("-h") self.producesHelp("-?") self.producesHelp("fooey.txt -h") self.producesHelp("-o -r @fooey.txt -? @booey.txt") def testDashOAndDashR(self): d = { 'cogfile.txt': """\ # Please run cog """ } makeFiles(d) with self.assertRaises(CogUsageError): self.cog.callableMain(['argv0', '-o', 'foo', '-r', 'cogfile.txt']) def testDashZ(self): d = { 'test.cog': """\ // This is my C++ file. //[[[cog fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing'] for fn in fnames: cog.outl("void %s();" % fn) //]]] """, 'test.out': """\ // This is my C++ file. //[[[cog fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing'] for fn in fnames: cog.outl("void %s();" % fn) //]]] void DoSomething(); void DoAnotherThing(); void DoLastThing(); """, } makeFiles(d) with self.assertRaisesRegexp(CogError, re.escape("test.cog(6): Missing '[[[end]]]' before end of file.")): self.cog.callableMain(['argv0', '-r', 'test.cog']) self.newCog() self.cog.callableMain(['argv0', '-r', '-z', 'test.cog']) self.assertFilesSame('test.cog', 'test.out') def testBadDashD(self): with self.assertRaises(CogUsageError): self.cog.callableMain(['argv0', '-Dfooey', 'cog.txt']) with self.assertRaises(CogUsageError): self.cog.callableMain(['argv0', '-D', 'fooey', 'cog.txt']) def testBadMarkers(self): with self.assertRaises(CogUsageError): self.cog.callableMain(['argv0', '--markers=X']) with self.assertRaises(CogUsageError): self.cog.callableMain(['argv0', '--markers=A B C D']) class TestFileHandling(TestCaseWithTempDir): def testSimple(self): d = { 'test.cog': """\ // This is my C++ file. //[[[cog fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing'] for fn in fnames: cog.outl("void %s();" % fn) //]]] //[[[end]]] """, 'test.out': """\ // This is my C++ file. //[[[cog fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing'] for fn in fnames: cog.outl("void %s();" % fn) //]]] void DoSomething(); void DoAnotherThing(); void DoLastThing(); //[[[end]]] """, } makeFiles(d) self.cog.callableMain(['argv0', '-r', 'test.cog']) self.assertFilesSame('test.cog', 'test.out') output = self.output.getvalue() self.assertIn("(changed)", output) def testOutputFile(self): # -o sets the output file. d = { 'test.cog': """\ // This is my C++ file. //[[[cog fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing'] for fn in fnames: cog.outl("void %s();" % fn) //]]] //[[[end]]] """, 'test.out': """\ // This is my C++ file. //[[[cog fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing'] for fn in fnames: cog.outl("void %s();" % fn) //]]] void DoSomething(); void DoAnotherThing(); void DoLastThing(); //[[[end]]] """, } makeFiles(d) self.cog.callableMain(['argv0', '-o', 'test.cogged', 'test.cog']) self.assertFilesSame('test.cogged', 'test.out') def testAtFile(self): d = { 'one.cog': """\ //[[[cog cog.outl("hello world") //]]] //[[[end]]] """, 'one.out': """\ //[[[cog cog.outl("hello world") //]]] hello world //[[[end]]] """, 'two.cog': """\ //[[[cog cog.outl("goodbye cruel world") //]]] //[[[end]]] """, 'two.out': """\ //[[[cog cog.outl("goodbye cruel world") //]]] goodbye cruel world //[[[end]]] """, 'cogfiles.txt': """\ # Please run cog one.cog two.cog """ } makeFiles(d) self.cog.callableMain(['argv0', '-r', '@cogfiles.txt']) self.assertFilesSame('one.cog', 'one.out') self.assertFilesSame('two.cog', 'two.out') output = self.output.getvalue() self.assertIn("(changed)", output) def testNestedAtFile(self): d = { 'one.cog': """\ //[[[cog cog.outl("hello world") //]]] //[[[end]]] """, 'one.out': """\ //[[[cog cog.outl("hello world") //]]] hello world //[[[end]]] """, 'two.cog': """\ //[[[cog cog.outl("goodbye cruel world") //]]] //[[[end]]] """, 'two.out': """\ //[[[cog cog.outl("goodbye cruel world") //]]] goodbye cruel world //[[[end]]] """, 'cogfiles.txt': """\ # Please run cog one.cog @cogfiles2.txt """, 'cogfiles2.txt': """\ # This one too, please. two.cog """, } makeFiles(d) self.cog.callableMain(['argv0', '-r', '@cogfiles.txt']) self.assertFilesSame('one.cog', 'one.out') self.assertFilesSame('two.cog', 'two.out') output = self.output.getvalue() self.assertIn("(changed)", output) def testAtFileWithArgs(self): d = { 'both.cog': """\ //[[[cog cog.outl("one: %s" % ('one' in globals())) cog.outl("two: %s" % ('two' in globals())) //]]] //[[[end]]] """, 'one.out': """\ //[[[cog cog.outl("one: %s" % ('one' in globals())) cog.outl("two: %s" % ('two' in globals())) //]]] one: True // ONE two: False // ONE //[[[end]]] """, 'two.out': """\ //[[[cog cog.outl("one: %s" % ('one' in globals())) cog.outl("two: %s" % ('two' in globals())) //]]] one: False // TWO two: True // TWO //[[[end]]] """, 'cogfiles.txt': """\ # Please run cog both.cog -o both.one -s ' // ONE' -D one=x both.cog -o both.two -s ' // TWO' -D two=x """ } makeFiles(d) self.cog.callableMain(['argv0', '@cogfiles.txt']) self.assertFilesSame('both.one', 'one.out') self.assertFilesSame('both.two', 'two.out') def testAtFileWithBadArgCombo(self): d = { 'both.cog': """\ //[[[cog cog.outl("one: %s" % ('one' in globals())) cog.outl("two: %s" % ('two' in globals())) //]]] //[[[end]]] """, 'cogfiles.txt': """\ # Please run cog both.cog both.cog -d # This is bad: -r and -d """ } makeFiles(d) with self.assertRaises(CogUsageError): self.cog.callableMain(['argv0', '-r', '@cogfiles.txt']) def testAtFileWithTrickyFilenames(self): def fix_backslashes(files_txt): """Make the contents of a files.txt sensitive to the platform.""" if sys.platform != "win32": files_txt = files_txt.replace("\\", "/") return files_txt d = { 'one 1.cog': """\ //[[[cog cog.outl("hello world") ]]] """, 'one.out': """\ //[[[cog cog.outl("hello world") ]]] hello world //xxx """, 'subdir': { 'subback.cog': """\ //[[[cog cog.outl("down deep with backslashes") ]]] """, 'subfwd.cog': """\ //[[[cog cog.outl("down deep with slashes") ]]] """, }, 'subback.out': """\ //[[[cog cog.outl("down deep with backslashes") ]]] down deep with backslashes //yyy """, 'subfwd.out': """\ //[[[cog cog.outl("down deep with slashes") ]]] down deep with slashes //zzz """, 'cogfiles.txt': fix_backslashes("""\ # Please run cog 'one 1.cog' -s ' //xxx' subdir\\subback.cog -s ' //yyy' subdir/subfwd.cog -s ' //zzz' """) } makeFiles(d) self.cog.callableMain(['argv0', '-z', '-r', '@cogfiles.txt']) self.assertFilesSame('one 1.cog', 'one.out') self.assertFilesSame('subdir/subback.cog', 'subback.out') self.assertFilesSame('subdir/subfwd.cog', 'subfwd.out') def run_with_verbosity(self, verbosity): d = { 'unchanged.cog': """\ //[[[cog cog.outl("hello world") //]]] hello world //[[[end]]] """, 'changed.cog': """\ //[[[cog cog.outl("goodbye cruel world") //]]] //[[[end]]] """, 'cogfiles.txt': """\ unchanged.cog changed.cog """ } makeFiles(d) self.cog.callableMain(['argv0', '-r', '--verbosity='+verbosity, '@cogfiles.txt']) output = self.output.getvalue() return output def test_verbosity0(self): output = self.run_with_verbosity("0") self.assertEqual(output, "") def test_verbosity1(self): output = self.run_with_verbosity("1") self.assertEqual(output, "Cogging changed.cog (changed)\n") def test_verbosity2(self): output = self.run_with_verbosity("2") self.assertEqual(output, "Cogging unchanged.cog\nCogging changed.cog (changed)\n") class CogTestLineEndings(TestCaseWithTempDir): """Tests for -U option (force LF line-endings in output).""" lines_in = ['Some text.', '//[[[cog', 'cog.outl("Cog text")', '//]]]', 'gobbledegook.', '//[[[end]]]', 'epilogue.', ''] lines_out = ['Some text.', '//[[[cog', 'cog.outl("Cog text")', '//]]]', 'Cog text', '//[[[end]]]', 'epilogue.', ''] def testOutputNativeEol(self): makeFiles({'infile': '\n'.join(self.lines_in)}) self.cog.callableMain(['argv0', '-o', 'outfile', 'infile']) self.assertFileContent('outfile', os.linesep.join(self.lines_out)) def testOutputLfEol(self): makeFiles({'infile': '\n'.join(self.lines_in)}) self.cog.callableMain(['argv0', '-U', '-o', 'outfile', 'infile']) self.assertFileContent('outfile', '\n'.join(self.lines_out)) def testReplaceNativeEol(self): makeFiles({'test.cog': '\n'.join(self.lines_in)}) self.cog.callableMain(['argv0', '-r', 'test.cog']) self.assertFileContent('test.cog', os.linesep.join(self.lines_out)) def testReplaceLfEol(self): makeFiles({'test.cog': '\n'.join(self.lines_in)}) self.cog.callableMain(['argv0', '-U', '-r', 'test.cog']) self.assertFileContent('test.cog', '\n'.join(self.lines_out)) class CogTestCharacterEncoding(TestCaseWithTempDir): def testSimple(self): d = { 'test.cog': b("""\ // This is my C++ file. //[[[cog cog.outl("// Unicode: \xe1\x88\xb4 (U+1234)") //]]] //[[[end]]] """), 'test.out': b("""\ // This is my C++ file. //[[[cog cog.outl("// Unicode: \xe1\x88\xb4 (U+1234)") //]]] // Unicode: \xe1\x88\xb4 (U+1234) //[[[end]]] """), } makeFiles(d) self.cog.callableMain(['argv0', '-r', 'test.cog']) self.assertFilesSame('test.cog', 'test.out') output = self.output.getvalue() self.assertIn("(changed)", output) def testFileEncodingOption(self): d = { 'test.cog': b("""\ // \xca\xee\xe4\xe8\xf0\xe2\xea\xe0 Windows //[[[cog cog.outl("\xd1\xfa\xe5\xf8\xfc \xe5\xf9\xb8 \xfd\xf2\xe8\xf5 \xec\xff\xe3\xea\xe8\xf5 \xf4\xf0\xe0\xed\xf6\xf3\xe7\xf1\xea\xe8\xf5 \xe1\xf3\xeb\xee\xea \xe4\xe0 \xe2\xfb\xef\xe5\xe9 \xf7\xe0\xfe") //]]] //[[[end]]] """), 'test.out': b("""\ // \xca\xee\xe4\xe8\xf0\xe2\xea\xe0 Windows //[[[cog cog.outl("\xd1\xfa\xe5\xf8\xfc \xe5\xf9\xb8 \xfd\xf2\xe8\xf5 \xec\xff\xe3\xea\xe8\xf5 \xf4\xf0\xe0\xed\xf6\xf3\xe7\xf1\xea\xe8\xf5 \xe1\xf3\xeb\xee\xea \xe4\xe0 \xe2\xfb\xef\xe5\xe9 \xf7\xe0\xfe") //]]] \xd1\xfa\xe5\xf8\xfc \xe5\xf9\xb8 \xfd\xf2\xe8\xf5 \xec\xff\xe3\xea\xe8\xf5 \xf4\xf0\xe0\xed\xf6\xf3\xe7\xf1\xea\xe8\xf5 \xe1\xf3\xeb\xee\xea \xe4\xe0 \xe2\xfb\xef\xe5\xe9 \xf7\xe0\xfe //[[[end]]] """), } makeFiles(d) self.cog.callableMain(['argv0', '-n', 'cp1251', '-r', 'test.cog']) self.assertFilesSame('test.cog', 'test.out') output = self.output.getvalue() self.assertIn("(changed)", output) class TestCaseWithImports(TestCaseWithTempDir): """ When running tests which import modules, the sys.modules list leaks from one test to the next. This test case class scrubs the list after each run to keep the tests isolated from each other. """ def setUp(self): TestCaseWithTempDir.setUp(self) self.sysmodulekeys = list(sys.modules) def tearDown(self): modstoscrub = [ modname for modname in sys.modules if modname not in self.sysmodulekeys ] for modname in modstoscrub: del sys.modules[modname] TestCaseWithTempDir.tearDown(self) class CogIncludeTests(TestCaseWithImports): dincludes = { 'test.cog': """\ //[[[cog import mymodule //]]] //[[[end]]] """, 'test.out': """\ //[[[cog import mymodule //]]] Hello from mymodule //[[[end]]] """, 'test2.out': """\ //[[[cog import mymodule //]]] Hello from mymodule in inc2 //[[[end]]] """, 'include': { 'mymodule.py': """\ import cog cog.outl("Hello from mymodule") """ }, 'inc2': { 'mymodule.py': """\ import cog cog.outl("Hello from mymodule in inc2") """ }, 'inc3': { 'someothermodule.py': """\ import cog cog.outl("This is some other module.") """ }, } def testNeedIncludePath(self): # Try it without the -I, to see that an ImportError happens. makeFiles(self.dincludes) with self.assertRaises(ImportError): self.cog.callableMain(['argv0', '-r', 'test.cog']) def testIncludePath(self): # Test that -I adds include directories properly. makeFiles(self.dincludes) self.cog.callableMain(['argv0', '-r', '-I', 'include', 'test.cog']) self.assertFilesSame('test.cog', 'test.out') def testTwoIncludePaths(self): # Test that two -I's add include directories properly. makeFiles(self.dincludes) self.cog.callableMain(['argv0', '-r', '-I', 'include', '-I', 'inc2', 'test.cog']) self.assertFilesSame('test.cog', 'test.out') def testTwoIncludePaths2(self): # Test that two -I's add include directories properly. makeFiles(self.dincludes) self.cog.callableMain(['argv0', '-r', '-I', 'inc2', '-I', 'include', 'test.cog']) self.assertFilesSame('test.cog', 'test2.out') def testUselessIncludePath(self): # Test that the search will continue past the first directory. makeFiles(self.dincludes) self.cog.callableMain(['argv0', '-r', '-I', 'inc3', '-I', 'include', 'test.cog']) self.assertFilesSame('test.cog', 'test.out') def testSysPathIsUnchanged(self): d = { 'bad.cog': """\ //[[[cog cog.error("Oh no!") ]]] //[[[end]]] """, 'good.cog': """\ //[[[cog cog.outl("Oh yes!") ]]] //[[[end]]] """, } makeFiles(d) # Is it unchanged just by creating a cog engine? oldsyspath = sys.path[:] self.newCog() self.assertEqual(oldsyspath, sys.path) # Is it unchanged for a successful run? self.newCog() self.cog.callableMain(['argv0', '-r', 'good.cog']) self.assertEqual(oldsyspath, sys.path) # Is it unchanged for a successful run with includes? self.newCog() self.cog.callableMain(['argv0', '-r', '-I', 'xyzzy', 'good.cog']) self.assertEqual(oldsyspath, sys.path) # Is it unchanged for a successful run with two includes? self.newCog() self.cog.callableMain(['argv0', '-r', '-I', 'xyzzy', '-I', 'quux', 'good.cog']) self.assertEqual(oldsyspath, sys.path) # Is it unchanged for a failed run? self.newCog() with self.assertRaises(CogError): self.cog.callableMain(['argv0', '-r', 'bad.cog']) self.assertEqual(oldsyspath, sys.path) # Is it unchanged for a failed run with includes? self.newCog() with self.assertRaises(CogError): self.cog.callableMain(['argv0', '-r', '-I', 'xyzzy', 'bad.cog']) self.assertEqual(oldsyspath, sys.path) # Is it unchanged for a failed run with two includes? self.newCog() with self.assertRaises(CogError): self.cog.callableMain(['argv0', '-r', '-I', 'xyzzy', '-I', 'quux', 'bad.cog']) self.assertEqual(oldsyspath, sys.path) def testSubDirectories(self): # Test that relative paths on the command line work, with includes. d = { 'code': { 'test.cog': """\ //[[[cog import mysubmodule //]]] //[[[end]]] """, 'test.out': """\ //[[[cog import mysubmodule //]]] Hello from mysubmodule //[[[end]]] """, 'mysubmodule.py': """\ import cog cog.outl("Hello from mysubmodule") """ } } makeFiles(d) # We should be able to invoke cog without the -I switch, and it will # auto-include the current directory self.cog.callableMain(['argv0', '-r', 'code/test.cog']) self.assertFilesSame('code/test.cog', 'code/test.out') class CogTestsInFiles(TestCaseWithTempDir): def testWarnIfNoCogCode(self): # Test that the -e switch warns if there is no Cog code. d = { 'with.cog': """\ //[[[cog cog.outl("hello world") //]]] hello world //[[[end]]] """, 'without.cog': """\ There's no cog code in this file. """, } makeFiles(d) self.cog.callableMain(['argv0', '-e', 'with.cog']) output = self.output.getvalue() self.assertNotIn("Warning", output) self.newCog() self.cog.callableMain(['argv0', '-e', 'without.cog']) output = self.output.getvalue() self.assertIn("Warning: no cog code found in without.cog", output) self.newCog() self.cog.callableMain(['argv0', 'without.cog']) output = self.output.getvalue() self.assertNotIn("Warning", output) def testFileNameProps(self): d = { 'cog1.txt': """\ //[[[cog cog.outl("This is %s in, %s out" % (cog.inFile, cog.outFile)) //]]] this is cog1.txt in, cog1.txt out [[[end]]] """, 'cog1.out': """\ //[[[cog cog.outl("This is %s in, %s out" % (cog.inFile, cog.outFile)) //]]] This is cog1.txt in, cog1.txt out [[[end]]] """, 'cog1out.out': """\ //[[[cog cog.outl("This is %s in, %s out" % (cog.inFile, cog.outFile)) //]]] This is cog1.txt in, cog1out.txt out [[[end]]] """, } makeFiles(d) self.cog.callableMain(['argv0', '-r', 'cog1.txt']) self.assertFilesSame('cog1.txt', 'cog1.out') self.newCog() self.cog.callableMain(['argv0', '-o', 'cog1out.txt', 'cog1.txt']) self.assertFilesSame('cog1out.txt', 'cog1out.out') def testGlobalsDontCrossFiles(self): # Make sure that global values don't get shared between files. d = { 'one.cog': """\ //[[[cog s = "This was set in one.cog" ]]] //[[[end]]] //[[[cog cog.outl(s) ]]] //[[[end]]] """, 'one.out': """\ //[[[cog s = "This was set in one.cog" ]]] //[[[end]]] //[[[cog cog.outl(s) ]]] This was set in one.cog //[[[end]]] """, 'two.cog': """\ //[[[cog try: cog.outl(s) except NameError: cog.outl("s isn't set!") //]]] //[[[end]]] """, 'two.out': """\ //[[[cog try: cog.outl(s) except NameError: cog.outl("s isn't set!") //]]] s isn't set! //[[[end]]] """, 'cogfiles.txt': """\ # Please run cog one.cog two.cog """ } makeFiles(d) self.cog.callableMain(['argv0', '-r', '@cogfiles.txt']) self.assertFilesSame('one.cog', 'one.out') self.assertFilesSame('two.cog', 'two.out') output = self.output.getvalue() self.assertIn("(changed)", output) def testRemoveGeneratedOutput(self): d = { 'cog1.txt': """\ //[[[cog cog.outl("This line was generated.") //]]] This line was generated. //[[[end]]] This line was not. """, 'cog1.out': """\ //[[[cog cog.outl("This line was generated.") //]]] //[[[end]]] This line was not. """, 'cog1.out2': """\ //[[[cog cog.outl("This line was generated.") //]]] This line was generated. //[[[end]]] This line was not. """, } makeFiles(d) # Remove generated output. self.cog.callableMain(['argv0', '-r', '-x', 'cog1.txt']) self.assertFilesSame('cog1.txt', 'cog1.out') self.newCog() # Regenerate the generated output. self.cog.callableMain(['argv0', '-r', 'cog1.txt']) self.assertFilesSame('cog1.txt', 'cog1.out2') self.newCog() # Remove the generated output again. self.cog.callableMain(['argv0', '-r', '-x', 'cog1.txt']) self.assertFilesSame('cog1.txt', 'cog1.out') def testMsgCall(self): infile = """\ #[[[cog cog.msg("Hello there!") #]]] #[[[end]]] """ infile = reindentBlock(infile) self.assertEqual(self.cog.processString(infile), infile) output = self.output.getvalue() self.assertEqual(output, "Message: Hello there!\n") def testErrorMessageHasNoTraceback(self): # Test that a Cog error is printed to stderr with no traceback. d = { 'cog1.txt': """\ //[[[cog cog.outl("This line was newly") cog.outl("generated by cog") cog.outl("blah blah.") //]]] Xhis line was newly generated by cog blah blah. //[[[end]]] (checksum: a8540982e5ad6b95c9e9a184b26f4346) """, } makeFiles(d) stderr = StringIO() self.cog.setOutput(stderr=stderr) self.cog.main(['argv0', '-c', '-r', "cog1.txt"]) self.assertEqual(self.output.getvalue(), "Cogging cog1.txt\n") self.assertEqual(stderr.getvalue(), "cog1.txt(9): Output has been edited! Delete old checksum to unprotect.\n") def testDashD(self): d = { 'test.cog': """\ --[[[cog cog.outl("Defined fooey as " + fooey) ]]] --[[[end]]] """, 'test.kablooey': """\ --[[[cog cog.outl("Defined fooey as " + fooey) ]]] Defined fooey as kablooey --[[[end]]] """, 'test.einstein': """\ --[[[cog cog.outl("Defined fooey as " + fooey) ]]] Defined fooey as e=mc2 --[[[end]]] """, } makeFiles(d) self.cog.callableMain(['argv0', '-r', '-D', 'fooey=kablooey', 'test.cog']) self.assertFilesSame('test.cog', 'test.kablooey') makeFiles(d) self.cog.callableMain(['argv0', '-r', '-Dfooey=kablooey', 'test.cog']) self.assertFilesSame('test.cog', 'test.kablooey') makeFiles(d) self.cog.callableMain(['argv0', '-r', '-Dfooey=e=mc2', 'test.cog']) self.assertFilesSame('test.cog', 'test.einstein') makeFiles(d) self.cog.callableMain(['argv0', '-r', '-Dbar=quux', '-Dfooey=kablooey', 'test.cog']) self.assertFilesSame('test.cog', 'test.kablooey') makeFiles(d) self.cog.callableMain(['argv0', '-r', '-Dfooey=kablooey', '-Dbar=quux', 'test.cog']) self.assertFilesSame('test.cog', 'test.kablooey') makeFiles(d) self.cog.callableMain(['argv0', '-r', '-Dfooey=gooey', '-Dfooey=kablooey', 'test.cog']) self.assertFilesSame('test.cog', 'test.kablooey') def testOutputToStdout(self): d = { 'test.cog': """\ --[[[cog cog.outl('Hey there!') ]]] --[[[end]]] """ } makeFiles(d) stderr = StringIO() self.cog.setOutput(stderr=stderr) self.cog.callableMain(['argv0', 'test.cog']) output = self.output.getvalue() outerr = stderr.getvalue() self.assertEqual(output, "--[[[cog cog.outl('Hey there!') ]]]\nHey there!\n--[[[end]]]\n") self.assertEqual(outerr, "") def testReadFromStdin(self): stdin = StringIO("--[[[cog cog.outl('Wow') ]]]\n--[[[end]]]\n") def restore_stdin(old_stdin): sys.stdin = old_stdin self.addCleanup(restore_stdin, sys.stdin) sys.stdin = stdin stderr = StringIO() self.cog.setOutput(stderr=stderr) self.cog.callableMain(['argv0', '-']) output = self.output.getvalue() outerr = stderr.getvalue() self.assertEqual(output, "--[[[cog cog.outl('Wow') ]]]\nWow\n--[[[end]]]\n") self.assertEqual(outerr, "") def testSuffixOutputLines(self): d = { 'test.cog': """\ Hey there. ;[[[cog cog.outl('a\\nb\\n \\nc') ]]] ;[[[end]]] Good bye. """, 'test.out': """\ Hey there. ;[[[cog cog.outl('a\\nb\\n \\nc') ]]] a (foo) b (foo) """ # These three trailing spaces are important. # The suffix is not applied to completely blank lines. """ c (foo) ;[[[end]]] Good bye. """, } makeFiles(d) self.cog.callableMain(['argv0', '-r', '-s', ' (foo)', 'test.cog']) self.assertFilesSame('test.cog', 'test.out') def testEmptySuffix(self): d = { 'test.cog': """\ ;[[[cog cog.outl('a\\nb\\nc') ]]] ;[[[end]]] """, 'test.out': """\ ;[[[cog cog.outl('a\\nb\\nc') ]]] a b c ;[[[end]]] """, } makeFiles(d) self.cog.callableMain(['argv0', '-r', '-s', '', 'test.cog']) self.assertFilesSame('test.cog', 'test.out') def testHellishSuffix(self): d = { 'test.cog': """\ ;[[[cog cog.outl('a\\n\\nb') ]]] """, 'test.out': """\ ;[[[cog cog.outl('a\\n\\nb') ]]] a /\\n*+([)]>< b /\\n*+([)]>< """, } makeFiles(d) self.cog.callableMain(['argv0', '-z', '-r', '-s', r' /\n*+([)]><', 'test.cog']) self.assertFilesSame('test.cog', 'test.out') class WritabilityTests(TestCaseWithTempDir): d = { 'test.cog': """\ //[[[cog for fn in ['DoSomething', 'DoAnotherThing', 'DoLastThing']: cog.outl("void %s();" % fn) //]]] //[[[end]]] """, 'test.out': """\ //[[[cog for fn in ['DoSomething', 'DoAnotherThing', 'DoLastThing']: cog.outl("void %s();" % fn) //]]] void DoSomething(); void DoAnotherThing(); void DoLastThing(); //[[[end]]] """, } if os.name == 'nt': #pragma: no cover # for Windows cmd_w_args = 'attrib -R %s' cmd_w_asterisk = 'attrib -R *' else: #pragma: no cover # for unix-like cmd_w_args = 'chmod +w %s' cmd_w_asterisk = 'chmod +w *' def setUp(self): TestCaseWithTempDir.setUp(self) makeFiles(self.d) self.testcog = os.path.join(self.tempdir, 'test.cog') os.chmod(self.testcog, stat.S_IREAD) # Make the file readonly. assert not os.access(self.testcog, os.W_OK) def tearDown(self): os.chmod(self.testcog, stat.S_IWRITE) # Make the file writable again. TestCaseWithTempDir.tearDown(self) def testReadonlyNoCommand(self): with self.assertRaisesRegexp(CogError, "Can't overwrite test.cog"): self.cog.callableMain(['argv0', '-r', 'test.cog']) assert not os.access(self.testcog, os.W_OK) def testReadonlyWithCommand(self): self.cog.callableMain(['argv0', '-r', '-w', self.cmd_w_args, 'test.cog']) self.assertFilesSame('test.cog', 'test.out') assert os.access(self.testcog, os.W_OK) def testReadonlyWithCommandWithNoSlot(self): self.cog.callableMain(['argv0', '-r', '-w', self.cmd_w_asterisk, 'test.cog']) self.assertFilesSame('test.cog', 'test.out') assert os.access(self.testcog, os.W_OK) def testReadonlyWithIneffectualCommand(self): with self.assertRaisesRegexp(CogError, "Couldn't make test.cog writable"): self.cog.callableMain(['argv0', '-r', '-w', 'echo %s', 'test.cog']) assert not os.access(self.testcog, os.W_OK) class ChecksumTests(TestCaseWithTempDir): def testCreateChecksumOutput(self): d = { 'cog1.txt': """\ //[[[cog cog.outl("This line was generated.") //]]] This line was generated. //[[[end]]] This line was not. """, 'cog1.out': """\ //[[[cog cog.outl("This line was generated.") //]]] This line was generated. //[[[end]]] (checksum: 8adb13fb59b996a1c7f0065ea9f3d893) This line was not. """, } makeFiles(d) self.cog.callableMain(['argv0', '-r', '-c', 'cog1.txt']) self.assertFilesSame('cog1.txt', 'cog1.out') def testCheckChecksumOutput(self): d = { 'cog1.txt': """\ //[[[cog cog.outl("This line was newly") cog.outl("generated by cog") cog.outl("blah blah.") //]]] This line was generated. //[[[end]]] (checksum: 8adb13fb59b996a1c7f0065ea9f3d893) """, 'cog1.out': """\ //[[[cog cog.outl("This line was newly") cog.outl("generated by cog") cog.outl("blah blah.") //]]] This line was newly generated by cog blah blah. //[[[end]]] (checksum: a8540982e5ad6b95c9e9a184b26f4346) """, } makeFiles(d) self.cog.callableMain(['argv0', '-r', '-c', 'cog1.txt']) self.assertFilesSame('cog1.txt', 'cog1.out') def testRemoveChecksumOutput(self): d = { 'cog1.txt': """\ //[[[cog cog.outl("This line was newly") cog.outl("generated by cog") cog.outl("blah blah.") //]]] This line was generated. //[[[end]]] (checksum: 8adb13fb59b996a1c7f0065ea9f3d893) fooey """, 'cog1.out': """\ //[[[cog cog.outl("This line was newly") cog.outl("generated by cog") cog.outl("blah blah.") //]]] This line was newly generated by cog blah blah. //[[[end]]] fooey """, } makeFiles(d) self.cog.callableMain(['argv0', '-r', 'cog1.txt']) self.assertFilesSame('cog1.txt', 'cog1.out') def testTamperedChecksumOutput(self): d = { 'cog1.txt': """\ //[[[cog cog.outl("This line was newly") cog.outl("generated by cog") cog.outl("blah blah.") //]]] Xhis line was newly generated by cog blah blah. //[[[end]]] (checksum: a8540982e5ad6b95c9e9a184b26f4346) """, 'cog2.txt': """\ //[[[cog cog.outl("This line was newly") cog.outl("generated by cog") cog.outl("blah blah.") //]]] This line was newly generated by cog blah blah! //[[[end]]] (checksum: a8540982e5ad6b95c9e9a184b26f4346) """, 'cog3.txt': """\ //[[[cog cog.outl("This line was newly") cog.outl("generated by cog") cog.outl("blah blah.") //]]] This line was newly generated by cog blah blah. //[[[end]]] (checksum: a8540982e5ad6b95c9e9a184b26f4346) """, 'cog4.txt': """\ //[[[cog cog.outl("This line was newly") cog.outl("generated by cog") cog.outl("blah blah.") //]]] This line was newly generated by cog blah blah.. //[[[end]]] (checksum: a8540982e5ad6b95c9e9a184b26f4346) """, 'cog5.txt': """\ //[[[cog cog.outl("This line was newly") cog.outl("generated by cog") cog.outl("blah blah.") //]]] This line was newly generated by cog blah blah. extra //[[[end]]] (checksum: a8540982e5ad6b95c9e9a184b26f4346) """, 'cog6.txt': """\ //[[[cog cog.outl("This line was newly") cog.outl("generated by cog") cog.outl("blah blah.") //]]] //[[[end]]] (checksum: a8540982e5ad6b95c9e9a184b26f4346) """, } makeFiles(d) with self.assertRaisesRegexp(CogError, r"cog1.txt\(9\): Output has been edited! Delete old checksum to unprotect."): self.cog.callableMain(['argv0', '-c', "cog1.txt"]) with self.assertRaisesRegexp(CogError, r"cog2.txt\(9\): Output has been edited! Delete old checksum to unprotect."): self.cog.callableMain(['argv0', '-c', "cog2.txt"]) with self.assertRaisesRegexp(CogError, r"cog3.txt\(10\): Output has been edited! Delete old checksum to unprotect."): self.cog.callableMain(['argv0', '-c', "cog3.txt"]) with self.assertRaisesRegexp(CogError, r"cog4.txt\(9\): Output has been edited! Delete old checksum to unprotect."): self.cog.callableMain(['argv0', '-c', "cog4.txt"]) with self.assertRaisesRegexp(CogError, r"cog5.txt\(10\): Output has been edited! Delete old checksum to unprotect."): self.cog.callableMain(['argv0', '-c', "cog5.txt"]) with self.assertRaisesRegexp(CogError, r"cog6.txt\(6\): Output has been edited! Delete old checksum to unprotect."): self.cog.callableMain(['argv0', '-c', "cog6.txt"]) def testArgvIsntModified(self): argv = ['argv0', '-v'] orig_argv = argv[:] self.cog.callableMain(argv) self.assertEqual(argv, orig_argv) class CustomMarkerTests(TestCaseWithTempDir): def testCustomerMarkers(self): d = { 'test.cog': """\ //{{ cog.outl("void %s();" % "MyFunction") //}} //{{end}} """, 'test.out': """\ //{{ cog.outl("void %s();" % "MyFunction") //}} void MyFunction(); //{{end}} """, } makeFiles(d) self.cog.callableMain([ 'argv0', '-r', '--markers={{ }} {{end}}', 'test.cog' ]) self.assertFilesSame('test.cog', 'test.out') def testTrulyWackyMarkers(self): # Make sure the markers are properly re-escaped. d = { 'test.cog': """\ //**( cog.outl("void %s();" % "MyFunction") //**) //**(end)** """, 'test.out': """\ //**( cog.outl("void %s();" % "MyFunction") //**) void MyFunction(); //**(end)** """, } makeFiles(d) self.cog.callableMain([ 'argv0', '-r', '--markers=**( **) **(end)**', 'test.cog' ]) self.assertFilesSame('test.cog', 'test.out') def testChangeJustOneMarker(self): d = { 'test.cog': """\ //**( cog.outl("void %s();" % "MyFunction") //]]] //[[[end]]] """, 'test.out': """\ //**( cog.outl("void %s();" % "MyFunction") //]]] void MyFunction(); //[[[end]]] """, } makeFiles(d) self.cog.callableMain([ 'argv0', '-r', '--markers=**( ]]] [[[end]]]', 'test.cog' ]) self.assertFilesSame('test.cog', 'test.out') class BlakeTests(TestCaseWithTempDir): # Blake Winton's contributions. def testDeleteCode(self): # -o sets the output file. d = { 'test.cog': """\ // This is my C++ file. //[[[cog fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing'] for fn in fnames: cog.outl("void %s();" % fn) //]]] Some Sample Code Here //[[[end]]]Data Data And Some More """, 'test.out': """\ // This is my C++ file. void DoSomething(); void DoAnotherThing(); void DoLastThing(); And Some More """, } makeFiles(d) self.cog.callableMain(['argv0', '-d', '-o', 'test.cogged', 'test.cog']) self.assertFilesSame('test.cogged', 'test.out') def testDeleteCodeWithDashRFails(self): d = { 'test.cog': """\ // This is my C++ file. """ } makeFiles(d) with self.assertRaises(CogUsageError): self.cog.callableMain(['argv0', '-r', '-d', 'test.cog']) def testSettingGlobals(self): # Blake Winton contributed a way to set the globals that will be used in # processFile(). d = { 'test.cog': """\ // This is my C++ file. //[[[cog for fn in fnames: cog.outl("void %s();" % fn) //]]] Some Sample Code Here //[[[end]]]""", 'test.out': """\ // This is my C++ file. void DoBlake(); void DoWinton(); void DoContribution(); """, } makeFiles(d) globals = {} globals['fnames'] = ['DoBlake', 'DoWinton', 'DoContribution'] self.cog.options.bDeleteCode = True self.cog.processFile('test.cog', 'test.cogged', globals=globals) self.assertFilesSame('test.cogged', 'test.out') class ErrorCallTests(TestCaseWithTempDir): def testErrorCallHasNoTraceback(self): # Test that cog.error() doesn't show a traceback. d = { 'error.cog': """\ //[[[cog cog.error("Something Bad!") //]]] //[[[end]]] """, } makeFiles(d) self.cog.main(['argv0', '-r', 'error.cog']) output = self.output.getvalue() self.assertEqual(output, "Cogging error.cog\nError: Something Bad!\n") def testRealErrorHasTraceback(self): # Test that a genuine error does show a traceback. d = { 'error.cog': """\ //[[[cog raise RuntimeError("Hey!") //]]] //[[[end]]] """, } makeFiles(d) self.cog.main(['argv0', '-r', 'error.cog']) output = self.output.getvalue() msg = 'Actual output:\n' + output self.assert_(output.startswith("Cogging error.cog\nTraceback (most recent"), msg) self.assertIn("RuntimeError: Hey!", output) # Things not yet tested: # - A bad -w command (currently fails silently).