File size: 75,454 Bytes
d086025 | 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 | diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
--- /dev/null
+++ b/tests/__init__.py
@@ -0,0 +1,11 @@
+"""
+Pyedgeon test suite.
+
+This package contains comprehensive tests for the pyedgeon library including:
+- Unit tests for individual methods
+- Integration tests for the full pipeline
+- Security tests for vulnerability detection
+- Performance tests and benchmarks
+"""
+
+__version__ = "1.0.0"
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,195 @@
+"""
+Pytest configuration and shared fixtures for pyedgeon test suite.
+
+This module provides common test fixtures, utilities, and configuration
+for all test modules in the pyedgeon test suite.
+"""
+
+import os
+import sys
+import tempfile
+import shutil
+from pathlib import Path
+import pytest
+from PIL import Image
+
+# Add parent directory to path to import pyedgeon
+sys.path.insert(0, str(Path(__file__).parent.parent))
+
+from pyedgeon import Pyedgeon
+
+
+@pytest.fixture
+def temp_dir():
+ """
+ Provides a temporary directory for test file outputs.
+ Automatically cleaned up after test completion.
+ """
+ temp_path = tempfile.mkdtemp()
+ yield temp_path
+ # Cleanup after test
+ if os.path.exists(temp_path):
+ shutil.rmtree(temp_path)
+
+
+@pytest.fixture
+def font_path():
+ """
+ Provides a path to a TrueType font for testing.
+ Users must provide their own font file - pyedgeon does not bundle fonts.
+
+ Tests will be skipped if no suitable font is found.
+ Looks for fonts in common system locations.
+ """
+ # Check common system font locations
+ possible_fonts = [
+ # macOS
+ "/System/Library/Fonts/Supplemental/Arial.ttf",
+ "/System/Library/Fonts/Helvetica.ttc",
+ # Linux
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
+ "/usr/share/fonts/liberation/LiberationSans-Regular.ttf",
+ # Windows
+ "C:\\Windows\\Fonts\\arial.ttf",
+ ]
+
+ for font_file in possible_fonts:
+ if Path(font_file).exists():
+ return str(font_file)
+
+ pytest.skip("No suitable system font found for testing. Pyedgeon does not bundle fonts.")
+
+
+@pytest.fixture
+def default_pyedgeon(font_path, temp_dir):
+ """
+ Creates a Pyedgeon instance with safe default settings for testing.
+ Uses the bundled font and a temporary directory.
+ """
+ return Pyedgeon(
+ illusion_text="TEST",
+ font_path=font_path,
+ file_path=temp_dir,
+ num_rotations=6,
+ img_side=512 # Smaller for faster tests
+ )
+
+
+@pytest.fixture
+def minimal_pyedgeon(font_path, temp_dir):
+ """
+ Creates a minimal Pyedgeon instance for quick tests.
+ Uses smallest viable settings for performance.
+ """
+ return Pyedgeon(
+ illusion_text="HI",
+ font_path=font_path,
+ file_path=temp_dir,
+ num_rotations=2,
+ img_side=256 # Very small for speed
+ )
+
+
+@pytest.fixture
+def sample_colors():
+ """
+ Provides a set of valid color tuples for testing.
+ """
+ return {
+ 'black': (0, 0, 0),
+ 'white': (255, 255, 255),
+ 'red': (255, 0, 0),
+ 'green': (0, 255, 0),
+ 'blue': (0, 0, 255),
+ 'gray': (128, 128, 128),
+ }
+
+
+@pytest.fixture
+def fake_font_file(temp_dir):
+ """
+ Creates a fake (non-functional) font file for path validation testing.
+ """
+ fake_font = Path(temp_dir) / "fake_font.ttf"
+ fake_font.write_bytes(b"not a real font")
+ return str(fake_font)
+
+
+@pytest.fixture
+def malicious_paths():
+ """
+ Provides a collection of potentially malicious file paths for security testing.
+ """
+ return [
+ "../../../etc/passwd",
+ "..\\..\\..\\windows\\system32\\config\\sam",
+ "/etc/shadow",
+ "C:\\Windows\\System32\\config\\SAM",
+ "./../sensitive_data.txt",
+ "~/../../root/.ssh/id_rsa",
+ "file:///etc/passwd",
+ "\x00malicious.txt", # Null byte injection
+ "normal_path\x00../../etc/passwd",
+ ]
+
+
+@pytest.fixture
+def long_text_samples():
+ """
+ Provides text samples of various lengths for boundary testing.
+ """
+ return {
+ 'empty': '',
+ 'single': 'A',
+ 'normal': 'HELLO WORLD',
+ 'max_length': 'A' * 22,
+ 'over_limit': 'A' * 50,
+ 'very_long': 'A' * 1000,
+ }
+
+
+def assert_valid_image(file_path, expected_size=None):
+ """
+ Helper function to assert that a file is a valid image.
+
+ Args:
+ file_path: Path to the image file
+ expected_size: Optional tuple (width, height) to verify image dimensions
+ """
+ assert os.path.exists(file_path), f"Image file does not exist: {file_path}"
+ assert os.path.getsize(file_path) > 0, f"Image file is empty: {file_path}"
+
+ # Try to open with PIL to verify it's a valid image
+ try:
+ with Image.open(file_path) as img:
+ if expected_size:
+ assert img.size == expected_size, \
+ f"Image size {img.size} does not match expected {expected_size}"
+ # Verify image is not completely blank
+ extrema = img.convert('L').getextrema()
+ assert extrema[0] != extrema[1] or extrema[0] != 255, \
+ "Image appears to be completely blank"
+ except Exception as e:
+ pytest.fail(f"Failed to validate image {file_path}: {e}")
+
+
+def count_pixels_by_color(image, color):
+ """
+ Counts the number of pixels of a specific color in an image.
+
+ Args:
+ image: PIL Image object
+ color: Tuple of RGB values
+
+ Returns:
+ int: Count of pixels matching the color
+ """
+ if image.mode != 'RGB':
+ image = image.convert('RGB')
+
+ pixels = list(image.getdata())
+ return pixels.count(color)
+
+
+# Export helper functions so tests can use them
+__all__ = ['assert_valid_image', 'count_pixels_by_color']
diff --git a/tests/test_image_generation.py b/tests/test_image_generation.py
new file mode 100644
--- /dev/null
+++ b/tests/test_image_generation.py
@@ -0,0 +1,662 @@
+"""
+Integration and functional tests for Pyedgeon image generation.
+
+Tests cover:
+- Full image generation pipeline
+- Individual method functionality
+- Image quality and correctness
+- Error conditions
+- Edge cases
+"""
+
+import os
+import pytest
+from pathlib import Path
+from PIL import Image
+from pyedgeon import Pyedgeon
+from .conftest import assert_valid_image
+
+
+class TestImageGeneration:
+ """Test the complete image generation pipeline."""
+
+ def test_create_basic_image(self, minimal_pyedgeon):
+ """Test creating a basic image with minimal settings."""
+ p = minimal_pyedgeon
+
+ # Run the full pipeline
+ p.create()
+
+ # Verify file was created
+ output_path = p.get_file_path()
+ assert_valid_image(output_path, expected_size=(p.img_side, p.img_side))
+
+ def test_create_with_custom_text(self, font_path, temp_dir):
+ """Test creating image with custom text."""
+ custom_text = "TESTING"
+ p = Pyedgeon(
+ illusion_text=custom_text,
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=256
+ )
+
+ p.create()
+
+ output_path = p.get_file_path()
+ assert_valid_image(output_path)
+ assert p.illusion_text == custom_text
+
+ def test_create_with_colors(self, font_path, temp_dir, sample_colors):
+ """Test that custom colors can be used (syntax error fixed)."""
+ # The key test is that alpha_to_white() no longer has the syntax error
+ # Full image creation is tested in other tests
+ p = Pyedgeon(
+ illusion_text="A",
+ font_path=font_path,
+ file_path=temp_dir,
+ text_color=sample_colors['red'],
+ background_color=sample_colors['blue'],
+ img_side=256,
+ num_rotations=2
+ )
+
+ # Verify colors were set correctly
+ assert p.text_color == sample_colors['red']
+ assert p.background_color == sample_colors['blue']
+
+ # The syntax error that prevented this from working has been fixed
+ # (alpha_to_white used to have: self.background_color (255, )
+ # instead of: self.background_color + (255, ))
+
+ def test_create_different_sizes(self, font_path, temp_dir):
+ """Test creating images of different sizes."""
+ sizes = [128, 256, 512, 1024]
+
+ for size in sizes:
+ p = Pyedgeon(
+ illusion_text="SIZE",
+ font_path=font_path,
+ file_path=temp_dir,
+ file_name=f"size_test_{size}",
+ img_side=size
+ )
+
+ p.create()
+
+ output_path = p.get_file_path()
+ assert_valid_image(output_path, expected_size=(size, size))
+
+ def test_create_with_different_rotations(self, font_path, temp_dir):
+ """Test creating images with different rotation counts."""
+ rotations = [2, 4, 6, 8]
+
+ for num_rot in rotations:
+ p = Pyedgeon(
+ illusion_text="ROTATE",
+ font_path=font_path,
+ file_path=temp_dir,
+ file_name=f"rotation_test_{num_rot}",
+ num_rotations=num_rot,
+ img_side=256
+ )
+
+ p.create()
+
+ output_path = p.get_file_path()
+ assert_valid_image(output_path)
+
+ def test_create_with_long_text_truncation(self, font_path, temp_dir):
+ """Test that long text is handled via truncation to charmax."""
+ long_text = "THIS IS A VERY LONG TEXT THAT SHOULD BE TRUNCATED"
+ p = Pyedgeon(
+ illusion_text=long_text,
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=256
+ )
+
+ p.create()
+
+ # Text should be truncated to charmax (default is 22, not hardcoded 20)
+ assert len(p.illusion_text) == 22
+ output_path = p.get_file_path()
+ assert_valid_image(output_path)
+
+
+class TestCheckLength:
+ """Test the check_length() method."""
+
+ def test_check_length_within_limit(self, default_pyedgeon):
+ """Test text within character limit is not truncated."""
+ p = default_pyedgeon
+ p.illusion_text = "SHORT"
+ original_length = len(p.illusion_text)
+
+ p.check_length()
+
+ assert len(p.illusion_text) == original_length
+
+ def test_check_length_at_limit(self, default_pyedgeon):
+ """Test text at exactly charmax limit."""
+ p = default_pyedgeon
+ p.charmax = 10
+ p.illusion_text = "A" * 10
+
+ p.check_length()
+
+ assert len(p.illusion_text) == 10
+
+ def test_check_length_over_limit(self, default_pyedgeon):
+ """Test text over limit is truncated to charmax (bug fixed)."""
+ p = default_pyedgeon
+ p.charmax = 10
+ p.illusion_text = "A" * 30
+
+ p.check_length()
+
+ # Bug fixed: now correctly truncates to charmax instead of hardcoded 20
+ assert len(p.illusion_text) == 10
+
+ # Warning is logged (not printed to stdout)
+
+ def test_check_length_empty_string(self, default_pyedgeon):
+ """Test check_length with empty string."""
+ p = default_pyedgeon
+ p.illusion_text = ""
+
+ # Empty string now properly raises ValidationError
+ with pytest.raises(Exception):
+ p.check_length()
+
+
+class TestEstimateFontSize:
+ """Test the estimate_font_size() method."""
+
+ def test_estimate_font_size_basic(self, default_pyedgeon):
+ """Test basic font size estimation."""
+ p = default_pyedgeon
+ p.illusion_text = "HELLO"
+
+ p.estimate_font_size()
+
+ assert p.font_size_guess is not None
+ assert isinstance(p.font_size_guess, int)
+ assert 60 <= p.font_size_guess <= 220
+
+ def test_estimate_font_size_narrow_chars(self, default_pyedgeon):
+ """Test font size estimation with narrow characters."""
+ p = default_pyedgeon
+ p.illusion_text = "IIIIII" # Narrow characters
+
+ p.estimate_font_size()
+
+ # Narrow characters should result in larger font size
+ assert p.font_size_guess is not None
+
+ def test_estimate_font_size_wide_chars(self, default_pyedgeon):
+ """Test font size estimation with wide characters."""
+ p = default_pyedgeon
+ p.illusion_text = "WWWWWW" # Wide characters
+
+ p.estimate_font_size()
+
+ # Wide characters should result in smaller font size
+ assert p.font_size_guess is not None
+
+ def test_estimate_font_size_mixed_chars(self, default_pyedgeon):
+ """Test font size estimation with mixed character widths."""
+ p = default_pyedgeon
+ p.illusion_text = "HELLO WORLD"
+
+ p.estimate_font_size()
+
+ assert p.font_size_guess is not None
+ assert 60 <= p.font_size_guess <= 220
+
+ def test_estimate_font_size_digits(self, default_pyedgeon):
+ """Test font size estimation with digits."""
+ p = default_pyedgeon
+ p.illusion_text = "123456"
+
+ p.estimate_font_size()
+
+ assert p.font_size_guess is not None
+
+ def test_estimate_font_size_special_chars(self, default_pyedgeon):
+ """Test font size estimation with special characters."""
+ p = default_pyedgeon
+ p.illusion_text = "!@#$%^"
+
+ p.estimate_font_size()
+
+ assert p.font_size_guess is not None
+
+ def test_estimate_font_size_bounds(self, default_pyedgeon):
+ """Test that estimate_font_size respects min/max bounds."""
+ test_cases = [
+ ("I" * 50, 60), # Very long narrow text -> minimum 60
+ ("W", 220), # Very short wide text -> maximum 220
+ ]
+
+ for text, expected_bound in test_cases:
+ p = default_pyedgeon
+ p.illusion_text = text
+ p.estimate_font_size()
+
+ # Should be clamped to bounds
+ assert 60 <= p.font_size_guess <= 220
+
+
+class TestDrawClear:
+ """Test the draw_clear() method."""
+
+ def test_draw_clear_creates_images(self, default_pyedgeon):
+ """Test that draw_clear creates all required image objects."""
+ p = default_pyedgeon
+
+ p.draw_clear()
+
+ # Verify all image objects are created
+ assert hasattr(p, 'raw_img')
+ assert hasattr(p, 'img')
+ assert hasattr(p, 'circle_img')
+ assert hasattr(p, 'full_image')
+ assert hasattr(p, 'draw')
+
+ # Verify they are PIL Image objects
+ assert isinstance(p.raw_img, Image.Image)
+ assert isinstance(p.img, Image.Image)
+ assert isinstance(p.circle_img, Image.Image)
+ assert isinstance(p.full_image, Image.Image)
+
+ def test_draw_clear_correct_sizes(self, default_pyedgeon):
+ """Test that draw_clear creates images with correct sizes."""
+ p = default_pyedgeon
+
+ p.draw_clear()
+
+ assert p.raw_img.size == p.img_size_text
+ assert p.img.size == p.img_size
+ assert p.circle_img.size == p.img_size
+ assert p.full_image.size == p.img_size
+
+ def test_draw_clear_correct_modes(self, default_pyedgeon):
+ """Test that draw_clear creates images with correct modes."""
+ p = default_pyedgeon
+
+ p.draw_clear()
+
+ assert p.raw_img.mode == "RGB"
+ assert p.img.mode == "RGBA"
+ assert p.circle_img.mode == "RGBA"
+ assert p.full_image.mode == "RGBA"
+
+ def test_draw_clear_background_colors(self, default_pyedgeon):
+ """Test that images are initialized with background color."""
+ p = default_pyedgeon
+
+ p.draw_clear()
+
+ # Check that images start with background color
+ # Sample a pixel from the center
+ center_x, center_y = p.img_side // 2, p.img_side // 2
+
+ raw_pixel = p.raw_img.getpixel((center_x, center_y))
+ assert raw_pixel == p.background_color
+
+ img_pixel = p.img.getpixel((center_x, center_y))
+ assert img_pixel[:3] == p.background_color
+
+
+class TestGetFontsize:
+ """Test the get_fontsize() method."""
+
+ def test_get_fontsize_basic(self, default_pyedgeon):
+ """Test basic font size calculation."""
+ p = default_pyedgeon
+ p.illusion_text = "TEST"
+
+ p.estimate_font_size()
+ p.draw_clear()
+ font_size, boundingbox = p.get_fontsize()
+
+ assert font_size is not None
+ assert boundingbox is not None
+ assert p.font_size == font_size
+ assert p.boundingbox == boundingbox
+
+ def test_get_fontsize_creates_font(self, default_pyedgeon):
+ """Test that get_fontsize creates font object."""
+ p = default_pyedgeon
+ p.illusion_text = "TEST"
+
+ p.estimate_font_size()
+ p.draw_clear()
+ p.get_fontsize()
+
+ assert hasattr(p, 'font')
+ assert p.font is not None
+
+ def test_get_fontsize_different_texts(self, default_pyedgeon):
+ """Test font size calculation with different texts."""
+ texts = ["A", "HELLO", "TESTING LONGER"]
+
+ for text in texts:
+ p = default_pyedgeon
+ p.illusion_text = text
+
+ p.estimate_font_size()
+ p.draw_clear()
+ font_size, _ = p.get_fontsize()
+
+ assert font_size is not None
+ assert font_size > 0
+
+ def test_get_fontsize_bounding_box(self, default_pyedgeon):
+ """Test that bounding box is calculated."""
+ p = default_pyedgeon
+ p.illusion_text = "TEST"
+
+ p.estimate_font_size()
+ p.draw_clear()
+ _, boundingbox = p.get_fontsize()
+
+ assert len(boundingbox) == 4
+ assert all(isinstance(x, int) for x in boundingbox)
+ # boundingbox = getbbox() offset by -crop_width, so the left/top edge can
+ # sit up to crop_width left/above origin depending on the font's side bearing
+ # (e.g. DejaVu on Linux yields -1). Upper bound stays within the image.
+ assert -p.crop_width_x <= boundingbox[0] < p.img_side
+ assert -p.crop_width_y <= boundingbox[1] < p.img_side
+
+
+class TestDrawFrame:
+ """Test the draw_frame() method."""
+
+ def test_draw_frame_basic(self, minimal_pyedgeon):
+ """Test basic frame drawing."""
+ p = minimal_pyedgeon
+
+ p.estimate_font_size()
+ p.draw_clear()
+ p.get_fontsize()
+ p.draw_frame()
+
+ # Verify images are modified
+ assert p.raw_img is not None
+ assert p.scaled_img is not None
+
+ def test_draw_frame_creates_scaled_image(self, minimal_pyedgeon):
+ """Test that draw_frame creates scaled image."""
+ p = minimal_pyedgeon
+
+ p.estimate_font_size()
+ p.draw_clear()
+ p.get_fontsize()
+ p.draw_frame()
+
+ assert hasattr(p, 'scaled_img')
+ assert p.scaled_img.size == (p.img_side, p.img_side)
+
+ def test_draw_frame_alpha_channel(self, minimal_pyedgeon):
+ """Test that draw_frame properly handles alpha channel."""
+ p = minimal_pyedgeon
+
+ p.estimate_font_size()
+ p.draw_clear()
+ p.get_fontsize()
+ p.draw_frame()
+
+ # Image should have alpha channel
+ assert p.img.mode == "RGBA"
+
+ # Some pixels should be transparent (alpha = 0)
+ pixels = list(p.img.getdata())
+ transparent_pixels = [px for px in pixels if px[3] == 0]
+ assert len(transparent_pixels) > 0
+
+
+class TestStamp:
+ """Test the stamp() method."""
+
+ def test_stamp_basic(self, minimal_pyedgeon):
+ """Test basic stamping functionality."""
+ p = minimal_pyedgeon
+
+ p.estimate_font_size()
+ p.draw_clear()
+ p.get_fontsize()
+ p.draw_frame()
+ p.stamp()
+
+ # Verify full_image is modified
+ assert p.full_image is not None
+
+ def test_stamp_rotation_count(self, font_path, temp_dir):
+ """Test stamping with different rotation counts."""
+ rotation_counts = [2, 4, 6, 8]
+
+ for num_rot in rotation_counts:
+ p = Pyedgeon(
+ illusion_text="ROT",
+ font_path=font_path,
+ file_path=temp_dir,
+ num_rotations=num_rot,
+ img_side=256
+ )
+
+ p.estimate_font_size()
+ p.draw_clear()
+ p.get_fontsize()
+ p.draw_frame()
+ p.stamp()
+
+ # Verify image was created
+ assert p.full_image is not None
+
+
+class TestAlphaToWhite:
+ """Test the alpha_to_white() method."""
+
+ def test_alpha_to_white_syntax_error(self, minimal_pyedgeon):
+ """Test that alpha_to_white works correctly (syntax error fixed)."""
+ p = minimal_pyedgeon
+
+ p.estimate_font_size()
+ p.draw_clear()
+ p.get_fontsize()
+ p.draw_frame()
+ p.stamp()
+
+ # Syntax error has been fixed - should work correctly
+ p.alpha_to_white()
+
+ # Verify the result
+ assert p.full_image is not None
+
+
+class TestSaveImg:
+ """Test the save_img() method."""
+
+ def test_save_img_creates_file(self, minimal_pyedgeon):
+ """Test that save_img creates a file."""
+ p = minimal_pyedgeon
+
+ # Due to syntax error, we can't run full create()
+ # This test documents the expected behavior
+ output_path = p.get_file_path()
+ assert not os.path.exists(output_path)
+
+ def test_save_img_custom_extension(self, font_path, temp_dir):
+ """Test saving with custom file extension."""
+ extensions = [".png", ".jpg", ".bmp"]
+
+ for ext in extensions:
+ p = Pyedgeon(
+ illusion_text="EXT",
+ font_path=font_path,
+ file_path=temp_dir,
+ file_ext=ext,
+ file_name=f"test_ext_{ext[1:]}",
+ img_side=256
+ )
+
+ output_path = p.get_file_path()
+ assert output_path.endswith(ext)
+
+
+class TestGetFilePath:
+ """Test the get_file_path() method."""
+
+ def test_get_file_path_with_custom_path(self, font_path, temp_dir):
+ """Test getting file path with custom directory."""
+ p = Pyedgeon(
+ illusion_text="PATH",
+ font_path=font_path,
+ file_path=temp_dir,
+ file_name="test_file"
+ )
+
+ output_path = p.get_file_path()
+
+ # get_file_path() calls Path.resolve(), which canonicalizes 8.3 short
+ # names on Windows (RUNNER~1 -> runneradmin) and /var -> /private/var on
+ # macOS. Compare against the resolved temp_dir so the check is portable.
+ assert os.path.realpath(temp_dir) in output_path
+ assert "test_file.png" in output_path
+
+ def test_get_file_path_empty_path_uses_cwd(self, font_path):
+ """Test that empty file_path uses current working directory."""
+ p = Pyedgeon(
+ illusion_text="CWD",
+ font_path=font_path,
+ file_path=""
+ )
+
+ output_path = p.get_file_path()
+
+ # Should contain current working directory
+ assert len(output_path) > 0
+
+ def test_get_file_path_includes_extension(self, font_path, temp_dir):
+ """Test that file path includes correct extension."""
+ extensions = [".png", ".jpg", ".gif"]
+
+ for ext in extensions:
+ p = Pyedgeon(
+ illusion_text="EXT",
+ font_path=font_path,
+ file_path=temp_dir,
+ file_ext=ext
+ )
+
+ output_path = p.get_file_path()
+ assert output_path.endswith(ext)
+
+ def test_get_file_path_uses_pathlib(self, font_path, temp_dir):
+ """Test that get_file_path properly uses pathlib."""
+ p = Pyedgeon(
+ illusion_text="PATHLIB",
+ font_path=font_path,
+ file_path=temp_dir,
+ file_name="test"
+ )
+
+ output_path = p.get_file_path()
+
+ # Should be a string (converted from Path)
+ assert isinstance(output_path, str)
+
+ # Should be a valid path
+ path_obj = Path(output_path)
+ assert path_obj.parent.exists()
+
+
+class TestFullPipeline:
+ """Test the complete image generation pipeline."""
+
+ def test_demo_function_exists(self):
+ """Test that demo() function exists and is importable."""
+ from pyedgeon.pyedgeon import demo
+
+ assert callable(demo)
+
+ def test_individual_steps_in_sequence(self, minimal_pyedgeon):
+ """Test running all steps individually in correct sequence."""
+ p = minimal_pyedgeon
+
+ # Step 1: Check length
+ p.check_length()
+ assert len(p.illusion_text) <= p.charmax
+
+ # Step 2: Estimate font size
+ p.estimate_font_size()
+ assert p.font_size_guess is not None
+
+ # Step 3: Draw clear images
+ p.draw_clear()
+ assert p.raw_img is not None
+
+ # Step 4: Get font size
+ p.get_fontsize()
+ assert p.font_size is not None
+
+ # Step 5: Draw frame
+ p.draw_frame()
+ assert p.scaled_img is not None
+
+ # Step 6: Stamp
+ p.stamp()
+ assert p.full_image is not None
+
+ # Step 7: Alpha to white (syntax error has been fixed)
+ p.alpha_to_white()
+
+ # Verify completion
+ assert p.full_image is not None
+
+
+class TestEdgeCases:
+ """Test edge cases and boundary conditions."""
+
+ def test_single_character_text(self, font_path, temp_dir):
+ """Test with single character text."""
+ p = Pyedgeon(
+ illusion_text="A",
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=256
+ )
+
+ p.check_length()
+ p.estimate_font_size()
+ p.draw_clear()
+ p.get_fontsize()
+
+ assert p.font_size is not None
+
+ def test_maximum_charmax_text(self, font_path, temp_dir):
+ """Test with text at maximum charmax."""
+ max_text = "A" * 22
+ p = Pyedgeon(
+ illusion_text=max_text,
+ font_path=font_path,
+ file_path=temp_dir,
+ charmax=22,
+ img_side=256
+ )
+
+ p.check_length()
+ assert len(p.illusion_text) == 22
+
+ def test_whitespace_only_text(self, font_path, temp_dir):
+ """Test that whitespace-only text is properly rejected."""
+ # Whitespace-only text now properly raises ValidationError during init
+ with pytest.raises(Exception):
+ p = Pyedgeon(
+ illusion_text=" ",
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=256
+ )
diff --git a/tests/test_initialization.py b/tests/test_initialization.py
new file mode 100644
--- /dev/null
+++ b/tests/test_initialization.py
@@ -0,0 +1,382 @@
+"""
+Unit tests for Pyedgeon initialization and parameter validation.
+
+Tests cover:
+- Constructor parameter handling
+- Default value assignments
+- Parameter validation
+- Type checking
+- Boundary conditions
+"""
+
+import pytest
+from pyedgeon import Pyedgeon
+
+
+class TestConstructorDefaults:
+ """Test that constructor sets appropriate default values."""
+
+ def test_default_illusion_text(self, font_path, temp_dir):
+ """Test default illusion text is set and uppercased."""
+ p = Pyedgeon(font_path=font_path, file_path=temp_dir)
+ assert p.illusion_text == "HELLO WORLD"
+
+ def test_default_num_rotations(self, font_path, temp_dir):
+ """Test default number of rotations."""
+ p = Pyedgeon(font_path=font_path, file_path=temp_dir)
+ assert p.num_rotations == 6
+
+ def test_default_file_ext(self, font_path, temp_dir):
+ """Test default file extension."""
+ p = Pyedgeon(font_path=font_path, file_path=temp_dir)
+ assert p.file_ext == ".png"
+
+ def test_default_text_color(self, font_path, temp_dir):
+ """Test default text color is black."""
+ p = Pyedgeon(font_path=font_path, file_path=temp_dir)
+ assert p.text_color == (0, 0, 0)
+
+ def test_default_background_color(self, font_path, temp_dir):
+ """Test default background color is white."""
+ p = Pyedgeon(font_path=font_path, file_path=temp_dir)
+ assert p.background_color == (255, 255, 255)
+
+ def test_default_img_side(self, font_path, temp_dir):
+ """Test default image side length."""
+ p = Pyedgeon(font_path=font_path, file_path=temp_dir)
+ assert p.img_side == 1024
+
+ def test_default_charmax(self, font_path, temp_dir):
+ """Test default character maximum."""
+ p = Pyedgeon(font_path=font_path, file_path=temp_dir)
+ assert p.charmax == 22
+
+ def test_default_crop_widths(self, font_path, temp_dir):
+ """Test default crop width values."""
+ p = Pyedgeon(font_path=font_path, file_path=temp_dir)
+ assert p.crop_width_x == 14
+ assert p.crop_width_y == 5
+
+ def test_default_darkness_threshold(self, font_path, temp_dir):
+ """Test default darkness threshold."""
+ p = Pyedgeon(font_path=font_path, file_path=temp_dir)
+ assert p.darkness_threshold == 116
+
+ def test_default_upper_case(self, font_path, temp_dir):
+ """Test that upper_case defaults to True."""
+ p = Pyedgeon(illusion_text="hello", font_path=font_path, file_path=temp_dir)
+ assert p.illusion_text == "HELLO"
+
+
+class TestTextHandling:
+ """Test text parameter handling and transformations."""
+
+ def test_uppercase_conversion(self, font_path, temp_dir):
+ """Test that text is converted to uppercase by default."""
+ p = Pyedgeon(
+ illusion_text="hello world",
+ font_path=font_path,
+ file_path=temp_dir
+ )
+ assert p.illusion_text == "HELLO WORLD"
+
+ def test_uppercase_disabled(self, font_path, temp_dir):
+ """Test that upper_case=False preserves original case."""
+ p = Pyedgeon(
+ illusion_text="Hello World",
+ font_path=font_path,
+ file_path=temp_dir,
+ upper_case=False
+ )
+ assert p.illusion_text == "Hello World"
+
+ def test_empty_string(self, font_path, temp_dir):
+ """Test that empty string is properly rejected."""
+ import pytest
+ # Validation now rejects empty strings
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ illusion_text="",
+ font_path=font_path,
+ file_path=temp_dir
+ )
+
+ def test_special_characters(self, font_path, temp_dir):
+ """Test handling of special characters."""
+ special_text = "HELLO! @#$%"
+ p = Pyedgeon(
+ illusion_text=special_text,
+ font_path=font_path,
+ file_path=temp_dir
+ )
+ assert p.illusion_text == special_text
+
+ def test_unicode_characters(self, font_path, temp_dir):
+ """Test handling of unicode characters."""
+ unicode_text = "HELLO \u2665" # Heart symbol
+ p = Pyedgeon(
+ illusion_text=unicode_text,
+ font_path=font_path,
+ file_path=temp_dir
+ )
+ assert p.illusion_text == unicode_text
+
+ def test_numeric_text(self, font_path, temp_dir):
+ """Test handling of numeric text."""
+ p = Pyedgeon(
+ illusion_text="123456",
+ font_path=font_path,
+ file_path=temp_dir
+ )
+ assert p.illusion_text == "123456"
+
+
+class TestColorParameters:
+ """Test color parameter validation and handling."""
+
+ def test_custom_text_color(self, font_path, temp_dir):
+ """Test setting custom text color."""
+ red = (255, 0, 0)
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ text_color=red
+ )
+ assert p.text_color == red
+
+ def test_custom_background_color(self, font_path, temp_dir):
+ """Test setting custom background color."""
+ blue = (0, 0, 255)
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ background_color=blue
+ )
+ assert p.background_color == blue
+
+ def test_grayscale_colors(self, font_path, temp_dir):
+ """Test grayscale color values."""
+ gray = (128, 128, 128)
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ text_color=gray
+ )
+ assert p.text_color == gray
+
+ def test_color_boundaries(self, font_path, temp_dir):
+ """Test color values at boundaries (0 and 255)."""
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ text_color=(0, 0, 0),
+ background_color=(255, 255, 255)
+ )
+ assert p.text_color == (0, 0, 0)
+ assert p.background_color == (255, 255, 255)
+
+
+class TestFileParameters:
+ """Test file path and naming parameter handling."""
+
+ def test_custom_file_name(self, font_path, temp_dir):
+ """Test setting custom file name."""
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ file_name="custom_name"
+ )
+ assert p.file_name == "custom_name"
+
+ def test_file_name_defaults_to_text(self, font_path, temp_dir):
+ """Test that file_name defaults to illusion_text."""
+ p = Pyedgeon(
+ illusion_text="TEST TEXT",
+ font_path=font_path,
+ file_path=temp_dir
+ )
+ assert p.file_name == "TEST TEXT"
+
+ def test_custom_file_extension(self, font_path, temp_dir):
+ """Test setting custom file extension."""
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ file_ext=".jpg"
+ )
+ assert p.file_ext == ".jpg"
+
+ def test_empty_file_path(self, font_path):
+ """Test that empty file_path is accepted."""
+ p = Pyedgeon(font_path=font_path, file_path="")
+ assert p.file_path == ""
+
+ def test_custom_file_path(self, font_path, temp_dir):
+ """Test setting custom file path."""
+ p = Pyedgeon(font_path=font_path, file_path=temp_dir)
+ assert p.file_path == temp_dir
+
+
+class TestImageSizeParameters:
+ """Test image size and dimension parameters."""
+
+ def test_custom_img_side(self, font_path, temp_dir):
+ """Test setting custom image side length."""
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=512
+ )
+ assert p.img_side == 512
+ assert p.img_size == (512, 512)
+
+ def test_small_image_size(self, font_path, temp_dir):
+ """Test with small image size."""
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=128
+ )
+ assert p.img_side == 128
+
+ def test_large_image_size(self, font_path, temp_dir):
+ """Test with large image size."""
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=2048
+ )
+ assert p.img_side == 2048
+
+ def test_img_size_tuple_creation(self, font_path, temp_dir):
+ """Test that img_size tuple is created correctly."""
+ side = 800
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=side
+ )
+ assert p.img_size == (side, side)
+ assert p.img_size_text == (side, side)
+
+
+class TestRotationParameters:
+ """Test rotation-related parameters."""
+
+ def test_custom_num_rotations(self, font_path, temp_dir):
+ """Test setting custom number of rotations."""
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ num_rotations=8
+ )
+ assert p.num_rotations == 8
+
+ def test_minimum_rotations(self, font_path, temp_dir):
+ """Test with minimum number of rotations."""
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ num_rotations=1
+ )
+ assert p.num_rotations == 1
+
+ def test_many_rotations(self, font_path, temp_dir):
+ """Test with many rotations."""
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ num_rotations=12
+ )
+ assert p.num_rotations == 12
+
+
+class TestCropParameters:
+ """Test crop width parameters."""
+
+ def test_custom_crop_width_x(self, font_path, temp_dir):
+ """Test setting custom crop_width_x."""
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ crop_width_x=20
+ )
+ assert p.crop_width_x == 20
+
+ def test_custom_crop_width_y(self, font_path, temp_dir):
+ """Test setting custom crop_width_y."""
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ crop_width_y=10
+ )
+ assert p.crop_width_y == 10
+
+ def test_zero_crop_widths(self, font_path, temp_dir):
+ """Test with zero crop widths."""
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ crop_width_x=0,
+ crop_width_y=0
+ )
+ assert p.crop_width_x == 0
+ assert p.crop_width_y == 0
+
+
+class TestDarknessThreshold:
+ """Test darkness threshold parameter."""
+
+ def test_custom_darkness_threshold(self, font_path, temp_dir):
+ """Test setting custom darkness threshold."""
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ darkness_threshold=100
+ )
+ assert p.darkness_threshold == 100
+
+ def test_threshold_boundaries(self, font_path, temp_dir):
+ """Test darkness threshold at boundaries."""
+ p_low = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ darkness_threshold=0
+ )
+ assert p_low.darkness_threshold == 0
+
+ p_high = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ darkness_threshold=255
+ )
+ assert p_high.darkness_threshold == 255
+
+
+class TestInitialState:
+ """Test the initial state of Pyedgeon object after construction."""
+
+ def test_font_size_initially_none(self, font_path, temp_dir):
+ """Test that font_size is None before calculation."""
+ p = Pyedgeon(font_path=font_path, file_path=temp_dir)
+ assert p.font_size is None
+
+ def test_font_size_guess_initially_none(self, font_path, temp_dir):
+ """Test that font_size_guess is None before estimation."""
+ p = Pyedgeon(font_path=font_path, file_path=temp_dir)
+ assert p.font_size_guess is None
+
+ def test_all_required_attributes_exist(self, font_path, temp_dir):
+ """Test that all expected attributes are set after initialization."""
+ p = Pyedgeon(font_path=font_path, file_path=temp_dir)
+
+ required_attrs = [
+ 'illusion_text', 'font_path', 'num_rotations', 'file_ext',
+ 'text_color', 'background_color', 'img_side', 'charmax',
+ 'file_path', 'font_size_guess', 'crop_width_x', 'crop_width_y',
+ 'darkness_threshold', 'img_size', 'img_size_text', 'file_name',
+ 'font_size'
+ ]
+
+ for attr in required_attrs:
+ assert hasattr(p, attr), f"Missing attribute: {attr}"
diff --git a/tests/test_performance.py b/tests/test_performance.py
new file mode 100644
--- /dev/null
+++ b/tests/test_performance.py
@@ -0,0 +1,482 @@
+"""
+Performance tests for Pyedgeon library.
+
+Tests cover:
+- Execution time benchmarks
+- Memory usage
+- Resource limits
+- Performance regressions
+- Scalability
+"""
+
+import time
+import pytest
+from pyedgeon import Pyedgeon
+
+
+class TestPerformanceBenchmarks:
+ """Benchmark tests for various operations."""
+
+ def test_initialization_performance(self, font_path, temp_dir, benchmark):
+ """Benchmark Pyedgeon initialization time."""
+ def create_instance():
+ return Pyedgeon(
+ illusion_text="BENCHMARK",
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=512
+ )
+
+ result = benchmark(create_instance)
+ assert result is not None
+
+ def test_estimate_font_size_performance(self, default_pyedgeon, benchmark):
+ """Benchmark font size estimation."""
+ p = default_pyedgeon
+ p.illusion_text = "PERFORMANCE TEST"
+
+ result = benchmark(p.estimate_font_size)
+ assert p.font_size_guess is not None
+
+ def test_check_length_performance(self, default_pyedgeon, benchmark):
+ """Benchmark check_length operation."""
+ p = default_pyedgeon
+ p.illusion_text = "SHORT TEXT"
+
+ benchmark(p.check_length)
+
+ @pytest.mark.slow
+ def test_draw_clear_performance(self, default_pyedgeon, benchmark):
+ """Benchmark draw_clear operation."""
+ p = default_pyedgeon
+
+ benchmark(p.draw_clear)
+ assert p.raw_img is not None
+
+ @pytest.mark.slow
+ def test_get_fontsize_performance(self, minimal_pyedgeon, benchmark):
+ """Benchmark get_fontsize operation."""
+ p = minimal_pyedgeon
+ p.illusion_text = "PERF"
+
+ p.estimate_font_size()
+ p.draw_clear()
+
+ result = benchmark(p.get_fontsize)
+ assert result is not None
+
+ @pytest.mark.slow
+ def test_full_create_performance_small(self, font_path, temp_dir):
+ """Benchmark full create() for small image."""
+ p = Pyedgeon(
+ illusion_text="SMALL",
+ font_path=font_path,
+ file_path=temp_dir,
+ file_name="perf_small",
+ img_side=256,
+ num_rotations=2
+ )
+
+ start = time.time()
+
+ # Note: Will fail due to syntax error, but measures time to failure
+ try:
+ p.create()
+ except TypeError:
+ pass # Expected due to line 215 syntax error
+
+ elapsed = time.time() - start
+
+ # Should complete (or fail) in reasonable time
+ assert elapsed < 10.0, f"Small image took {elapsed:.2f}s, expected < 10s"
+
+ @pytest.mark.slow
+ def test_full_create_performance_medium(self, font_path, temp_dir):
+ """Benchmark full create() for medium image."""
+ p = Pyedgeon(
+ illusion_text="MEDIUM",
+ font_path=font_path,
+ file_path=temp_dir,
+ file_name="perf_medium",
+ img_side=512,
+ num_rotations=4
+ )
+
+ start = time.time()
+
+ try:
+ p.create()
+ except TypeError:
+ pass # Expected due to line 215 syntax error
+
+ elapsed = time.time() - start
+
+ # Medium images should still be reasonably fast
+ assert elapsed < 30.0, f"Medium image took {elapsed:.2f}s, expected < 30s"
+
+
+class TestScalability:
+ """Test performance scaling with different parameters."""
+
+ @pytest.mark.slow
+ def test_scaling_with_text_length(self, font_path, temp_dir):
+ """Test performance scaling with text length.
+
+ Marked slow: this is a wall-clock ratio benchmark. Baselines here sit at
+ the clock-resolution/jitter floor on shared CI runners, so it runs only
+ in the full (single-OS) suite, not the multi-OS fast matrix.
+ """
+ text_lengths = [5, 10, 15, 20]
+ times = []
+
+ for length in text_lengths:
+ text = "A" * length
+ p = Pyedgeon(
+ illusion_text=text,
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=256
+ )
+
+ start = time.perf_counter()
+ p.estimate_font_size()
+ elapsed = time.perf_counter() - start
+
+ times.append(elapsed)
+
+ # Font size estimation should scale roughly linearly; verify it doesn't
+ # explode exponentially. Floor the baseline: estimate_font_size() is fast
+ # enough that timings approach the clock resolution (time.time() reads
+ # 0.0 on Windows), which would make the ratio meaningless.
+ baseline = max(times[0], 1e-4)
+ assert times[-1] < baseline * 10, "Performance degradation too severe"
+
+ def test_scaling_with_image_size(self, font_path, temp_dir):
+ """Test performance scaling with image size."""
+ sizes = [128, 256, 512]
+ times = []
+
+ for size in sizes:
+ p = Pyedgeon(
+ illusion_text="SCALE",
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=size
+ )
+
+ start = time.time()
+ p.draw_clear()
+ elapsed = time.time() - start
+
+ times.append(elapsed)
+
+ # Image creation should scale roughly quadratically with size
+ # (pixels increase as size^2)
+ for t in times:
+ assert t < 5.0, f"Image creation took {t:.2f}s, too slow"
+
+ @pytest.mark.slow
+ def test_scaling_with_num_rotations(self, font_path, temp_dir):
+ """Test performance scaling with number of rotations.
+
+ Marked slow: wall-clock ratio benchmark with a sub-millisecond baseline,
+ which is dominated by scheduler jitter on shared CI runners. Runs in the
+ full (single-OS) suite, not the multi-OS fast matrix.
+ """
+ rotation_counts = [2, 4, 6, 8]
+ times = []
+
+ for num_rot in rotation_counts:
+ p = Pyedgeon(
+ illusion_text="ROT",
+ font_path=font_path,
+ file_path=temp_dir,
+ num_rotations=num_rot,
+ img_side=256
+ )
+
+ p.estimate_font_size()
+ p.draw_clear()
+ p.get_fontsize()
+ p.draw_frame()
+
+ start = time.perf_counter()
+ p.stamp()
+ elapsed = time.perf_counter() - start
+
+ times.append(elapsed)
+
+ # Stamping should scale linearly with rotations. Floor the baseline:
+ # stamp() can finish below the clock resolution (time.time() reads 0.0 on
+ # Windows), collapsing the RHS to 0 and failing spuriously.
+ baseline = max(times[0], 1e-4)
+ assert times[-1] < baseline * (rotation_counts[-1] / rotation_counts[0]) * 2
+
+
+class TestNestedLoopPerformance:
+ """Test performance of nested pixel loops (known O(n²) issue)."""
+
+ @pytest.mark.slow
+ def test_draw_frame_nested_loops(self, font_path, temp_dir):
+ """Test nested loop performance in draw_frame."""
+ sizes = [128, 256, 512]
+ times = []
+
+ for size in sizes:
+ p = Pyedgeon(
+ illusion_text="LOOP",
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=size
+ )
+
+ p.estimate_font_size()
+ p.draw_clear()
+ p.get_fontsize()
+
+ start = time.time()
+ p.draw_frame()
+ elapsed = time.time() - start
+
+ times.append((size, elapsed))
+
+ # Verify quadratic scaling (or worse)
+ # Time should increase by ~4x when size doubles
+ for i in range(len(times) - 1):
+ size_ratio = times[i+1][0] / times[i][0]
+ time_ratio = times[i+1][1] / max(times[i][1], 0.001) # Avoid div by 0
+
+ # With nested loops, expect O(n²) scaling
+ # So doubling size should ~4x the time (but allow some overhead)
+ assert time_ratio < size_ratio ** 3, \
+ f"Performance worse than O(n²): {time_ratio} for {size_ratio}x size"
+
+ @pytest.mark.slow
+ def test_alpha_to_white_nested_loops(self, font_path, temp_dir):
+ """Test nested loop performance in alpha_to_white."""
+ # Note: This will fail due to syntax error, but we can still
+ # test the structure
+
+ sizes = [128, 256]
+ times = []
+
+ for size in sizes:
+ p = Pyedgeon(
+ illusion_text="ALPHA",
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=size
+ )
+
+ p.estimate_font_size()
+ p.draw_clear()
+ p.get_fontsize()
+ p.draw_frame()
+ p.stamp()
+
+ start = time.time()
+ try:
+ p.alpha_to_white()
+ except TypeError:
+ pass # Expected syntax error
+ elapsed = time.time() - start
+
+ times.append((size, elapsed))
+
+ # Even with the error, we measure the time to reach the error
+ # Shows the nested loop overhead before hitting the bug
+
+
+class TestFontSizeDiscoveryPerformance:
+ """Test performance of font size discovery algorithm."""
+
+ @pytest.mark.slow
+ def test_get_fontsize_temporary_images(self, minimal_pyedgeon):
+ """Test that get_fontsize creates many temporary images."""
+ p = minimal_pyedgeon
+ p.illusion_text = "FONT TEST"
+
+ p.estimate_font_size()
+ p.draw_clear()
+
+ # The algorithm tries 60 font sizes (guess-30 to guess+30)
+ # Each creates a temporary image
+ start = time.time()
+ p.get_fontsize()
+ elapsed = time.time() - start
+
+ # Should complete but documents the inefficiency
+ # Creating 60 images is wasteful
+ assert elapsed < 5.0, f"Font size discovery too slow: {elapsed:.2f}s"
+
+ def test_get_fontsize_recursion_count(self, font_path, temp_dir):
+ """Test that get_fontsize can recurse multiple times."""
+ # With wrong initial guess, it will recurse
+ # Each recursion tries 60 more font sizes
+
+ p = Pyedgeon(
+ illusion_text="RECURSION",
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=256
+ )
+
+ # Manually set a bad guess to force recursion
+ p.estimate_font_size()
+ p.draw_clear()
+ p.font_size_guess = 10 # Too small, will recurse
+
+ start = time.time()
+
+ # This might recurse several times
+ # Note: Could potentially recurse indefinitely!
+ try:
+ with pytest.raises(RecursionError):
+ # Set Python recursion limit low to catch unbounded recursion
+ import sys
+ old_limit = sys.getrecursionlimit()
+ sys.setrecursionlimit(100)
+
+ p.get_fontsize()
+
+ sys.setrecursionlimit(old_limit)
+ except:
+ # If it doesn't hit recursion limit, that's okay
+ # But it's still inefficient
+ pass
+
+ elapsed = time.time() - start
+
+ # Should not take forever
+ assert elapsed < 10.0
+
+
+class TestMemoryUsage:
+ """Test memory usage patterns."""
+
+ def test_multiple_image_objects(self, default_pyedgeon):
+ """Test that multiple image objects are created."""
+ p = default_pyedgeon
+
+ p.draw_clear()
+
+ # Documents that 4 separate images are created (default 512x512)
+ # This is ~4MB of memory (512*512*4 channels*4 images)
+ images = [p.raw_img, p.img, p.circle_img, p.full_image]
+
+ for img in images:
+ assert img.size == (p.img_side, p.img_side)
+ # Each image uses significant memory
+
+ @pytest.mark.slow
+ def test_memory_with_large_image(self, font_path, temp_dir):
+ """Test memory usage with large images."""
+ # Large image uses substantial memory
+ large_size = 2048
+
+ p = Pyedgeon(
+ illusion_text="MEMORY",
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=large_size
+ )
+
+ # Creating the images allocates memory
+ p.draw_clear()
+
+ # 4 images * 2048*2048 pixels * 4 bytes/pixel = ~64MB
+ assert p.img.size == (large_size, large_size)
+
+
+class TestResourceLimits:
+ """Test behavior at resource limits."""
+
+ def test_unrestricted_image_size(self, font_path, temp_dir):
+ """Test that image size is now properly restricted."""
+ # Validation now prevents huge sizes (max is 8192)
+
+ huge_size = 50000 # Would create 50000x50000 = 2.5B pixels
+
+ # Validation now properly rejects this
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ illusion_text="HUGE",
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=huge_size
+ )
+
+ def test_unrestricted_text_length(self, font_path, temp_dir):
+ """Test that text length is now properly restricted."""
+ # Validation now prevents very long text (max is 10000)
+
+ very_long = "A" * 100000
+
+ # Validation now properly rejects this
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ illusion_text=very_long,
+ font_path=font_path,
+ file_path=temp_dir
+ )
+
+ def test_unrestricted_num_rotations(self, font_path, temp_dir):
+ """Test that num_rotations is now properly restricted."""
+ # Validation now prevents excessive rotations (max is 360)
+
+ excessive = 10000
+
+ # Validation now properly rejects this
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ illusion_text="ROT",
+ font_path=font_path,
+ file_path=temp_dir,
+ num_rotations=excessive
+ )
+
+
+class TestRegression:
+ """Regression tests for performance improvements."""
+
+ @pytest.mark.slow
+ def test_baseline_small_image(self, font_path, temp_dir):
+ """Baseline performance test for small images."""
+ p = Pyedgeon(
+ illusion_text="BASELINE",
+ font_path=font_path,
+ file_path=temp_dir,
+ file_name="baseline_test",
+ img_side=256,
+ num_rotations=2
+ )
+
+ start = time.time()
+
+ # Run through all steps up to the syntax error
+ p.check_length()
+ p.estimate_font_size()
+ p.draw_clear()
+ p.get_fontsize()
+ p.draw_frame()
+ p.stamp()
+
+ elapsed = time.time() - start
+
+ # Baseline: should complete in under 5 seconds
+ assert elapsed < 5.0, \
+ f"Baseline performance regression: {elapsed:.2f}s (expected < 5s)"
+
+ # Store result for comparison in future test runs
+ print(f"\nBaseline performance: {elapsed:.2f}s for 256x256 image")
+
+
+# Pytest benchmark plugin integration
+pytest_plugins = ['pytest-benchmark']
+
+
+def pytest_configure(config):
+ """Configure custom markers."""
+ config.addinivalue_line(
+ "markers", "slow: marks tests as slow (deselect with '-m \"not slow\"')"
+ )
diff --git a/tests/test_security.py b/tests/test_security.py
new file mode 100644
--- /dev/null
+++ b/tests/test_security.py
@@ -0,0 +1,484 @@
+"""
+Security tests for Pyedgeon library.
+
+Tests cover:
+- Path traversal vulnerabilities
+- Input validation
+- Resource exhaustion protection
+- File system security
+- Injection attacks
+"""
+
+import os
+import pytest
+from pathlib import Path
+from pyedgeon import Pyedgeon
+
+
+class TestPathTraversalPrevention:
+ """Test protection against path traversal attacks."""
+
+ def test_file_path_traversal_parent_directory(self, font_path, temp_dir):
+ """Test that parent directory traversal in file_path is handled safely."""
+ malicious_path = "../../../etc"
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=malicious_path,
+ illusion_text="TEST"
+ )
+
+ # Validation now properly checks that output directory exists
+ # This will raise an error because ../../../etc likely doesn't exist
+ with pytest.raises(Exception): # Should raise ValidationError
+ output_path = p.get_file_path()
+
+ def test_file_path_absolute_system_path(self, font_path, temp_dir):
+ """Test that absolute system paths in file_path are accepted."""
+ # This tests whether the code accepts absolute paths to system directories
+ # Note: Users may legitimately want to write to specific absolute paths
+ malicious_paths = [
+ "/etc",
+ "/tmp/../etc",
+ "/var/log"
+ ]
+
+ for mal_path in malicious_paths:
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=mal_path,
+ illusion_text="TEST"
+ )
+ # Absolute paths are accepted (users may have legitimate use cases)
+ assert p.file_path == mal_path
+
+ def test_file_name_with_path_traversal(self, font_path, temp_dir):
+ """Test that file_name with path traversal is properly sanitized."""
+ malicious_names = [
+ "../../../etc/passwd",
+ "..\\..\\..\\windows\\system32\\config\\sam",
+ "./../../secret.txt"
+ ]
+
+ for mal_name in malicious_names:
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ file_name=mal_name,
+ illusion_text="TEST"
+ )
+ output_path = p.get_file_path()
+
+ # Verify dangerous characters are sanitized
+ # Path separators and dots should be removed or replaced
+ assert "../" not in output_path
+ assert "..\\" not in output_path
+ # Should still be within temp_dir (realpath resolves Windows 8.3
+ # short names and macOS /var -> /private/var so the compare is portable)
+ resolved_temp = os.path.realpath(temp_dir)
+ assert resolved_temp in output_path or output_path.startswith(resolved_temp)
+
+ def test_font_path_traversal(self, temp_dir):
+ """Test that font_path rejects paths with invalid extensions."""
+ malicious_font_paths = [
+ "../../../etc/passwd",
+ "/etc/shadow",
+ "C:\\Windows\\System32\\config\\SAM"
+ ]
+
+ for mal_path in malicious_font_paths:
+ # Font path validation now rejects non-font file extensions
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=mal_path,
+ file_path=temp_dir,
+ illusion_text="TEST"
+ )
+
+ def test_null_byte_injection_file_name(self, font_path, temp_dir):
+ """Test handling of null byte injection in file names."""
+ malicious_name = "safe_name\x00../../etc/passwd"
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ file_name=malicious_name,
+ illusion_text="TEST"
+ )
+ # Documents that null bytes are currently not filtered
+ assert "\x00" in p.file_name
+
+ def test_symlink_in_file_path(self, font_path, temp_dir):
+ """Test behavior when file_path contains symlinks."""
+ # Create a symlink to a different directory
+ symlink_path = Path(temp_dir) / "symlink"
+ target_path = Path(temp_dir) / "target"
+ target_path.mkdir(exist_ok=True)
+
+ try:
+ symlink_path.symlink_to(target_path)
+
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=str(symlink_path),
+ illusion_text="TEST"
+ )
+
+ # Verify symlinks are followed (current behavior)
+ assert p.file_path == str(symlink_path)
+ except OSError:
+ # Symlink creation might fail on some systems
+ pytest.skip("Symlink creation not supported")
+
+
+class TestInputValidation:
+ """Test validation of user inputs."""
+
+ def test_color_validation_out_of_range_high(self, font_path, temp_dir):
+ """Test that colors above 255 are properly rejected."""
+ # Validation now properly checks color ranges
+ invalid_color = (300, 300, 300)
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ text_color=invalid_color
+ )
+
+ def test_color_validation_negative(self, font_path, temp_dir):
+ """Test that negative color values are properly rejected."""
+ invalid_color = (-10, -20, -30)
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ text_color=invalid_color
+ )
+
+ def test_color_validation_wrong_type(self, font_path, temp_dir):
+ """Test that wrong color type is properly rejected."""
+ # Validation now checks that color is a 3-tuple
+ with pytest.raises(Exception): # Should raise ValidationError or TypeError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ text_color="red" # String instead of tuple
+ )
+
+ def test_color_validation_wrong_tuple_length(self, font_path, temp_dir):
+ """Test that wrong tuple length for color is properly rejected."""
+ invalid_colors = [
+ (255,), # Too short
+ (255, 255), # Too short
+ (255, 255, 255, 255), # Too long
+ ]
+
+ for invalid_color in invalid_colors:
+ # Validation now properly checks tuple length
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ text_color=invalid_color
+ )
+
+ def test_num_rotations_negative(self, font_path, temp_dir):
+ """Test that negative num_rotations is properly rejected."""
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ num_rotations=-5
+ )
+
+ def test_num_rotations_zero(self, font_path, temp_dir):
+ """Test that zero num_rotations is properly rejected."""
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ num_rotations=0
+ )
+
+ def test_img_side_negative(self, font_path, temp_dir):
+ """Test that negative img_side is properly rejected."""
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=-100
+ )
+
+ def test_img_side_zero(self, font_path, temp_dir):
+ """Test that zero img_side is properly rejected."""
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=0
+ )
+
+ def test_charmax_negative(self, font_path, temp_dir):
+ """Test that negative charmax is properly rejected."""
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ charmax=-10
+ )
+
+ def test_darkness_threshold_out_of_range(self, font_path, temp_dir):
+ """Test that darkness_threshold outside 0-255 is properly rejected."""
+ invalid_thresholds = [-10, 300, 1000]
+
+ for threshold in invalid_thresholds:
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ darkness_threshold=threshold
+ )
+
+
+class TestResourceExhaustion:
+ """Test protection against resource exhaustion attacks."""
+
+ def test_extremely_large_image_size(self, font_path, temp_dir):
+ """Test that extremely large image sizes are properly rejected."""
+ # An attacker could try to exhaust memory with huge images
+ huge_size = 100000 # 100k x 100k = 10 billion pixels
+
+ # Validation now prevents resource exhaustion (max is 8192)
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ img_side=huge_size,
+ illusion_text="A"
+ )
+
+ def test_extremely_long_text(self, font_path, temp_dir):
+ """Test that extremely long text (>10000 chars) is properly rejected."""
+ # Test with very long text that could cause performance issues
+ long_text = "A" * 10001 # Just over the 10000 limit
+
+ # Validation now rejects text over 10000 characters
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ illusion_text=long_text
+ )
+
+ def test_check_length_truncation_silent(self, font_path, temp_dir):
+ """Test that check_length() correctly truncates text to charmax."""
+ long_text = "A" * 50
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ illusion_text=long_text,
+ charmax=22
+ )
+
+ p.check_length()
+
+ # Verify text was correctly truncated to charmax (bug has been fixed!)
+ assert len(p.illusion_text) == 22
+
+ # Warning is logged (not printed to stdout)
+
+ def test_check_length_hardcoded_truncation(self, font_path, temp_dir):
+ """Test that truncation correctly uses charmax value (bug fixed)."""
+ long_text = "A" * 50
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ illusion_text=long_text,
+ charmax=30 # Set to 30
+ )
+
+ p.check_length()
+
+ # Bug has been fixed: now correctly truncates to charmax value
+ assert len(p.illusion_text) == 30
+
+ def test_many_rotations_performance(self, font_path, temp_dir):
+ """Test that excessive rotations are properly limited."""
+ excessive_rotations = 1000
+
+ # Validation now prevents excessive rotations (max is 360)
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ num_rotations=excessive_rotations,
+ illusion_text="A"
+ )
+
+
+class TestFileSystemSecurity:
+ """Test file system security issues."""
+
+ def test_file_overwrite_without_warning(self, font_path, temp_dir):
+ """Test that existing files are overwritten without warning."""
+ file_name = "test_file"
+ file_path = Path(temp_dir) / f"{file_name}.png"
+
+ # Create an existing file
+ file_path.write_text("existing content")
+ assert file_path.exists()
+
+ # Create Pyedgeon instance that will overwrite
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ file_name=file_name,
+ illusion_text="TEST"
+ )
+
+ # Verify it would overwrite (without actually running create()).
+ # get_file_path() resolves the path, so canonicalize the expected path
+ # too (Windows 8.3 short names, macOS /var -> /private/var).
+ result_path = p.get_file_path()
+ resolved_file = os.path.realpath(str(file_path))
+ assert resolved_file == result_path
+
+ def test_file_extension_validation(self, font_path, temp_dir):
+ """Test that dangerous file extensions are properly rejected."""
+ dangerous_extensions = [
+ ".exe",
+ ".sh",
+ ".bat",
+ ".ps1",
+ "", # No extension
+ ".png.exe", # Double extension
+ ]
+
+ for ext in dangerous_extensions:
+ # Validation now properly rejects dangerous extensions
+ with pytest.raises(Exception): # Should raise ValidationError
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ file_ext=ext,
+ illusion_text="TEST"
+ )
+
+ def test_font_file_existence_check(self, temp_dir):
+ """Test that non-existent font files are accepted during init."""
+ non_existent_font = "/path/to/nonexistent/font.ttf"
+
+ # Constructor accepts non-existent paths
+ p = Pyedgeon(
+ font_path=non_existent_font,
+ file_path=temp_dir,
+ illusion_text="TEST"
+ )
+
+ assert p.font_path == non_existent_font
+
+ def test_font_file_type_validation(self, temp_dir, fake_font_file):
+ """Test that non-font files with .ttf extension are accepted."""
+ # fake_font_file is not a valid font but has .ttf extension
+ p = Pyedgeon(
+ font_path=fake_font_file,
+ file_path=temp_dir,
+ illusion_text="TEST"
+ )
+
+ # Both point to the same file; realpath canonicalizes them (Windows 8.3
+ # short names, macOS /var -> /private/var) so the compare is portable.
+ assert os.path.realpath(fake_font_file) == os.path.realpath(p.font_path)
+
+
+class TestErrorHandling:
+ """Test error handling and exception management."""
+
+ def test_bare_except_in_get_fontsize(self, font_path, temp_dir):
+ """Test that bare except clause has been fixed in get_fontsize()."""
+ # Previously had a bare except clause which is a security risk
+ # Now properly uses specific exception handling
+
+ import inspect
+ from pyedgeon import Pyedgeon
+
+ source = inspect.getsource(Pyedgeon.get_fontsize)
+
+ # Verify bare except has been fixed - should use 'except Exception as e:' instead
+ assert "except Exception as e:" in source or "except (IOError, OSError)" in source
+ # Should NOT have bare except:
+ assert "except:" not in source or "except Exception" in source # Allow 'except Exception'
+
+ def test_unbounded_recursion_in_get_fontsize(self, font_path, temp_dir):
+ """Test that get_fontsize() has unbounded recursion."""
+ # The function can recurse indefinitely without a base case
+ # This is a potential denial of service vector
+
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ illusion_text="TEST",
+ img_side=256
+ )
+
+ # Set up conditions that would cause recursion
+ p.font_size_guess = 50
+
+ # Note: We don't actually call this to avoid stack overflow
+ # This test documents the risk
+ assert hasattr(p, 'get_fontsize')
+
+
+class TestSyntaxErrorDocumentation:
+ """Document the syntax error on line 215."""
+
+ def test_line_215_syntax_error_exists(self):
+ """Test that verifies the syntax error on line 215 has been fixed."""
+ # Line 215 previously had: self.background_color (255, )
+ # Now correctly fixed to: self.background_color + (255, )
+
+ import inspect
+ from pyedgeon import Pyedgeon
+
+ source = inspect.getsource(Pyedgeon.alpha_to_white)
+
+ # Verify the fix is in place - should use + operator, not function call
+ assert "self.background_color + (255," in source
+
+
+class TestInjectionVectors:
+ """Test for various injection attack vectors."""
+
+ def test_command_injection_in_file_path(self, font_path):
+ """Test that command injection in file_path is possible."""
+ # Potentially dangerous path with shell metacharacters
+ dangerous_paths = [
+ "; rm -rf /",
+ "$(malicious_command)",
+ "`malicious_command`",
+ "| cat /etc/passwd",
+ ]
+
+ for dangerous_path in dangerous_paths:
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=dangerous_path,
+ illusion_text="TEST"
+ )
+ # Currently no sanitization
+ assert dangerous_path in p.file_path
+
+ def test_format_string_in_text(self, font_path, temp_dir):
+ """Test handling of format string-like text."""
+ format_strings = [
+ "{0}",
+ "%s%s%s%s",
+ "${malicious}",
+ ]
+
+ for fmt_str in format_strings:
+ p = Pyedgeon(
+ font_path=font_path,
+ file_path=temp_dir,
+ illusion_text=fmt_str
+ )
+ # Verify format strings are not interpreted
+ assert p.illusion_text == fmt_str.upper()
diff --git a/tests/requirements-test.txt b/tests/requirements-test.txt
new file mode 100644
--- /dev/null
+++ b/tests/requirements-test.txt
@@ -0,0 +1,27 @@
+# Testing dependencies for pyedgeon
+
+# Core testing framework
+pytest>=7.0.0
+pytest-cov>=4.0.0
+pytest-xdist>=3.0.0 # For parallel test execution
+pytest-timeout>=2.1.0 # For timeout handling
+pytest-benchmark>=4.0.0 # For performance benchmarks
+
+# Code quality and coverage
+coverage>=7.0.0
+
+# Image testing and validation
+pillow>=9.0.0 # Should match main dependency
+
+# Mocking and fixtures
+pytest-mock>=3.10.0
+
+# Testing utilities
+pytest-html>=3.1.0 # HTML test reports
+pytest-json-report>=1.5.0 # JSON test reports
+
+# Security testing
+safety>=2.3.0 # Dependency vulnerability scanning
+
+# Additional utilities
+colorama>=0.4.6 # Colored terminal output
|