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
|
require 'test/unit'
# FIXME: This has platform-specific bits in it
class TestKernel < Test::Unit::TestCase
def test_EQUAL # '=='
o1 = Object.new
o2 = Object.new
assert(o1 == o1)
assert(o2 == o2)
assert(o1 != o2)
assert(!(o1 == o2))
end
def test_MATCH # '=~'
o1 = Object.new
o2 = Object.new
assert(!(o1 =~ o1))
assert(!(o2 =~ o2))
assert(o1 !~ o2)
assert(!(o1 =~ o2))
end
def test_VERY_EQUAL # '==='
o1 = Object.new
o2 = Object.new
assert(o1 === o1)
assert(o2 === o2)
assert(!(o1 === o2))
end
def test___id__
# naive test - no 2 ids the same
objs = []
ObjectSpace.each_object { |obj| objs << obj.__id__ }
objs.sort!
0.upto(objs.size-2) {|i| assert(objs[i] != objs[i+1]) }
assert_equal(1.__id__, (3-2).__id__)
assert_instance_of(Fixnum, 1.__id__)
end
class SendTest
def send_test1
"send1"
end
def send_test2(a, b)
a + b
end
end
def test___send__
t = SendTest.new
assert_equal("send1", t.__send__(:send_test1))
assert_equal(99, t.__send__("send_test2", 44, 55))
end
def test_class
assert_instance_of(Class, 1.class)
assert_equal(Fixnum, 1.class)
assert_equal(Class, TestKernel.class)
assert_equal(Class, TestKernel.class.class)
assert_equal(Module, Enumerable.class)
end
class CloneTest
attr_accessor :str
end
def test_clone
s1 = CloneTest.new
s1.str = "hello"
s2 = s1.clone
assert(s1.str == s2.str)
assert(s1.str.__id__ == s2.str.__id__)
assert(s1.__id__ != s2.__id__)
foo = Object.new
def foo.test
"test"
end
bar = foo.clone
def bar.test2
"test2"
end
assert_equal("test2", bar.test2)
assert_equal("test", bar.test)
assert_equal("test", foo.test)
Version.less_than("1.7") do
assert_raise(NameError) { foo.test2 }
end
Version.greater_or_equal("1.7") do
assert_raise(NoMethodError) { foo.test2 }
end
end
class DisplayTest
attr :val
def write(obj)
@val = "!#{obj.to_s}!"
end
end
def test_display
dt = DisplayTest.new
assert_nil("hello".display(dt))
assert_equal("!hello!", dt.val)
save = $>
begin
$> = dt
assert_nil("hello".display)
assert_equal("!hello!", dt.val)
ensure
$> = save
end
end
def test_dup
s1 = CloneTest.new
s1.str = "hello"
s2 = s1.dup
assert(s1.str == s2.str)
assert(s1.str.__id__ == s2.str.__id__)
assert(s1.__id__ != s2.__id__)
end
def test_eql?
o1 = Object.new
o2 = Object.new
assert(o1.eql?(o1))
assert(o2.eql?(o2))
assert(!(o1.eql?(o2)))
end
def test_equal?
o1 = Object.new
o2 = Object.new
assert(o1.equal?(o1))
assert(o2.equal?(o2))
assert(!(o1.equal?(o2)))
end
module ExtendTest1
def et1
"et1"
end
def et3
"et3.1"
end
end
module ExtendTest2
def et2
"et2"
end
def et3
"et3.2"
end
end
def test_extend
s = "hello"
assert(!defined?(s.et1))
s.extend(ExtendTest1)
assert_not_nil(defined?(s.et1))
assert(!defined?(s.et2))
assert_equal("et1", s.et1)
assert_equal("et3.1", s.et3)
s.extend(ExtendTest2)
assert_not_nil(defined?(s.et2))
assert_equal("et1", s.et1)
assert_equal("et2", s.et2)
assert_equal("et3.2", s.et3)
t = "goodbye"
t.extend(ExtendTest1)
t.extend(ExtendTest2)
assert_equal("et1", t.et1)
assert_equal("et2", t.et2)
assert_equal("et3.2", t.et3)
t = "goodbye"
t.extend(ExtendTest2)
t.extend(ExtendTest1)
assert_equal("et1", t.et1)
assert_equal("et2", t.et2)
assert_equal("et3.1", t.et3)
end
def test_freeze
s = "hello"
s[3] = "x"
eval %q{ def s.m1() "m1" end }
assert_equal("m1", s.m1)
s.freeze
assert(s.frozen?)
assert_raise(TypeError) { s[3] = 'y' }
assert_raise(TypeError) { eval %q{ def s.m1() "m1" end } }
assert_equal("helxo", s)
end
def test_frozen?
s = "hello"
assert(!s.frozen?)
assert(!self.frozen?)
s.freeze
assert(s.frozen?)
end
def test_hash
assert_instance_of(Fixnum, "hello".hash)
s1 = "hello"
s2 = "hello"
assert(s1.__id__ != s2.__id__)
assert(s1.eql?(s2))
assert(s1.hash == s2.hash)
s1[2] = 'x'
assert(s1.hash != s2.hash)
end
def test_id
objs = []
ObjectSpace.each_object { |obj| objs << obj.__id__ }
s1 = objs.size
assert_equal(s1, objs.uniq.size)
assert_equal(1.__id__, (3-2).__id__)
assert_instance_of(Fixnum, 1.__id__)
end
def test_inspect
assert_instance_of(String, 1.inspect)
assert_instance_of(String, /a/.inspect)
assert_instance_of(String, "hello".inspect)
assert_instance_of(String, self.inspect)
end
def test_instance_eval
s = "hello"
assert_equal(s, s.instance_eval { self } )
assert_equal("HELLO", s.instance_eval("upcase"))
end
def test_instance_of?
s = "hello"
assert(s.instance_of?(String))
assert(!s.instance_of?(Object))
assert(!s.instance_of?(Class))
assert(self.instance_of?(TestKernel))
end
class IVTest1
end
class IVTest2
def initialize
@var1 = 1
@var2 = 2
end
end
def test_instance_variables
o = IVTest1.new
assert_equal([], o.instance_variables)
o = IVTest2.new
assert_bag_equal(%w(@var1 @var2), o.instance_variables)
end
def test_is_a?
s = "hello"
assert(s.is_a?(String))
assert(s.is_a?(Object))
assert(!s.is_a?(Class))
assert(self.is_a?(TestKernel))
assert(TestKernel.is_a?(Class))
assert(TestKernel.is_a?(Module))
assert(TestKernel.is_a?(Object))
a = []
assert(a.is_a?(Array))
assert(a.is_a?(Enumerable))
end
def test_kind_of?
s = "hello"
assert(s.kind_of?(String))
assert(s.kind_of?(Object))
assert(!s.kind_of?(Class))
assert(self.kind_of?(TestKernel))
assert(TestKernel.kind_of?(Class))
assert(TestKernel.kind_of?(Module))
assert(TestKernel.kind_of?(Object))
a = []
assert(a.kind_of?(Array))
assert(a.kind_of?(Enumerable))
end
def MethodTest1
"mt1"
end
def MethodTest2(a, b, c)
a + b + c
end
def test_method
assert_raise(NameError) { self.method(:wombat) }
m = self.method("MethodTest1")
assert_instance_of(Method, m)
assert_equal("mt1", m.call)
assert_raise(ArgumentError) { m.call(1, 2, 3) }
m = self.method("MethodTest2")
assert_instance_of(Method, m)
assert_equal(6, m.call(1, *[2, 3]))
assert_raise(ArgumentError) { m.call(1, 3) }
end
class MethodMissing
def method_missing(m, *a)
return [m, a]
end
def mm
return "mm"
end
end
def test_method_missing
mm = MethodMissing.new
assert_equal("mm", mm.mm)
assert_equal([ :dave, []], mm.dave)
assert_equal([ :dave, [1, 2, 3]], mm.dave(1, *[2, 3]))
end
class MethodsTest
def MethodsTest.singleton
end
def one
end
def two
end
def three
end
def four
end
private :two
protected :three
end
def test_methods
assert_bag_equal(TestKernel.instance_methods(true), self.methods)
assert_bag_equal(%w(one three four) + Object.instance_methods(true),
MethodsTest.new.methods)
end
def test_nil?
assert(!self.nil?)
assert(nil.nil?)
a = []
assert(a[99].nil?)
end
class PrivateMethods < MethodsTest
def five
end
def six
end
def seven
end
private :six
protected :seven
end
def test_private_methods
assert_bag_equal(%w(two six) + Object.new.private_methods,
PrivateMethods.new.private_methods)
end
def test_protected_methods
assert_bag_equal(%w(three seven) + Object.new.protected_methods,
PrivateMethods.new.protected_methods)
end
def test_public_methods
assert_bag_equal(TestKernel.instance_methods(true), self.public_methods)
assert_bag_equal(%w(one four) + Object.instance_methods(true),
MethodsTest.new.public_methods)
end
def test_respond_to?
assert(self.respond_to?(:test_respond_to?))
assert(!self.respond_to?(:TEST_respond_to?))
mt = PrivateMethods.new
# public
assert(mt.respond_to?("five"))
assert(mt.respond_to?(:one))
assert(mt.respond_to?("five", true))
assert(mt.respond_to?(:one, false))
# protected
assert(mt.respond_to?("seven"))
assert(mt.respond_to?(:three))
assert(mt.respond_to?("seven", true))
assert(mt.respond_to?(:three, false))
#private
assert(!mt.respond_to?(:two))
assert(!mt.respond_to?("six"))
assert(mt.respond_to?(:two, true))
assert(mt.respond_to?("six", true))
end
def test_send
t = SendTest.new
assert_equal("send1", t.send(:send_test1))
assert_equal(99, t.send("send_test2", 44, 55))
end
def test_singleton_methods
assert_equal(%w(singleton), MethodsTest.singleton_methods)
assert_equal(%w(singleton), PrivateMethods.singleton_methods)
mt = MethodsTest.new
assert_equal([], mt.singleton_methods)
eval "def mt.wombat() end"
assert_equal(%w(wombat), mt.singleton_methods)
end
def test_taint
a = "hello"
assert(!a.tainted?)
assert_equal(a, a.taint)
assert(a.tainted?)
end
def test_tainted?
a = "hello"
assert(!a.tainted?)
assert_equal(a, a.taint)
assert(a.tainted?)
end
def test_to_a
Version.less_than("1.7.2") do
o = Object.new
assert_equal([o], o.to_a) # rest tested in individual classes
end
end
def test_to_s
o = Object.new
assert_match(/^#<Object:0x[0-9a-f]+>/, o.to_s)
end
def test_type
assert_instance_of(Class, self.class)
assert_equal(TestKernel, self.class)
assert_equal(String, "hello".class)
assert_equal(Bignum, (10**40).class)
end
def test_untaint
a = "hello"
assert(!a.tainted?)
assert_equal(a, a.taint)
assert(a.tainted?)
assert_equal(a, a.untaint)
assert(!a.tainted?)
a = "hello"
assert(!a.tainted?)
assert_equal(a, a.untaint)
assert(!a.tainted?)
end
class Caster
def to_a
[4, 5, 6]
end
def to_f
2.34
end
def to_i
99
end
def to_s
"Hello"
end
end
def test_s_Array
Version.less_than("1.7.2") do
assert_equal([], Array(nil))
end
assert_equal([1, 2, 3], Array([1, 2, 3]))
assert_equal([1, 2, 3], Array(1..3))
assert_equal([4, 5, 6], Array(Caster.new))
end
def test_s_Float
assert_instance_of(Float, Float(1))
assert_flequal(1, Float(1))
assert_flequal(1.23, Float('1.23'))
assert_flequal(2.34, Float(Caster.new))
end
def test_s_Integer
assert_instance_of(Fixnum, Integer(1))
assert_instance_of(Bignum, Integer(10**30))
assert_equal(123, Integer(123.99))
assert_equal(-123, Integer(-123.99))
a = Integer(1.0e30) - 10**30
assert(a.abs < 10**20)
assert_equal(99, Integer(Caster.new))
end
def test_s_String
assert_instance_of(String, String(123))
assert_equal("123", String(123))
assert_equal("123.45", String(123.45))
assert_equal("123", String([1, 2, 3]))
assert_equal("Hello", String(Caster.new))
end
def test_s_BACKTICK
assert_equal("hello\n", `echo hello`)
assert_equal(0, $?)
MsWin32.dont do
assert_equal("", `not_a_valid_command 2>/dev/null`)
end
MsWin32.only do
assert_equal("", `not_a_valid_command 2>nul`)
end
assert($? != 0)
assert_equal("hello\n", %x{echo hello})
assert_equal(0, $?)
MsWin32.dont do
assert_equal("", %x{not_a_valid_command 2>/dev/null})
end
MsWin32.only do
assert_equal("", %x{not_a_valid_command 2>nul})
end
assert($? != 0)
end
def test_s_abort
p = IO.popen("#$interpreter -e 'abort;exit 99'")
p.close
assert_equal(1<<8, $?)
end
def test_s_at_exit
script = %{at_exit {puts "world"};at_exit {puts "cruel"};puts "goodbye";exit 99}
p = IO.popen("#$interpreter -e '#{script}'")
begin
assert_equal("goodbye\n", p.gets)
assert_equal("cruel\n", p.gets)
assert_equal("world\n", p.gets)
ensure
p.close
assert_equal(99<<8, $?)
end
end
def test_s_autoload
File.open("_dummy.rb", "w") do |f|
f.print <<-EOM
module Module_Test
VAL = 123
end
EOM
end
assert(!defined? Module_Test)
autoload(:Module_Test, "./_dummy.rb")
assert_not_nil(defined? Module_Test::VAL)
assert_equal(123, Module_Test::VAL)
assert($".include?("./_dummy.rb"))#"
File.delete("./_dummy.rb")
end
def bindproc(val)
return binding
end
def test_s_binding
val = 123
b = binding
assert_instance_of(Binding, b)
assert_equal(123, eval("val", b))
b = bindproc(321)
assert_equal(321, eval("val", b))
end
def blocker1
return block_given?
end
def blocker2(&p)
return block_given?
end
def test_s_block_given?
assert(!blocker1())
assert(!blocker2())
assert(blocker1() { 1 })
assert(blocker2() { 1 })
end
def callcc_test(n)
cont = nil
callcc { |cont|
return [cont, n]
}
n -= 1
return [n.zero? ? nil : cont, n ]
end
def test_s_callcc
res = nil
cont = nil
assert_equal(2,
callcc { |cont|
res = 1
res = 2
})
assert_equal(2, res)
res = nil
assert_equal(99,
callcc { |cont|
res = 1
cont.call 99
res = 2
})
assert_equal(1, res)
# Test gotos!
callcc { |cont| res = 0 }
res += 1
cont.call if res < 4
assert_equal(4, res)
# Test reactivating procedures
n = 4
cont, res = callcc_test(4)
assert_equal(n, res)
n -= 1
puts cont.call if cont
end
def caller_test
return caller
end
def test_s_caller
c = caller_test
assert_match(%r{TestKernel.rb:#{__LINE__-1}:in `test_s_caller'}, c[0])
end #`
def catch_test
throw :c, 456;
789;
end
def test_s_catch
assert_equal(123, catch(:c) { a = 1; 123 })
assert_equal(321, catch(:c) { a = 1; throw :c, 321; 123 })
assert_equal(456, catch(:c) { a = 1; catch_test; 123 })
assert_equal(456, catch(:c) { catch(:d) { catch_test; 123 } } )
end
def test_s_chomp
$_ = "hello"
assert_equal("hello", chomp)
assert_equal("hello", chomp('aaa'))
assert_equal("he", chomp('llo'))
assert_equal("he", $_)
a = "hello\n"
$_ = a
assert_equal("hello", chomp)
assert_equal("hello", $_)
assert_equal("hello\n", a)
end
def test_s_chomp!
$_ = "hello"
assert_equal(nil, chomp!)
assert_equal(nil, chomp!('aaa'))
assert_equal("he", chomp!('llo'))
assert_equal("he", $_)
a = "hello\n"
$_ = a
assert_equal("hello", chomp!)
assert_equal("hello", $_)
assert_equal("hello", a)
end
def test_s_chop
a = "hi"
$_ = a
assert_equal("h", chop)
assert_equal("h", $_)
assert_equal("", chop)
assert_equal("", $_)
assert_equal("", chop)
assert_equal("hi", a)
$_ = "hi\n"
assert_equal("hi", chop)
$_ = "hi\r\n"
assert_equal("hi", chop)
$_ = "hi\n\r"
assert_equal("hi\n", chop)
end
def test_s_chop!
a = "hi"
$_ = a
assert_equal("h", chop!)
assert_equal("h", $_)
assert_equal("", chop!)
assert_equal("", $_)
assert_equal(nil, chop!)
assert_equal("", $_)
assert_equal("", a)
$_ = "hi\n"
assert_equal("hi", chop!)
$_ = "hi\r\n"
assert_equal("hi", chop!)
$_ = "hi\n\r"
assert_equal("hi\n", chop!)
end
def test_s_eval
assert_equal(123, eval("100 + 20 + 3"))
val = 123
assert_equal(123, eval("val", binding))
assert_equal(321, eval("val", bindproc(321)))
skipping("Check of eval with file name")
begin
eval "1
burble", binding, "gumby", 321
rescue Exception => detail
end
end
def test_s_exec
open("xyzzy.dat", "w") { |f| f.puts "stuff" }
tf = Tempfile.new("tf")
begin
# all in one string - wildcards get expanded
tf.puts 'exec("echo xy*y.dat")'
tf.close
IO.popen("#$interpreter #{tf.path}") do |p|
assert_equal("xyzzy.dat\n", p.gets)
end
# with two parameters, the '*' doesn't get expanded
tf.open
tf.puts 'exec("echo", "xy*y.dat")'
tf.close
IO.popen("#$interpreter #{tf.path}") do |p|
assert_equal("xy*y.dat\n", p.gets)
end
ensure
tf.close(true)
File.unlink "xyzzy.dat" if p
end
end
def test_s_exit
begin
exit
fail("No exception raised")
rescue SystemExit
assert(true)
rescue Exception
fail("Bad exception: #$!")
end
p = IO.popen("#$interpreter -e 'exit'")
p.close
assert_equal(0, $?)
p = IO.popen("#$interpreter -e 'exit 123'")
p.close
assert_equal(123 << 8, $?)
end
def test_s_exit!
tf = Tempfile.new("tf")
tf.puts %{
begin
exit! 99
exit 1
rescue SystemExit
exit 2
rescue Exception
exit 3
end
exit 4}
tf.close
IO.popen("#$interpreter #{tf.path}").close
assert_equal(99<<8, $?)
IO.popen("#$interpreter -e 'exit!'").close
Version.less_than("1.8.1") do
assert_equal(0xff << 8, $?)
end
Version.greater_or_equal("1.8.1") do
assert_equal(1 << 8, $?)
end
IO.popen("#$interpreter -e 'exit! 123'").close
assert_equal(123 << 8, $?)
ensure
tf.close(true)
end
def test_s_fail
begin
fail
rescue StandardError
assert(true)
rescue Exception
fail("Wrong exception raised")
end
begin
fail "Wombat"
rescue StandardError => detail
assert_equal("Wombat", detail.message)
rescue Exception
fail("Wrong exception raised")
end
assert_raise(NotImplementedError) { fail NotImplementedError }
begin
fail "Wombat"
fail("No exception")
rescue StandardError => detail
assert_equal("Wombat", detail.message)
rescue Exception
fail("Wrong exception raised")
end
begin
fail NotImplementedError, "Wombat"
fail("No exception")
rescue NotImplementedError => detail
assert_equal("Wombat", detail.message)
rescue Exception
fail("Wrong exception raised")
end
bt = %w(one two three)
begin
fail NotImplementedError, "Wombat", bt
fail("No exception")
rescue NotImplementedError => detail
assert_equal("Wombat", detail.message)
assert_equal(bt, detail.backtrace)
rescue Exception
fail("Wrong exception raised")
end
end
MsWin32.dont do
def test_s_fork
f = fork
if f.nil?
File.open("_pid", "w") {|f| f.puts $$}
exit 99
end
begin
Process.wait
assert_equal(99<<8, $?)
File.open("_pid") do |file|
assert_equal(file.gets.to_i, f)
end
ensure
File.delete("_pid")
end
f = fork do
File.open("_pid", "w") {|f| f.puts $$}
end
begin
Process.wait
assert_equal(0<<8, $?)
File.open("_pid") do |file|
assert_equal(file.gets.to_i, f)
end
ensure
File.delete("_pid")
end
end
end
def test_s_format
assert_equal("00123", format("%05d", 123))
assert_equal("123 |00000001", format("%-5s|%08x", 123, 1))
x = format("%3s %-4s%%foo %.0s%5d %#x%c%3.1f %b %x %X %#b %#x %#X",
"hi",
123,
"never seen",
456,
0,
?A,
3.0999,
11,
171,
171,
11,
171,
171)
assert_equal(' hi 123 %foo 456 0x0A3.1 1011 ab AB 0b1011 0xab 0XAB', x)
end
def setupFiles
setupTestDir
File.open("_test/_file1", "w") do |f|
f.puts "0: Line 1"
f.puts "1: Line 2"
end
File.open("_test/_file2", "w") do |f|
f.puts "2: Line 1"
f.puts "3: Line 2"
end
ARGV.replace ["_test/_file1", "_test/_file2" ]
end
def teardownFiles
teardownTestDir
end
def test_s_gets1
setupFiles
begin
count = 0
while gets
num = $_[0..1].to_i
assert_equal(count, num)
count += 1
end
assert_equal(4, count)
ensure
teardownFiles
end
end
def test_s_gets2
setupFiles
begin
count = 0
while gets(nil)
split(/\n/).each do |line|
num = line[0..1].to_i
assert_equal(count, num)
count += 1
end
end
assert_equal(4, count)
ensure
teardownFiles
end
end
def test_s_gets3
setupFiles
begin
count = 0
while gets(' ')
count += 1
end
assert_equal(10, count)
ensure
teardownFiles
end
end
def test_s_global_variables
g1 = global_variables
assert_instance_of(Array, g1)
assert_instance_of(String, g1[0])
assert(!g1.include?("$fred"))
eval "$fred = 1"
g2 = global_variables
assert(g2.include?("$fred"))
assert_equal(["$fred"], g2 - g1)
end
def test_s_gsub
$_ = "hello"
assert_equal("h*ll*", gsub(/[aeiou]/, '*'))
assert_equal("h*ll*", $_)
$_ = "hello"
assert_equal("h<e>ll<o>", gsub(/([aeiou])/, '<\1>'))
assert_equal("h<e>ll<o>", $_)
$_ = "hello"
assert_equal("104 101 108 108 111 ", gsub(/./) {
|s| s[0].to_s+' '})
assert_equal("104 101 108 108 111 ", $_)
$_ = "hello"
assert_equal("HELL-o", gsub(/(hell)(.)/) {
|s| $1.upcase + '-' + $2
})
assert_equal("HELL-o", $_)
$_ = "hello"
$_.taint
assert_equal(true, (gsub(/./,'X').tainted?))
assert_equal(true, $_.tainted?)
end
def test_s_gsub!
$_ = "hello"
assert_equal("h*ll*", gsub!(/[aeiou]/, '*'))
assert_equal("h*ll*", $_)
$_ = "hello"
assert_equal("h<e>ll<o>", gsub!(/([aeiou])/, '<\1>'))
assert_equal("h<e>ll<o>", $_)
$_ = "hello"
assert_equal("104 101 108 108 111 ", gsub!(/./) {
|s| s[0].to_s+' '})
assert_equal("104 101 108 108 111 ", $_)
$_ = "hello"
assert_equal("HELL-o", gsub!(/(hell)(.)/) {
|s| $1.upcase + '-' + $2
})
assert_equal("HELL-o", $_)
$_ = "hello"
assert_equal(nil, gsub!(/x/, 'y'))
assert_equal("hello", $_)
$_ = "hello"
$_.taint
assert_equal(true, (gsub!(/./,'X').tainted?))
assert_equal(true, $_.tainted?)
end
def iterator_test(&b)
return iterator?
end
def test_s_iterator?
assert(iterator_test { 1 })
assert(!iterator_test)
end
def test_s_lambda
a = lambda { "hello" }
assert_equal("hello", a.call)
a = lambda { |s| "there " + s }
assert_equal("there Dave", a.call("Dave"))
end
def test_s_load
File.open("_dummy_load.rb", "w") do |f|
f.print <<-EOM
module Module_Load
VAL = 234
end
EOM
end
assert(!defined? Module_Load)
load("./_dummy_load.rb")
assert_not_nil(defined? Module_Load::VAL)
assert_equal(234, Module_Load::VAL)
assert(!$".include?("./_dummy_load.rb"))#"
# Prove it's reloaded
File.open("_dummy_load.rb", "w") do |f|
f.print <<-EOM
module Module_Load
VAL1 = 456
end
EOM
end
load("./_dummy_load.rb")
assert_equal(456, Module_Load::VAL1)
# check that the sandbox works
File.open("_dummy_load.rb", "w") do |f|
f.print <<-EOM
GLOBAL_VAL = 789
EOM
end
load("./_dummy_load.rb", true)
assert(!defined? GLOBAL_VAL)
load("./_dummy_load.rb", false)
assert_not_nil(defined? GLOBAL_VAL)
assert_equal(789, GLOBAL_VAL)
File.delete("./_dummy_load.rb")
end
def local_variable_test(c)
d = 2
local_variables
end
def test_s_local_variables
assert_bag_equal(%w(a), local_variables)
eval "b = 1"
assert_bag_equal(%w(a b), local_variables)
assert_bag_equal(%w(c d), local_variable_test(1))
a = 1
end
# This is a lame test--can we do better?
def test_s_loop
a = 0
loop do
a += 1
break if a > 4
end
assert_equal(5, a)
end
# regular files
def test_s_open1
setupTestDir
begin
file1 = "_test/_file1"
assert_raise(Errno::ENOENT) { File.open("_gumby") }
# test block/non block forms
f = open(file1)
begin
assert_instance_of(File, f)
ensure
f.close
end
assert_nil(open(file1) { |f| assert_equal(File, f.class)})
# test modes
modes = [
%w( r w r+ w+ a a+ ),
[ File::RDONLY,
File::WRONLY | File::CREAT,
File::RDWR,
File::RDWR + File::TRUNC + File::CREAT,
File::WRONLY + File::APPEND + File::CREAT,
File::RDWR + File::APPEND + File::CREAT
]]
for modeset in modes
sys("rm -f #{file1}")
sys("touch #{file1}")
mode = modeset.shift # "r"
# file: empty
open(file1, mode) { |f|
assert_nil(f.gets)
assert_raise(IOError) { f.puts "wombat" }
}
mode = modeset.shift # "w"
# file: empty
open(file1, mode) { |f|
assert_nil(f.puts("wombat"))
assert_raise(IOError) { f.gets }
}
mode = modeset.shift # "r+"
# file: wombat
open(file1, mode) { |f|
assert_equal("wombat\n", f.gets)
assert_nil(f.puts("koala"))
f.rewind
assert_equal("wombat\n", f.gets)
assert_equal("koala\n", f.gets)
}
mode = modeset.shift # "w+"
# file: wombat/koala
open(file1, mode) { |f|
assert_nil(f.gets)
assert_nil(f.puts("koala"))
f.rewind
assert_equal("koala\n", f.gets)
}
mode = modeset.shift # "a"
# file: koala
open(file1, mode) { |f|
assert_nil(f.puts("wombat"))
assert_raise(IOError) { f.gets }
}
mode = modeset.shift # "a+"
# file: koala/wombat
open(file1, mode) { |f|
assert_nil(f.puts("wallaby"))
f.rewind
assert_equal("koala\n", f.gets)
assert_equal("wombat\n", f.gets)
assert_equal("wallaby\n", f.gets)
}
end
# Now try creating files
filen = "_test/_filen"
open(filen, "w") {}
begin
assert(File.exists?(filen))
ensure
File.delete(filen)
end
Version.greater_or_equal("1.7") do
open(filen, "w", 0444) {}
begin
assert(File.exists?(filen))
Cygwin.known_problem do
assert_equal(0444 & ~File.umask, File.stat(filen).mode & 0777)
end
ensure
WindowsNative.or_variant do
# to be able to delete the file on Windows
File.chmod(0666, filen)
end
File.delete(filen)
end
end
ensure
teardownTestDir # also does a chdir
end
end
def setup_s_open2
setupTestDir
@file = "_test/_10lines"
File.open(@file, "w") do |f|
10.times { |i| f.printf "%02d: This is a line\n", i }
end
end
# pipes
def test_s_open2
setup_s_open2
begin
assert_nil(open("| echo hello") do |f|
assert_equal("hello\n", f.gets)
end)
# READ
p = open("|#$interpreter -e 'puts readlines' <#@file")
begin
count = 0
p.each do |line|
num = line[0..1].to_i
assert_equal(count, num)
count += 1
end
assert_equal(10, count)
ensure
p.close
end
# READ with block
res = open("|#$interpreter -e 'puts readlines' <#@file") do |p|
count = 0
p.each do |line|
num = line[0..1].to_i
assert_equal(count, num)
count += 1
end
assert_equal(10, count)
end
assert_nil(res)
# WRITE
p = open("|#$interpreter -e 'puts readlines' >#@file", "w")
begin
5.times { |i| p.printf "Line %d\n", i }
ensure
p.close
end
count = 0
IO.foreach(@file) do |line|
num = line.chomp[-1,1].to_i
assert_equal(count, num)
count += 1
end
assert_equal(5, count)
# Spawn an interpreter
MsWin32.dont do
parent = $$
p = open("|-")
if p
begin
assert_equal(parent, $$)
assert_equal("Hello\n", p.gets)
ensure
p.close
end
else
assert_equal(parent, Process.ppid)
puts "Hello"
exit
end
end
# Spawn an interpreter - WRITE
MsWin32.dont do
parent = $$
pipe = open("|-", "w")
if pipe
begin
assert_equal(parent, $$)
pipe.puts "12"
Process.wait
assert_equal(12, $?>>8)
ensure
pipe.close
end
else
buff = $stdin.gets
exit buff.to_i
end
end
# Spawn an interpreter - READWRITE
MsWin32.dont do
parent = $$
p = open("|-", "w+")
if p
begin
assert_equal(parent, $$)
p.puts "Hello\n"
assert_equal("Goodbye\n", p.gets)
Process.wait
ensure
p.close
end
else
puts "Goodbye" if $stdin.gets == "Hello\n"
exit
end
end
ensure
teardownTestDir
end
end
MacOS.only do
undef test_s_open2
end
def test_s_p
tf = Tempfile.new("tf")
begin
tf.puts %{
class PTest2
def inspect
"ptest2"
end
end
p 1
p PTest2.new
exit}
tf.close
IO.popen("#$interpreter #{tf.path}") do |pipe|
assert_equal("1\n", pipe.gets)
assert_equal("ptest2\n", pipe.gets)
end
ensure
tf.close(true)
end
end
def test_s_print
tf = Tempfile.new("tf")
begin
tf.puts %{
class PrintTest
def to_s
"printtest"
end
end
print 1
print PrintTest.new
print "\n"
$, = ":"
print 1, "cat", PrintTest.new, "\n"
exit}
tf.close
IO.popen("#$interpreter #{tf.path}") do |pipe|
assert_equal("1printtest\n", pipe.gets)
assert_equal("1:cat:printtest:\n", pipe.gets)
end
ensure
tf.close(true)
end
end
def test_s_printf
tf = Tempfile.new("tf")
begin
tf.puts %{
printf("%05d\n", 123)
printf("%-5s|%08x\n", 123, 1)
printf("%3s %-4s%%foo %.0s%5d %#x%c%3.1f %b %x %X %#b %#x %#X\n",
"hi",
123,
"never seen",
456,
0,
?A,
3.0999,
11,
171,
171,
11,
171,
171)
exit}
tf.close
IO.popen("#$interpreter #{tf.path}") do |pipe|
assert_equal("00123\n", pipe.gets)
assert_equal("123 |00000001\n", pipe.gets)
assert_equal(" hi 123 %foo 456 0x0A3.1 1011 ab AB 0b1011 0xab 0XAB\n",
pipe.gets)
end
ensure
tf.close(true)
end
end
def test_s_proc
a = proc { "hello" }
assert_equal("hello", a.call)
a = proc { |s| "there " + s }
assert_equal("there Dave", a.call("Dave"))
end
def test_s_putc
setupTestDir
fname = "_test/_op"
begin
File.open(fname, "wb") do |file|
file.putc "A"
0.upto(255) { |ch| file.putc ch }
end
File.open(fname, "rb") do |file|
assert_equal(?A, file.getc)
0.upto(255) { |ch| assert_equal(ch, file.getc) }
end
ensure
teardownTestDir
end
end
class PrintTest
def to_s
"printtest"
end
end
def test_s_puts
setupTestDir
fname = "_test/_op"
begin
File.open(fname, "w") do |file|
file.puts "line 1", "line 2"
file.puts PrintTest.new
file.puts 4
end
File.open(fname) do |file|
assert_equal("line 1\n", file.gets)
assert_equal("line 2\n", file.gets)
assert_equal("printtest\n", file.gets)
assert_equal("4\n", file.gets)
end
ensure
teardownTestDir
end
end
def test_s_raise
begin
raise
rescue StandardError
assert(true)
rescue Exception
fail("Wrong exception raised")
end
begin
raise "Wombat"
rescue StandardError => detail
assert_equal("Wombat", detail.message)
rescue Exception
fail("Wrong exception raised")
end
assert_raise(NotImplementedError) { raise NotImplementedError }
begin
raise "Wombat"
fail("No exception")
rescue StandardError => detail
assert_equal("Wombat", detail.message)
rescue Exception
fail("Wrong exception")
end
begin
raise NotImplementedError, "Wombat"
fail("No exception")
rescue NotImplementedError => detail
assert_equal("Wombat", detail.message)
rescue Exception
raise
end
bt = %w(one two three)
begin
raise NotImplementedError, "Wombat", bt
fail("No exception")
rescue NotImplementedError => detail
assert_equal("Wombat", detail.message)
assert_equal(bt, detail.backtrace)
rescue Exception
raise
end
if defined? Process.kill
x = 0
trap "SIGINT", proc {|sig| x = 2}
Process.kill "SIGINT", $$
sleep 0.1
assert_equal(2, x)
trap "SIGINT", proc {raise "Interrupt"}
x = nil
begin
Process.kill "SIGINT", $$
sleep 0.1
rescue
x = $!
end
assert_not_nil(x)
assert_not_nil(/Interrupt/ =~ x.to_s)
end
end
def rand_test(limit, result_type, bucket_scale, bucket_max, average)
n = rand(limit)
assert_instance_of(result_type, n)
repeat = 10000
sum = 0
min = 2**30
max = -1
buckets = [0] * bucket_max
sumstep = 0
repeat.times do
last, n = n, rand(limit)
sumstep += (n-last).abs
min = n if min > n
max = n if max < n
sum += n
buckets[bucket_scale.call(n)] += 1
end
# Normalize the limit
limit = limit.to_i
limit = 1 if limit == 0
# Check the mean is about right
assert(min >= 0.0)
assert(max < limit)
avg = Float(sum) / Float(repeat)
if (avg < Float(average)*0.95 or avg > Float(average)*1.05)
$stderr.puts "
I am about to fail a test, but the failure may be purely
a statistical coincidence. Try a difference see and see if
if still happens."
fail("Average out of range (got #{avg}, expected #{average}")
end
# Now do the same for the average difference
avgstep = Float(sumstep) / Float(repeat)
expstep = Float(limit)/3.0
if (avgstep < Float(expstep)*0.95 or avgstep > Float(expstep)*1.05)
$stderr.puts "
I am about to fail a test, but the failure may be purely
a statistical coincidence. Try a difference see and see if
if still happens."
fail("Avg. step out of range (got #{avgstep}, expected #{expstep}")
end
# check that no bucket has les than repeats/100/2 or more than
# repeats/100*1.5
expected = repeat/bucket_max
low = expected/2
high = (expected*3)/2
buckets.each_with_index do |item, index|
assert(item > low && item < high,
"Bucket[#{index}] has #{item} entries. Expected roughly #{expected}")
end
end
# Now the same, but with integers
def test_s_rand
rand_test( 0, Float, proc {|n| (100*n).to_i }, 100, 0.5)
rand_test(100, Fixnum, proc {|n| n }, 100, 49.5)
rand_test( 50, Fixnum, proc {|n| n }, 50, 24.5)
rand_test(500, Fixnum, proc {|n| n/5 }, 100, 249)
end
def test_s_readline1
setupFiles
begin
count = 0
4.times do |count|
line = readline
num = line[0..1].to_i
assert_equal(count, num)
count += 1
end
assert_raise(EOFError) { readline }
ensure
teardownFiles
end
end
def test_s_readline2
setupFiles
begin
count = 0
contents = readline(nil)
contents.split(/\n/).each do |line|
num = line[0..1].to_i
assert_equal(count, num)
count += 1
end
assert_equal(2, count)
contents = readline(nil)
contents.split(/\n/).each do |line|
num = line[0..1].to_i
assert_equal(count, num)
count += 1
end
assert_equal(4, count)
assert_raise(EOFError) { readline }
ensure
teardownFiles
end
end
def test_s_readline3
setupFiles
begin
count = 0
10.times do |count|
thing = readline(' ')
count += 1
end
assert_raise(EOFError) { readline }
ensure
teardownFiles
end
end
def test_s_readlines1
setupFiles
begin
lines = readlines
assert_equal(4, lines.size)
ensure
teardownFiles
end
end
def test_s_readlines2
setupFiles
begin
lines = readlines(nil)
assert_equal(2, lines.size)
ensure
teardownFiles
end
end
def test_s_require
assert_raise(LoadError) { require("gumby") }
File.open("_dummy_req.rb", "w") do |f|
f.print <<-EOM
module Module_Require
VAL = 234
end
EOM
end
assert(!defined? Module_Require)
assert_not_nil(require("./_dummy_req.rb"))
assert_not_nil(defined? Module_Require::VAL)
assert_equal(234, Module_Require::VAL)
assert($".include?("./_dummy_req.rb"))#"
# Prove it isn;t reloaded
File.open("_dummy_req.rb", "w") do |f|
f.print <<-EOM
module Module_Require
VAL1 = 456
end
EOM
end
assert(!require("./_dummy_req.rb"))
assert(!defined? Module_Require::VAL1)
File.delete("./_dummy_req.rb")
end
def make_file(dirname, filename, number, &block)
if FileTest.directory?(dirname)
File.delete(*Dir[File.join(dirname, "**")])
Dir.rmdir(dirname)
end
Dir.mkdir(dirname)
File.open(File.join(dirname, filename), "w") do |f|
f.print <<-EOM
module Module_Require
VAL1 = #{number}
end
EOM
end
block.call
ensure
File.delete(*Dir[File.join(dirname, "**")])
Dir.rmdir(dirname)
end
def test_s_require_changedpath
old = $:.clone
begin
dirname1 = "_dummy_dir1"
dirname2 = "_dummy_dir2"
filename = 'a.rb'
make_file(dirname1, filename, 1) do
make_file(dirname2, filename, 2) do
assert(!$".include?(filename))
$:.unshift(dirname1)
assert(require(filename))
# the next line proves that Ruby excludes files, even though
# we have changed the path, and the originally loaded file no
# longer is first in the path.
$:.unshift(dirname2)
assert(!require(filename))
end
end
ensure
$:.clear; $:.concat(old) # restore path
end
end
def test_s_scan
$_ = "cruel world"
assert_equal(["cruel","world"], scan(/\w+/))
assert_equal(["cru", "el ","wor"], scan(/.../))
assert_equal([["cru"], ["el "],["wor"]], scan(/(...)/))
res=[]
assert_equal($_, scan(/\w+/) { |w| res << w })
assert_equal(["cruel","world"], res)
res=[]
assert_equal($_, scan(/.../) { |w| res << w })
assert_equal(["cru", "el ","wor"], res)
res=[]
assert_equal($_, scan(/(...)/) { |w| res << w })
assert_equal([["cru"], ["el "],["wor"]], res)
assert_equal("cruel world", $_)
end
# Need a better test here
def test_s_select
assert_nil(select(nil, nil, nil, 0))
assert_raise(ArgumentError) { select(nil, nil, nil, -1) }
tf = Tempfile.new("tf")
tf.close
begin
File.open(tf.path) do |file|
res = select([file], [$stdout, $stderr], [], 1)
assert_equal([[file], [$stdout, $stderr], []], res)
end
ensure
tf.close(true)
end
end
def trace_func(*params)
params.slice!(4) # Can't check the binding
@res << params
end
def trace_func_test(file, line)
__LINE__
end
def test_s_set_trace_func
@res = []
line = __LINE__
set_trace_func(proc {|*a| trace_func(*a) })
innerLine = trace_func_test(__FILE__, __LINE__)
set_trace_func(nil)
assert_equal(["line", __FILE__, line+2, :test_s_set_trace_func, TestKernel],
@res.shift)
Version.less_than("1.8.0") do
if defined? Object.allocate
assert_equal(["c-call", __FILE__, line+2, :allocate, String],
@res.shift)
assert_equal(["c-return", __FILE__, line+2, :allocate, String],
@res.shift)
end
end
assert_equal(["call", __FILE__, innerLine-1, :trace_func_test, TestKernel],
@res.shift)
assert_equal(["line", __FILE__, innerLine, :trace_func_test, TestKernel],
@res.shift)
assert_equal("return", @res.shift[0])
end
class SMATest
@@sms = []
def SMATest.singleton_method_added(id)
@@sms << id.id2name
end
def getsms() @@sms end
def SMATest.b() end
end
def SMATest.c() end
def test_s_singleton_method_added
assert_bag_equal(%w(singleton_method_added b c), SMATest.new.getsms)
end
def test_s_sleep
s1 = Time.now
11.times { sleep 0.1 }
s2 = Time.now
assert((s2-s1) >= 1)
assert((s2-s1) <= 3)
duration = sleep(0.1)
assert_instance_of(Fixnum, duration)
assert(duration >= 0 && duration < 2)
# Does Thread.run interrupt a sleep
pThread = Thread.current
Thread.new { sleep 1; pThread.run }
s1 = Time.now
duration = sleep 999
s2 = Time.now
assert(duration >= 0 && duration <= 2, "#{duration} not in 0..2")
assert((s2-s1) >= 0)
assert((s2-s1) <= 3)
end
def test_s_split
assert_equal(nil,$;)
$_ = " a b\t c "
assert_equal(["a", "b", "c"], split)
assert_equal(["a", "b", "c"], split(" "))
$_ = " a | b | c "
assert_equal([" a "," b "," c "], split("|"))
$_ = "aXXbXXcXX"
assert_equal(["a", "b", "c"], split(/X./))
$_ = "abc"
assert_equal(["a", "b", "c"], split(//))
$_ = "a|b|c"
assert_equal(["a|b|c"], split('|',1))
assert_equal(["a", "b|c"], split('|',2))
assert_equal(["a","b","c"], split('|',3))
$_ = "a|b|c|"
assert_equal(["a","b","c",""], split('|',-1))
$_ = "a|b|c||"
assert_equal(["a","b","c","",""], split('|',-1))
$_ = "a||b|c|"
assert_equal(["a","", "b", "c"], split('|'))
assert_equal(["a","", "b", "c",""], split('|',-1))
end
def test_s_sprintf
assert_equal("00123", sprintf("%05d", 123))
assert_equal("123 |00000001", sprintf("%-5s|%08x", 123, 1))
x = sprintf("%3s %-4s%%foo %.0s%5d %#x%c%3.1f %b %x %X %#b %#x %#X",
"hi",
123,
"never seen",
456,
0,
?A,
3.0999,
11,
171,
171,
11,
171,
171)
assert_equal(' hi 123 %foo 456 0x0A3.1 1011 ab AB 0b1011 0xab 0XAB', x)
end
def test_s_srand
# Check that srand with an argument always returns the same value
[ 0, 123, 45678980].each do |seed|
srand(seed)
expected = rand(2**30)
5.times do
assert_equal(seed, srand(seed))
assert_equal(expected, rand(2**30))
end
end
# Now check that the seed is random if called with no argument
keys = {}
values = {}
dups = 0
100.times do
oldSeed = srand
dups += 1 if keys[oldSeed]
keys[oldSeed] = 1
value = rand(2**30)
dups += 1 if values[value]
values[value] = 1
end
# this is a crap shoot, but more than 2 dups is suspicious
assert(dups <= 2, "srand may not be randomized.")
# and check that the seed is randomized for different runs of Ruby
values = {}
5.times do
val = `#$interpreter -e "puts rand(2**30)"`
assert($? == 0)
val = val.to_i
assert_nil(values[val])
values[val] = 1
end
end
def test_s_sub
$_ = "hello"
assert_equal("hello", sub(/x/,'*'))
assert_equal("hello", $_)
$_ = "hello"
assert_equal("h*llo", sub(/[aeiou]/,'*'))
assert_equal("h*llo", $_)
$_ = "hello"
assert_equal("h<e>llo", sub(/([aeiou])/,'<\1>'))
assert_equal("h<e>llo", $_)
$_ = "hello"
assert_equal("104 ello", sub(/./) { |s| s[0].to_s+' '})
assert_equal("104 ello", $_)
$_ = "hello"
assert_equal("HELL-o", sub(/(hell)(.)/) {|s| $1.upcase + '-' + $2})
assert_equal("HELL-o", $_)
$_ = "hello".taint
assert(sub(/./,'X').tainted?)
end
def test_s_sub!
$_ = "hello"
assert_equal(nil, sub!(/x/,'*'))
assert_equal("hello", $_)
$_ = "hello"
assert_equal("h*llo", sub!(/[aeiou]/,'*'))
assert_equal("h*llo", $_)
$_ = "hello"
assert_equal("h<e>llo", sub!(/([aeiou])/,'<\1>'))
assert_equal("h<e>llo", $_)
$_ = "hello"
assert_equal("104 ello", sub!(/./) { |s| s[0].to_s+' '})
assert_equal("104 ello", $_)
$_ = "hello"
assert_equal("HELL-o", sub!(/(hell)(.)/) {|s| $1.upcase + '-' + $2})
assert_equal("HELL-o", $_)
$_ = "hello".taint
assert(sub!(/./,'X').tainted?)
end
def test_s_syscall
skipping("platform specific")
end
def test_s_system
open("xyzzy.dat", "w") { |f| f.puts "stuff" }
tf = Tempfile.new("tf")
begin
# all in one string - wildcards get expanded
tf.puts 'system("echo xy*y.dat")'
tf.close
IO.popen("#$interpreter #{tf.path}") do |p|
assert_equal("xyzzy.dat\n", p.gets)
end
# with two parameters, the '*' doesn't get expanded
tf.open
tf.puts 'system("echo", "xy*y.dat")'
tf.close
IO.popen("#$interpreter #{tf.path}") do |p|
assert_equal("xy*y.dat\n", p.gets)
end
ensure
tf.close(true)
File.unlink "xyzzy.dat" if p
end
Version.less_than("1.9.0") do
system("____this_is_a_bad command____")
assert($? != 0)
end
Version.greater_or_equal("1.9.0") do
assert_raise(Errno::ENOENT) {
system("____this_is_a_bad command____")
}
end
end
# def test_s_test
# # in TestKernelTest
# end
def test_s_throw
# tested by test_s_catch
end
def test_s_trace_var
val = nil
p = proc { |val| }
trace_var(:$_, p)
$_ = "123"
assert_equal($_, val)
$_ = nil
assert_equal($_, val)
untrace_var("$_")
$_ = "123"
assert_equal(nil, val)
assert_equal("123", $_)
end
def test_s_trap
res = nil
lastProc = proc { res = 1 }
# 1. Check that an exception is thrown if we wait for a child and
# there is no child.
# "IGNORE" discards child termination status (but apparently not
# under Cygwin/W2k
Unix.only do
trap "CHLD", "IGNORE"
pid = fork
exit unless pid
sleep 1 # ensure child has exited (ish)
assert_raise(Errno::ECHILD) { Process.wait }
end
# 2. check that we run a proc as a handler when a child
# terminates
MsWin32.dont do
trap("SIGCHLD", lastProc)
fork { ; }
Process.wait
assert_equal(1, res)
end
# 3. Reset the signal handler (checking it returns the previous
# value) and ensure that the proc doesn't get called
MsWin32.dont do
assert_equal(lastProc, trap("SIGCHLD", "DEFAULT"))
res = nil
fork { ; }
Process.wait
assert_nil(res)
end
# 4. test EXIT handling
IO.popen(%{#$interpreter -e 'trap "EXIT", "exit! 123";exit 99'}).close
assert_equal(123<<8, $?)
end
def test_s_untrace_var1
trace_var(:$_, "puts 99")
p = proc { |val| }
trace_var("$_", p)
assert_bag_equal(["puts 99", p], untrace_var(:$_))
assert_equal([], untrace_var(:$_))
end
def test_s_untrace_var2
trace_var(:$_, "puts 99")
p = proc { |val| }
trace_var("$_", p)
assert_bag_equal(["puts 99", p], untrace_var(:$_))
end
def test_gvar_alias
$foo = 3
eval "alias $bar $foo"
assert_equal(3, $bar)
$bar = 4
assert_equal(4, $foo)
end
def test_svar_alias
eval "alias $foo $_"
$_ = 1
assert_equal(1, $foo)
$foo = 2
assert_equal(2, $_)
end
end
|