1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
|
package assert
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"os"
"reflect"
"regexp"
"runtime"
"strings"
"testing"
"time"
)
var (
i interface{}
zeros = []interface{}{
false,
byte(0),
complex64(0),
complex128(0),
float32(0),
float64(0),
int(0),
int8(0),
int16(0),
int32(0),
int64(0),
rune(0),
uint(0),
uint8(0),
uint16(0),
uint32(0),
uint64(0),
uintptr(0),
"",
[0]interface{}{},
[]interface{}(nil),
struct{ x int }{},
(*interface{})(nil),
(func())(nil),
nil,
interface{}(nil),
map[interface{}]interface{}(nil),
(chan interface{})(nil),
(<-chan interface{})(nil),
(chan<- interface{})(nil),
}
nonZeros = []interface{}{
true,
byte(1),
complex64(1),
complex128(1),
float32(1),
float64(1),
int(1),
int8(1),
int16(1),
int32(1),
int64(1),
rune(1),
uint(1),
uint8(1),
uint16(1),
uint32(1),
uint64(1),
uintptr(1),
"s",
[1]interface{}{1},
[]interface{}{},
struct{ x int }{1},
(&i),
(func() {}),
interface{}(1),
map[interface{}]interface{}{},
(make(chan interface{})),
(<-chan interface{})(make(chan interface{})),
(chan<- interface{})(make(chan interface{})),
}
)
// AssertionTesterInterface defines an interface to be used for testing assertion methods
type AssertionTesterInterface interface {
TestMethod()
}
// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface
type AssertionTesterConformingObject struct {
}
func (a *AssertionTesterConformingObject) TestMethod() {
}
// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface
type AssertionTesterNonConformingObject struct {
}
func TestObjectsAreEqual(t *testing.T) {
cases := []struct {
expected interface{}
actual interface{}
result bool
}{
// cases that are expected to be equal
{"Hello World", "Hello World", true},
{123, 123, true},
{123.5, 123.5, true},
{[]byte("Hello World"), []byte("Hello World"), true},
{nil, nil, true},
// cases that are expected not to be equal
{map[int]int{5: 10}, map[int]int{10: 20}, false},
{'x', "x", false},
{"x", 'x', false},
{0, 0.1, false},
{0.1, 0, false},
{time.Now, time.Now, false},
{func() {}, func() {}, false},
{uint32(10), int32(10), false},
}
for _, c := range cases {
t.Run(fmt.Sprintf("ObjectsAreEqual(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
res := ObjectsAreEqual(c.expected, c.actual)
if res != c.result {
t.Errorf("ObjectsAreEqual(%#v, %#v) should return %#v", c.expected, c.actual, c.result)
}
})
}
// Cases where type differ but values are equal
if !ObjectsAreEqualValues(uint32(10), int32(10)) {
t.Error("ObjectsAreEqualValues should return true")
}
if ObjectsAreEqualValues(0, nil) {
t.Fail()
}
if ObjectsAreEqualValues(nil, 0) {
t.Fail()
}
}
func TestImplements(t *testing.T) {
mockT := new(testing.T)
if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) {
t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface")
}
if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) {
t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface")
}
if Implements(mockT, (*AssertionTesterInterface)(nil), nil) {
t.Error("Implements method should return false: nil does not implement AssertionTesterInterface")
}
}
func TestIsType(t *testing.T) {
mockT := new(testing.T)
if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject")
}
if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) {
t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject")
}
}
func TestEqual(t *testing.T) {
type myType string
mockT := new(testing.T)
var m map[string]interface{}
cases := []struct {
expected interface{}
actual interface{}
result bool
remark string
}{
{"Hello World", "Hello World", true, ""},
{123, 123, true, ""},
{123.5, 123.5, true, ""},
{[]byte("Hello World"), []byte("Hello World"), true, ""},
{nil, nil, true, ""},
{int32(123), int32(123), true, ""},
{uint64(123), uint64(123), true, ""},
{myType("1"), myType("1"), true, ""},
{&struct{}{}, &struct{}{}, true, "pointer equality is based on equality of underlying value"},
// Not expected to be equal
{m["bar"], "something", false, ""},
{myType("1"), myType("2"), false, ""},
// A case that might be confusing, especially with numeric literals
{10, uint(10), false, ""},
}
for _, c := range cases {
t.Run(fmt.Sprintf("Equal(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
res := Equal(mockT, c.expected, c.actual)
if res != c.result {
t.Errorf("Equal(%#v, %#v) should return %#v: %s", c.expected, c.actual, c.result, c.remark)
}
})
}
}
func ptr(i int) *int {
return &i
}
func TestSame(t *testing.T) {
mockT := new(testing.T)
if Same(mockT, ptr(1), ptr(1)) {
t.Error("Same should return false")
}
if Same(mockT, 1, 1) {
t.Error("Same should return false")
}
p := ptr(2)
if Same(mockT, p, *p) {
t.Error("Same should return false")
}
if !Same(mockT, p, p) {
t.Error("Same should return true")
}
}
func TestNotSame(t *testing.T) {
mockT := new(testing.T)
if !NotSame(mockT, ptr(1), ptr(1)) {
t.Error("NotSame should return true; different pointers")
}
if !NotSame(mockT, 1, 1) {
t.Error("NotSame should return true; constant inputs")
}
p := ptr(2)
if !NotSame(mockT, p, *p) {
t.Error("NotSame should return true; mixed-type inputs")
}
if NotSame(mockT, p, p) {
t.Error("NotSame should return false")
}
}
func Test_samePointers(t *testing.T) {
p := ptr(2)
type args struct {
first interface{}
second interface{}
}
tests := []struct {
name string
args args
assertion BoolAssertionFunc
}{
{
name: "1 != 2",
args: args{first: 1, second: 2},
assertion: False,
},
{
name: "1 != 1 (not same ptr)",
args: args{first: 1, second: 1},
assertion: False,
},
{
name: "ptr(1) == ptr(1)",
args: args{first: p, second: p},
assertion: True,
},
{
name: "int(1) != float32(1)",
args: args{first: int(1), second: float32(1)},
assertion: False,
},
{
name: "array != slice",
args: args{first: [2]int{1, 2}, second: []int{1, 2}},
assertion: False,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.assertion(t, samePointers(tt.args.first, tt.args.second))
})
}
}
// bufferT implements TestingT. Its implementation of Errorf writes the output that would be produced by
// testing.T.Errorf to an internal bytes.Buffer.
type bufferT struct {
buf bytes.Buffer
}
func (t *bufferT) Errorf(format string, args ...interface{}) {
// implementation of decorate is copied from testing.T
decorate := func(s string) string {
_, file, line, ok := runtime.Caller(3) // decorate + log + public function.
if ok {
// Truncate file name at last file name separator.
if index := strings.LastIndex(file, "/"); index >= 0 {
file = file[index+1:]
} else if index = strings.LastIndex(file, "\\"); index >= 0 {
file = file[index+1:]
}
} else {
file = "???"
line = 1
}
buf := new(bytes.Buffer)
// Every line is indented at least one tab.
buf.WriteByte('\t')
fmt.Fprintf(buf, "%s:%d: ", file, line)
lines := strings.Split(s, "\n")
if l := len(lines); l > 1 && lines[l-1] == "" {
lines = lines[:l-1]
}
for i, line := range lines {
if i > 0 {
// Second and subsequent lines are indented an extra tab.
buf.WriteString("\n\t\t")
}
buf.WriteString(line)
}
buf.WriteByte('\n')
return buf.String()
}
t.buf.WriteString(decorate(fmt.Sprintf(format, args...)))
}
func TestStringEqual(t *testing.T) {
for i, currCase := range []struct {
equalWant string
equalGot string
msgAndArgs []interface{}
want string
}{
{equalWant: "hi, \nmy name is", equalGot: "what,\nmy name is", want: "\tassertions.go:\\d+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"hi, \\\\nmy name is\"\n\\s+actual\\s+: \"what,\\\\nmy name is\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1,2 \\+1,2 @@\n\\s+-hi, \n\\s+\\+what,\n\\s+my name is"},
} {
mockT := &bufferT{}
Equal(mockT, currCase.equalWant, currCase.equalGot, currCase.msgAndArgs...)
Regexp(t, regexp.MustCompile(currCase.want), mockT.buf.String(), "Case %d", i)
}
}
func TestEqualFormatting(t *testing.T) {
for i, currCase := range []struct {
equalWant string
equalGot string
msgAndArgs []interface{}
want string
}{
{equalWant: "want", equalGot: "got", want: "\tassertions.go:\\d+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"want\"\n\\s+actual\\s+: \"got\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1 \\+1 @@\n\\s+-want\n\\s+\\+got\n"},
{equalWant: "want", equalGot: "got", msgAndArgs: []interface{}{"hello, %v!", "world"}, want: "\tassertions.go:[0-9]+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"want\"\n\\s+actual\\s+: \"got\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1 \\+1 @@\n\\s+-want\n\\s+\\+got\n\\s+Messages:\\s+hello, world!\n"},
{equalWant: "want", equalGot: "got", msgAndArgs: []interface{}{123}, want: "\tassertions.go:[0-9]+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"want\"\n\\s+actual\\s+: \"got\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1 \\+1 @@\n\\s+-want\n\\s+\\+got\n\\s+Messages:\\s+123\n"},
{equalWant: "want", equalGot: "got", msgAndArgs: []interface{}{struct{ a string }{"hello"}}, want: "\tassertions.go:[0-9]+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"want\"\n\\s+actual\\s+: \"got\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1 \\+1 @@\n\\s+-want\n\\s+\\+got\n\\s+Messages:\\s+{a:hello}\n"},
} {
mockT := &bufferT{}
Equal(mockT, currCase.equalWant, currCase.equalGot, currCase.msgAndArgs...)
Regexp(t, regexp.MustCompile(currCase.want), mockT.buf.String(), "Case %d", i)
}
}
func TestFormatUnequalValues(t *testing.T) {
expected, actual := formatUnequalValues("foo", "bar")
Equal(t, `"foo"`, expected, "value should not include type")
Equal(t, `"bar"`, actual, "value should not include type")
expected, actual = formatUnequalValues(123, 123)
Equal(t, `123`, expected, "value should not include type")
Equal(t, `123`, actual, "value should not include type")
expected, actual = formatUnequalValues(int64(123), int32(123))
Equal(t, `int64(123)`, expected, "value should include type")
Equal(t, `int32(123)`, actual, "value should include type")
expected, actual = formatUnequalValues(int64(123), nil)
Equal(t, `int64(123)`, expected, "value should include type")
Equal(t, `<nil>(<nil>)`, actual, "value should include type")
type testStructType struct {
Val string
}
expected, actual = formatUnequalValues(&testStructType{Val: "test"}, &testStructType{Val: "test"})
Equal(t, `&assert.testStructType{Val:"test"}`, expected, "value should not include type annotation")
Equal(t, `&assert.testStructType{Val:"test"}`, actual, "value should not include type annotation")
}
func TestNotNil(t *testing.T) {
mockT := new(testing.T)
if !NotNil(mockT, new(AssertionTesterConformingObject)) {
t.Error("NotNil should return true: object is not nil")
}
if NotNil(mockT, nil) {
t.Error("NotNil should return false: object is nil")
}
if NotNil(mockT, (*struct{})(nil)) {
t.Error("NotNil should return false: object is (*struct{})(nil)")
}
}
func TestNil(t *testing.T) {
mockT := new(testing.T)
if !Nil(mockT, nil) {
t.Error("Nil should return true: object is nil")
}
if !Nil(mockT, (*struct{})(nil)) {
t.Error("Nil should return true: object is (*struct{})(nil)")
}
if Nil(mockT, new(AssertionTesterConformingObject)) {
t.Error("Nil should return false: object is not nil")
}
}
func TestTrue(t *testing.T) {
mockT := new(testing.T)
if !True(mockT, true) {
t.Error("True should return true")
}
if True(mockT, false) {
t.Error("True should return false")
}
}
func TestFalse(t *testing.T) {
mockT := new(testing.T)
if !False(mockT, false) {
t.Error("False should return true")
}
if False(mockT, true) {
t.Error("False should return false")
}
}
func TestExactly(t *testing.T) {
mockT := new(testing.T)
a := float32(1)
b := float64(1)
c := float32(1)
d := float32(2)
cases := []struct {
expected interface{}
actual interface{}
result bool
}{
{a, b, false},
{a, d, false},
{a, c, true},
{nil, a, false},
{a, nil, false},
}
for _, c := range cases {
t.Run(fmt.Sprintf("Exactly(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
res := Exactly(mockT, c.expected, c.actual)
if res != c.result {
t.Errorf("Exactly(%#v, %#v) should return %#v", c.expected, c.actual, c.result)
}
})
}
}
func TestNotEqual(t *testing.T) {
mockT := new(testing.T)
cases := []struct {
expected interface{}
actual interface{}
result bool
}{
// cases that are expected not to match
{"Hello World", "Hello World!", true},
{123, 1234, true},
{123.5, 123.55, true},
{[]byte("Hello World"), []byte("Hello World!"), true},
{nil, new(AssertionTesterConformingObject), true},
// cases that are expected to match
{nil, nil, false},
{"Hello World", "Hello World", false},
{123, 123, false},
{123.5, 123.5, false},
{[]byte("Hello World"), []byte("Hello World"), false},
{new(AssertionTesterConformingObject), new(AssertionTesterConformingObject), false},
{&struct{}{}, &struct{}{}, false},
{func() int { return 23 }, func() int { return 24 }, false},
// A case that might be confusing, especially with numeric literals
{int(10), uint(10), true},
}
for _, c := range cases {
t.Run(fmt.Sprintf("NotEqual(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
res := NotEqual(mockT, c.expected, c.actual)
if res != c.result {
t.Errorf("NotEqual(%#v, %#v) should return %#v", c.expected, c.actual, c.result)
}
})
}
}
func TestNotEqualValues(t *testing.T) {
mockT := new(testing.T)
cases := []struct {
expected interface{}
actual interface{}
result bool
}{
// cases that are expected not to match
{"Hello World", "Hello World!", true},
{123, 1234, true},
{123.5, 123.55, true},
{[]byte("Hello World"), []byte("Hello World!"), true},
{nil, new(AssertionTesterConformingObject), true},
// cases that are expected to match
{nil, nil, false},
{"Hello World", "Hello World", false},
{123, 123, false},
{123.5, 123.5, false},
{[]byte("Hello World"), []byte("Hello World"), false},
{new(AssertionTesterConformingObject), new(AssertionTesterConformingObject), false},
{&struct{}{}, &struct{}{}, false},
// Different behaviour from NotEqual()
{func() int { return 23 }, func() int { return 24 }, true},
{int(10), int(11), true},
{int(10), uint(10), false},
{struct{}{}, struct{}{}, false},
}
for _, c := range cases {
t.Run(fmt.Sprintf("NotEqualValues(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
res := NotEqualValues(mockT, c.expected, c.actual)
if res != c.result {
t.Errorf("NotEqualValues(%#v, %#v) should return %#v", c.expected, c.actual, c.result)
}
})
}
}
func TestContainsNotContains(t *testing.T) {
type A struct {
Name, Value string
}
list := []string{"Foo", "Bar"}
complexList := []*A{
{"b", "c"},
{"d", "e"},
{"g", "h"},
{"j", "k"},
}
simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
var zeroMap map[interface{}]interface{}
cases := []struct {
expected interface{}
actual interface{}
result bool
}{
{"Hello World", "Hello", true},
{"Hello World", "Salut", false},
{list, "Bar", true},
{list, "Salut", false},
{complexList, &A{"g", "h"}, true},
{complexList, &A{"g", "e"}, false},
{simpleMap, "Foo", true},
{simpleMap, "Bar", false},
{zeroMap, "Bar", false},
}
for _, c := range cases {
t.Run(fmt.Sprintf("Contains(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
mockT := new(testing.T)
res := Contains(mockT, c.expected, c.actual)
if res != c.result {
if res {
t.Errorf("Contains(%#v, %#v) should return true:\n\t%#v contains %#v", c.expected, c.actual, c.expected, c.actual)
} else {
t.Errorf("Contains(%#v, %#v) should return false:\n\t%#v does not contain %#v", c.expected, c.actual, c.expected, c.actual)
}
}
})
}
for _, c := range cases {
t.Run(fmt.Sprintf("NotContains(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
mockT := new(testing.T)
res := NotContains(mockT, c.expected, c.actual)
// NotContains should be inverse of Contains. If it's not, something is wrong
if res == Contains(mockT, c.expected, c.actual) {
if res {
t.Errorf("NotContains(%#v, %#v) should return true:\n\t%#v does not contains %#v", c.expected, c.actual, c.expected, c.actual)
} else {
t.Errorf("NotContains(%#v, %#v) should return false:\n\t%#v contains %#v", c.expected, c.actual, c.expected, c.actual)
}
}
})
}
}
func TestContainsFailMessage(t *testing.T) {
mockT := new(mockTestingT)
Contains(mockT, "Hello World", errors.New("Hello"))
expectedFail := "\"Hello World\" does not contain &errors.errorString{s:\"Hello\"}"
actualFail := mockT.errorString()
if !strings.Contains(actualFail, expectedFail) {
t.Errorf("Contains failure should include %q but was %q", expectedFail, actualFail)
}
}
func TestContainsNotContainsOnNilValue(t *testing.T) {
mockT := new(mockTestingT)
Contains(mockT, nil, "key")
expectedFail := "<nil> could not be applied builtin len()"
actualFail := mockT.errorString()
if !strings.Contains(actualFail, expectedFail) {
t.Errorf("Contains failure should include %q but was %q", expectedFail, actualFail)
}
NotContains(mockT, nil, "key")
if !strings.Contains(actualFail, expectedFail) {
t.Errorf("Contains failure should include %q but was %q", expectedFail, actualFail)
}
}
func TestSubsetNotSubset(t *testing.T) {
// MTestCase adds a custom message to the case
cases := []struct {
expected interface{}
actual interface{}
result bool
message string
}{
// cases that are expected to contain
{[]int{1, 2, 3}, nil, true, "given subset is nil"},
{[]int{1, 2, 3}, []int{}, true, "any set contains the nil set"},
{[]int{1, 2, 3}, []int{1, 2}, true, "[1, 2, 3] contains [1, 2]"},
{[]int{1, 2, 3}, []int{1, 2, 3}, true, "[1, 2, 3] contains [1, 2, 3"},
{[]string{"hello", "world"}, []string{"hello"}, true, "[\"hello\", \"world\"] contains [\"hello\"]"},
// cases that are expected not to contain
{[]string{"hello", "world"}, []string{"hello", "testify"}, false, "[\"hello\", \"world\"] does not contain [\"hello\", \"testify\"]"},
{[]int{1, 2, 3}, []int{4, 5}, false, "[1, 2, 3] does not contain [4, 5"},
{[]int{1, 2, 3}, []int{1, 5}, false, "[1, 2, 3] does not contain [1, 5]"},
}
for _, c := range cases {
t.Run("SubSet: "+c.message, func(t *testing.T) {
mockT := new(testing.T)
res := Subset(mockT, c.expected, c.actual)
if res != c.result {
if res {
t.Errorf("Subset should return true: %s", c.message)
} else {
t.Errorf("Subset should return false: %s", c.message)
}
}
})
}
for _, c := range cases {
t.Run("NotSubSet: "+c.message, func(t *testing.T) {
mockT := new(testing.T)
res := NotSubset(mockT, c.expected, c.actual)
// NotSubset should match the inverse of Subset. If it doesn't, something is wrong
if res == Subset(mockT, c.expected, c.actual) {
if res {
t.Errorf("NotSubset should return true: %s", c.message)
} else {
t.Errorf("NotSubset should return false: %s", c.message)
}
}
})
}
}
func TestNotSubsetNil(t *testing.T) {
mockT := new(testing.T)
NotSubset(mockT, []string{"foo"}, nil)
if !mockT.Failed() {
t.Error("NotSubset on nil set should have failed the test")
}
}
func Test_containsElement(t *testing.T) {
list1 := []string{"Foo", "Bar"}
list2 := []int{1, 2}
simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
ok, found := containsElement("Hello World", "World")
True(t, ok)
True(t, found)
ok, found = containsElement(list1, "Foo")
True(t, ok)
True(t, found)
ok, found = containsElement(list1, "Bar")
True(t, ok)
True(t, found)
ok, found = containsElement(list2, 1)
True(t, ok)
True(t, found)
ok, found = containsElement(list2, 2)
True(t, ok)
True(t, found)
ok, found = containsElement(list1, "Foo!")
True(t, ok)
False(t, found)
ok, found = containsElement(list2, 3)
True(t, ok)
False(t, found)
ok, found = containsElement(list2, "1")
True(t, ok)
False(t, found)
ok, found = containsElement(simpleMap, "Foo")
True(t, ok)
True(t, found)
ok, found = containsElement(simpleMap, "Bar")
True(t, ok)
False(t, found)
ok, found = containsElement(1433, "1")
False(t, ok)
False(t, found)
}
func TestElementsMatch(t *testing.T) {
mockT := new(testing.T)
cases := []struct {
expected interface{}
actual interface{}
result bool
}{
// matching
{nil, nil, true},
{nil, nil, true},
{[]int{}, []int{}, true},
{[]int{1}, []int{1}, true},
{[]int{1, 1}, []int{1, 1}, true},
{[]int{1, 2}, []int{1, 2}, true},
{[]int{1, 2}, []int{2, 1}, true},
{[2]int{1, 2}, [2]int{2, 1}, true},
{[]string{"hello", "world"}, []string{"world", "hello"}, true},
{[]string{"hello", "hello"}, []string{"hello", "hello"}, true},
{[]string{"hello", "hello", "world"}, []string{"hello", "world", "hello"}, true},
{[3]string{"hello", "hello", "world"}, [3]string{"hello", "world", "hello"}, true},
{[]int{}, nil, true},
// not matching
{[]int{1}, []int{1, 1}, false},
{[]int{1, 2}, []int{2, 2}, false},
{[]string{"hello", "hello"}, []string{"hello"}, false},
}
for _, c := range cases {
t.Run(fmt.Sprintf("ElementsMatch(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
res := ElementsMatch(mockT, c.actual, c.expected)
if res != c.result {
t.Errorf("ElementsMatch(%#v, %#v) should return %v", c.actual, c.expected, c.result)
}
})
}
}
func TestDiffLists(t *testing.T) {
tests := []struct {
name string
listA interface{}
listB interface{}
extraA []interface{}
extraB []interface{}
}{
{
name: "equal empty",
listA: []string{},
listB: []string{},
extraA: nil,
extraB: nil,
},
{
name: "equal same order",
listA: []string{"hello", "world"},
listB: []string{"hello", "world"},
extraA: nil,
extraB: nil,
},
{
name: "equal different order",
listA: []string{"hello", "world"},
listB: []string{"world", "hello"},
extraA: nil,
extraB: nil,
},
{
name: "extra A",
listA: []string{"hello", "hello", "world"},
listB: []string{"hello", "world"},
extraA: []interface{}{"hello"},
extraB: nil,
},
{
name: "extra A twice",
listA: []string{"hello", "hello", "hello", "world"},
listB: []string{"hello", "world"},
extraA: []interface{}{"hello", "hello"},
extraB: nil,
},
{
name: "extra B",
listA: []string{"hello", "world"},
listB: []string{"hello", "hello", "world"},
extraA: nil,
extraB: []interface{}{"hello"},
},
{
name: "extra B twice",
listA: []string{"hello", "world"},
listB: []string{"hello", "hello", "world", "hello"},
extraA: nil,
extraB: []interface{}{"hello", "hello"},
},
{
name: "integers 1",
listA: []int{1, 2, 3, 4, 5},
listB: []int{5, 4, 3, 2, 1},
extraA: nil,
extraB: nil,
},
{
name: "integers 2",
listA: []int{1, 2, 1, 2, 1},
listB: []int{2, 1, 2, 1, 2},
extraA: []interface{}{1},
extraB: []interface{}{2},
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
actualExtraA, actualExtraB := diffLists(test.listA, test.listB)
Equal(t, test.extraA, actualExtraA, "extra A does not match for listA=%v listB=%v",
test.listA, test.listB)
Equal(t, test.extraB, actualExtraB, "extra B does not match for listA=%v listB=%v",
test.listA, test.listB)
})
}
}
func TestCondition(t *testing.T) {
mockT := new(testing.T)
if !Condition(mockT, func() bool { return true }, "Truth") {
t.Error("Condition should return true")
}
if Condition(mockT, func() bool { return false }, "Lie") {
t.Error("Condition should return false")
}
}
func TestDidPanic(t *testing.T) {
if funcDidPanic, _, _ := didPanic(func() {
panic("Panic!")
}); !funcDidPanic {
t.Error("didPanic should return true")
}
if funcDidPanic, _, _ := didPanic(func() {
}); funcDidPanic {
t.Error("didPanic should return false")
}
}
func TestPanics(t *testing.T) {
mockT := new(testing.T)
if !Panics(mockT, func() {
panic("Panic!")
}) {
t.Error("Panics should return true")
}
if Panics(mockT, func() {
}) {
t.Error("Panics should return false")
}
}
func TestPanicsWithValue(t *testing.T) {
mockT := new(testing.T)
if !PanicsWithValue(mockT, "Panic!", func() {
panic("Panic!")
}) {
t.Error("PanicsWithValue should return true")
}
if PanicsWithValue(mockT, "Panic!", func() {
}) {
t.Error("PanicsWithValue should return false")
}
if PanicsWithValue(mockT, "at the disco", func() {
panic("Panic!")
}) {
t.Error("PanicsWithValue should return false")
}
}
func TestPanicsWithError(t *testing.T) {
mockT := new(testing.T)
if !PanicsWithError(mockT, "panic", func() {
panic(errors.New("panic"))
}) {
t.Error("PanicsWithError should return true")
}
if PanicsWithError(mockT, "Panic!", func() {
}) {
t.Error("PanicsWithError should return false")
}
if PanicsWithError(mockT, "at the disco", func() {
panic(errors.New("panic"))
}) {
t.Error("PanicsWithError should return false")
}
if PanicsWithError(mockT, "Panic!", func() {
panic("panic")
}) {
t.Error("PanicsWithError should return false")
}
}
func TestNotPanics(t *testing.T) {
mockT := new(testing.T)
if !NotPanics(mockT, func() {
}) {
t.Error("NotPanics should return true")
}
if NotPanics(mockT, func() {
panic("Panic!")
}) {
t.Error("NotPanics should return false")
}
}
func TestNoError(t *testing.T) {
mockT := new(testing.T)
// start with a nil error
var err error
True(t, NoError(mockT, err), "NoError should return True for nil arg")
// now set an error
err = errors.New("some error")
False(t, NoError(mockT, err), "NoError with error should return False")
// returning an empty error interface
err = func() error {
var err *customError
return err
}()
if err == nil { // err is not nil here!
t.Errorf("Error should be nil due to empty interface: %s", err)
}
False(t, NoError(mockT, err), "NoError should fail with empty error interface")
}
type customError struct{}
func (*customError) Error() string { return "fail" }
func TestError(t *testing.T) {
mockT := new(testing.T)
// start with a nil error
var err error
False(t, Error(mockT, err), "Error should return False for nil arg")
// now set an error
err = errors.New("some error")
True(t, Error(mockT, err), "Error with error should return True")
// go vet check
True(t, Errorf(mockT, err, "example with %s", "formatted message"), "Errorf with error should rturn True")
// returning an empty error interface
err = func() error {
var err *customError
return err
}()
if err == nil { // err is not nil here!
t.Errorf("Error should be nil due to empty interface: %s", err)
}
True(t, Error(mockT, err), "Error should pass with empty error interface")
}
func TestEqualError(t *testing.T) {
mockT := new(testing.T)
// start with a nil error
var err error
False(t, EqualError(mockT, err, ""),
"EqualError should return false for nil arg")
// now set an error
err = errors.New("some error")
False(t, EqualError(mockT, err, "Not some error"),
"EqualError should return false for different error string")
True(t, EqualError(mockT, err, "some error"),
"EqualError should return true")
}
func TestErrorContains(t *testing.T) {
mockT := new(testing.T)
// start with a nil error
var err error
False(t, ErrorContains(mockT, err, ""),
"ErrorContains should return false for nil arg")
// now set an error
err = errors.New("some error: another error")
False(t, ErrorContains(mockT, err, "bad error"),
"ErrorContains should return false for different error string")
True(t, ErrorContains(mockT, err, "some error"),
"ErrorContains should return true")
True(t, ErrorContains(mockT, err, "another error"),
"ErrorContains should return true")
}
func Test_isEmpty(t *testing.T) {
chWithValue := make(chan struct{}, 1)
chWithValue <- struct{}{}
True(t, isEmpty(""))
True(t, isEmpty(nil))
True(t, isEmpty([]string{}))
True(t, isEmpty(0))
True(t, isEmpty(int32(0)))
True(t, isEmpty(int64(0)))
True(t, isEmpty(false))
True(t, isEmpty(map[string]string{}))
True(t, isEmpty(new(time.Time)))
True(t, isEmpty(time.Time{}))
True(t, isEmpty(make(chan struct{})))
False(t, isEmpty("something"))
False(t, isEmpty(errors.New("something")))
False(t, isEmpty([]string{"something"}))
False(t, isEmpty(1))
False(t, isEmpty(true))
False(t, isEmpty(map[string]string{"Hello": "World"}))
False(t, isEmpty(chWithValue))
}
func TestEmpty(t *testing.T) {
mockT := new(testing.T)
chWithValue := make(chan struct{}, 1)
chWithValue <- struct{}{}
var tiP *time.Time
var tiNP time.Time
var s *string
var f *os.File
sP := &s
x := 1
xP := &x
type TString string
type TStruct struct {
x int
}
True(t, Empty(mockT, ""), "Empty string is empty")
True(t, Empty(mockT, nil), "Nil is empty")
True(t, Empty(mockT, []string{}), "Empty string array is empty")
True(t, Empty(mockT, 0), "Zero int value is empty")
True(t, Empty(mockT, false), "False value is empty")
True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty")
True(t, Empty(mockT, s), "Nil string pointer is empty")
True(t, Empty(mockT, f), "Nil os.File pointer is empty")
True(t, Empty(mockT, tiP), "Nil time.Time pointer is empty")
True(t, Empty(mockT, tiNP), "time.Time is empty")
True(t, Empty(mockT, TStruct{}), "struct with zero values is empty")
True(t, Empty(mockT, TString("")), "empty aliased string is empty")
True(t, Empty(mockT, sP), "ptr to nil value is empty")
False(t, Empty(mockT, "something"), "Non Empty string is not empty")
False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty")
False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty")
False(t, Empty(mockT, 1), "Non-zero int value is not empty")
False(t, Empty(mockT, true), "True value is not empty")
False(t, Empty(mockT, chWithValue), "Channel with values is not empty")
False(t, Empty(mockT, TStruct{x: 1}), "struct with initialized values is empty")
False(t, Empty(mockT, TString("abc")), "non-empty aliased string is empty")
False(t, Empty(mockT, xP), "ptr to non-nil value is not empty")
}
func TestNotEmpty(t *testing.T) {
mockT := new(testing.T)
chWithValue := make(chan struct{}, 1)
chWithValue <- struct{}{}
False(t, NotEmpty(mockT, ""), "Empty string is empty")
False(t, NotEmpty(mockT, nil), "Nil is empty")
False(t, NotEmpty(mockT, []string{}), "Empty string array is empty")
False(t, NotEmpty(mockT, 0), "Zero int value is empty")
False(t, NotEmpty(mockT, false), "False value is empty")
False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty")
True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty")
True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty")
True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty")
True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty")
True(t, NotEmpty(mockT, true), "True value is not empty")
True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty")
}
func Test_getLen(t *testing.T) {
falseCases := []interface{}{
nil,
0,
true,
false,
'A',
struct{}{},
}
for _, v := range falseCases {
ok, l := getLen(v)
False(t, ok, "Expected getLen fail to get length of %#v", v)
Equal(t, 0, l, "getLen should return 0 for %#v", v)
}
ch := make(chan int, 5)
ch <- 1
ch <- 2
ch <- 3
trueCases := []struct {
v interface{}
l int
}{
{[]int{1, 2, 3}, 3},
{[...]int{1, 2, 3}, 3},
{"ABC", 3},
{map[int]int{1: 2, 2: 4, 3: 6}, 3},
{ch, 3},
{[]int{}, 0},
{map[int]int{}, 0},
{make(chan int), 0},
{[]int(nil), 0},
{map[int]int(nil), 0},
{(chan int)(nil), 0},
}
for _, c := range trueCases {
ok, l := getLen(c.v)
True(t, ok, "Expected getLen success to get length of %#v", c.v)
Equal(t, c.l, l)
}
}
func TestLen(t *testing.T) {
mockT := new(testing.T)
False(t, Len(mockT, nil, 0), "nil does not have length")
False(t, Len(mockT, 0, 0), "int does not have length")
False(t, Len(mockT, true, 0), "true does not have length")
False(t, Len(mockT, false, 0), "false does not have length")
False(t, Len(mockT, 'A', 0), "Rune does not have length")
False(t, Len(mockT, struct{}{}, 0), "Struct does not have length")
ch := make(chan int, 5)
ch <- 1
ch <- 2
ch <- 3
cases := []struct {
v interface{}
l int
}{
{[]int{1, 2, 3}, 3},
{[...]int{1, 2, 3}, 3},
{"ABC", 3},
{map[int]int{1: 2, 2: 4, 3: 6}, 3},
{ch, 3},
{[]int{}, 0},
{map[int]int{}, 0},
{make(chan int), 0},
{[]int(nil), 0},
{map[int]int(nil), 0},
{(chan int)(nil), 0},
}
for _, c := range cases {
True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
}
cases = []struct {
v interface{}
l int
}{
{[]int{1, 2, 3}, 4},
{[...]int{1, 2, 3}, 2},
{"ABC", 2},
{map[int]int{1: 2, 2: 4, 3: 6}, 4},
{ch, 2},
{[]int{}, 1},
{map[int]int{}, 1},
{make(chan int), 1},
{[]int(nil), 1},
{map[int]int(nil), 1},
{(chan int)(nil), 1},
}
for _, c := range cases {
False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
}
}
func TestWithinDuration(t *testing.T) {
mockT := new(testing.T)
a := time.Now()
b := a.Add(10 * time.Second)
True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference")
True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference")
False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference")
False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference")
False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference")
False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference")
False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference")
False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference")
}
func TestInDelta(t *testing.T) {
mockT := new(testing.T)
True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01")
True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01")
True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1")
False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail")
False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail")
False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail")
False(t, InDelta(mockT, 42, math.NaN(), 0.01), "Expected NaN for actual to fail")
False(t, InDelta(mockT, math.NaN(), 42, 0.01), "Expected NaN for expected to fail")
True(t, InDelta(mockT, math.NaN(), math.NaN(), 0.01), "Expected NaN for both to pass")
cases := []struct {
a, b interface{}
delta float64
}{
{uint(2), uint(1), 1},
{uint8(2), uint8(1), 1},
{uint16(2), uint16(1), 1},
{uint32(2), uint32(1), 1},
{uint64(2), uint64(1), 1},
{int(2), int(1), 1},
{int8(2), int8(1), 1},
{int16(2), int16(1), 1},
{int32(2), int32(1), 1},
{int64(2), int64(1), 1},
{float32(2), float32(1), 1},
{float64(2), float64(1), 1},
}
for _, tc := range cases {
True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta)
}
}
func TestInDeltaSlice(t *testing.T) {
mockT := new(testing.T)
True(t, InDeltaSlice(mockT,
[]float64{1.001, math.NaN(), 0.999},
[]float64{1, math.NaN(), 1},
0.1), "{1.001, NaN, 0.009} is element-wise close to {1, NaN, 1} in delta=0.1")
True(t, InDeltaSlice(mockT,
[]float64{1, math.NaN(), 2},
[]float64{0, math.NaN(), 3},
1), "{1, NaN, 2} is element-wise close to {0, NaN, 3} in delta=1")
False(t, InDeltaSlice(mockT,
[]float64{1, math.NaN(), 2},
[]float64{0, math.NaN(), 3},
0.1), "{1, NaN, 2} is not element-wise close to {0, NaN, 3} in delta=0.1")
False(t, InDeltaSlice(mockT, "", nil, 1), "Expected non numeral slices to fail")
}
func TestInDeltaMapValues(t *testing.T) {
mockT := new(testing.T)
for _, tc := range []struct {
title string
expect interface{}
actual interface{}
f func(TestingT, bool, ...interface{}) bool
delta float64
}{
{
title: "Within delta",
expect: map[string]float64{
"foo": 1.0,
"bar": 2.0,
"baz": math.NaN(),
},
actual: map[string]float64{
"foo": 1.01,
"bar": 1.99,
"baz": math.NaN(),
},
delta: 0.1,
f: True,
},
{
title: "Within delta",
expect: map[int]float64{
1: 1.0,
2: 2.0,
},
actual: map[int]float64{
1: 1.0,
2: 1.99,
},
delta: 0.1,
f: True,
},
{
title: "Different number of keys",
expect: map[int]float64{
1: 1.0,
2: 2.0,
},
actual: map[int]float64{
1: 1.0,
},
delta: 0.1,
f: False,
},
{
title: "Within delta with zero value",
expect: map[string]float64{
"zero": 0,
},
actual: map[string]float64{
"zero": 0,
},
delta: 0.1,
f: True,
},
{
title: "With missing key with zero value",
expect: map[string]float64{
"zero": 0,
"foo": 0,
},
actual: map[string]float64{
"zero": 0,
"bar": 0,
},
f: False,
},
} {
tc.f(t, InDeltaMapValues(mockT, tc.expect, tc.actual, tc.delta), tc.title+"\n"+diff(tc.expect, tc.actual))
}
}
func TestInEpsilon(t *testing.T) {
mockT := new(testing.T)
cases := []struct {
a, b interface{}
epsilon float64
}{
{uint8(2), uint16(2), .001},
{2.1, 2.2, 0.1},
{2.2, 2.1, 0.1},
{-2.1, -2.2, 0.1},
{-2.2, -2.1, 0.1},
{uint64(100), uint8(101), 0.01},
{0.1, -0.1, 2},
{0.1, 0, 2},
{math.NaN(), math.NaN(), 1},
{time.Second, time.Second + time.Millisecond, 0.002},
}
for _, tc := range cases {
True(t, InEpsilon(t, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon), "test: %q", tc)
}
cases = []struct {
a, b interface{}
epsilon float64
}{
{uint8(2), int16(-2), .001},
{uint64(100), uint8(102), 0.01},
{2.1, 2.2, 0.001},
{2.2, 2.1, 0.001},
{2.1, -2.2, 1},
{2.1, "bla-bla", 0},
{0.1, -0.1, 1.99},
{0, 0.1, 2}, // expected must be different to zero
{time.Second, time.Second + 10*time.Millisecond, 0.002},
{math.NaN(), 0, 1},
{0, math.NaN(), 1},
{0, 0, math.NaN()},
}
for _, tc := range cases {
False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon))
}
}
func TestInEpsilonSlice(t *testing.T) {
mockT := new(testing.T)
True(t, InEpsilonSlice(mockT,
[]float64{2.2, math.NaN(), 2.0},
[]float64{2.1, math.NaN(), 2.1},
0.06), "{2.2, NaN, 2.0} is element-wise close to {2.1, NaN, 2.1} in espilon=0.06")
False(t, InEpsilonSlice(mockT,
[]float64{2.2, 2.0},
[]float64{2.1, 2.1},
0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in espilon=0.04")
False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail")
}
func TestRegexp(t *testing.T) {
mockT := new(testing.T)
cases := []struct {
rx, str string
}{
{"^start", "start of the line"},
{"end$", "in the end"},
{"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"},
}
for _, tc := range cases {
True(t, Regexp(mockT, tc.rx, tc.str))
True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
False(t, NotRegexp(mockT, tc.rx, tc.str))
False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
}
cases = []struct {
rx, str string
}{
{"^asdfastart", "Not the start of the line"},
{"end$", "in the end."},
{"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"},
}
for _, tc := range cases {
False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str)
False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
True(t, NotRegexp(mockT, tc.rx, tc.str))
True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
}
}
func testAutogeneratedFunction() {
defer func() {
if err := recover(); err == nil {
panic("did not panic")
}
CallerInfo()
}()
t := struct {
io.Closer
}{}
c := t
c.Close()
}
func TestCallerInfoWithAutogeneratedFunctions(t *testing.T) {
NotPanics(t, func() {
testAutogeneratedFunction()
})
}
func TestZero(t *testing.T) {
mockT := new(testing.T)
for _, test := range zeros {
True(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
}
for _, test := range nonZeros {
False(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
}
}
func TestNotZero(t *testing.T) {
mockT := new(testing.T)
for _, test := range zeros {
False(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
}
for _, test := range nonZeros {
True(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
}
}
func TestFileExists(t *testing.T) {
mockT := new(testing.T)
True(t, FileExists(mockT, "assertions.go"))
mockT = new(testing.T)
False(t, FileExists(mockT, "random_file"))
mockT = new(testing.T)
False(t, FileExists(mockT, "../_codegen"))
var tempFiles []string
link, err := getTempSymlinkPath("assertions.go")
if err != nil {
t.Fatal("could not create temp symlink, err:", err)
}
tempFiles = append(tempFiles, link)
mockT = new(testing.T)
True(t, FileExists(mockT, link))
link, err = getTempSymlinkPath("non_existent_file")
if err != nil {
t.Fatal("could not create temp symlink, err:", err)
}
tempFiles = append(tempFiles, link)
mockT = new(testing.T)
True(t, FileExists(mockT, link))
errs := cleanUpTempFiles(tempFiles)
if len(errs) > 0 {
t.Fatal("could not clean up temporary files")
}
}
func TestNoFileExists(t *testing.T) {
mockT := new(testing.T)
False(t, NoFileExists(mockT, "assertions.go"))
mockT = new(testing.T)
True(t, NoFileExists(mockT, "non_existent_file"))
mockT = new(testing.T)
True(t, NoFileExists(mockT, "../_codegen"))
var tempFiles []string
link, err := getTempSymlinkPath("assertions.go")
if err != nil {
t.Fatal("could not create temp symlink, err:", err)
}
tempFiles = append(tempFiles, link)
mockT = new(testing.T)
False(t, NoFileExists(mockT, link))
link, err = getTempSymlinkPath("non_existent_file")
if err != nil {
t.Fatal("could not create temp symlink, err:", err)
}
tempFiles = append(tempFiles, link)
mockT = new(testing.T)
False(t, NoFileExists(mockT, link))
errs := cleanUpTempFiles(tempFiles)
if len(errs) > 0 {
t.Fatal("could not clean up temporary files")
}
}
func getTempSymlinkPath(file string) (string, error) {
link := file + "_symlink"
err := os.Symlink(file, link)
return link, err
}
func cleanUpTempFiles(paths []string) []error {
var res []error
for _, path := range paths {
err := os.Remove(path)
if err != nil {
res = append(res, err)
}
}
return res
}
func TestDirExists(t *testing.T) {
mockT := new(testing.T)
False(t, DirExists(mockT, "assertions.go"))
mockT = new(testing.T)
False(t, DirExists(mockT, "non_existent_dir"))
mockT = new(testing.T)
True(t, DirExists(mockT, "../_codegen"))
var tempFiles []string
link, err := getTempSymlinkPath("assertions.go")
if err != nil {
t.Fatal("could not create temp symlink, err:", err)
}
tempFiles = append(tempFiles, link)
mockT = new(testing.T)
False(t, DirExists(mockT, link))
link, err = getTempSymlinkPath("non_existent_dir")
if err != nil {
t.Fatal("could not create temp symlink, err:", err)
}
tempFiles = append(tempFiles, link)
mockT = new(testing.T)
False(t, DirExists(mockT, link))
errs := cleanUpTempFiles(tempFiles)
if len(errs) > 0 {
t.Fatal("could not clean up temporary files")
}
}
func TestNoDirExists(t *testing.T) {
mockT := new(testing.T)
True(t, NoDirExists(mockT, "assertions.go"))
mockT = new(testing.T)
True(t, NoDirExists(mockT, "non_existent_dir"))
mockT = new(testing.T)
False(t, NoDirExists(mockT, "../_codegen"))
var tempFiles []string
link, err := getTempSymlinkPath("assertions.go")
if err != nil {
t.Fatal("could not create temp symlink, err:", err)
}
tempFiles = append(tempFiles, link)
mockT = new(testing.T)
True(t, NoDirExists(mockT, link))
link, err = getTempSymlinkPath("non_existent_dir")
if err != nil {
t.Fatal("could not create temp symlink, err:", err)
}
tempFiles = append(tempFiles, link)
mockT = new(testing.T)
True(t, NoDirExists(mockT, link))
errs := cleanUpTempFiles(tempFiles)
if len(errs) > 0 {
t.Fatal("could not clean up temporary files")
}
}
func TestJSONEq_EqualSONString(t *testing.T) {
mockT := new(testing.T)
True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`))
}
func TestJSONEq_EquivalentButNotEqual(t *testing.T) {
mockT := new(testing.T)
True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
}
func TestJSONEq_HashOfArraysAndHashes(t *testing.T) {
mockT := new(testing.T)
True(t, JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}",
"{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}"))
}
func TestJSONEq_Array(t *testing.T) {
mockT := new(testing.T)
True(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`))
}
func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) {
mockT := new(testing.T)
False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`))
}
func TestJSONEq_HashesNotEquivalent(t *testing.T) {
mockT := new(testing.T)
False(t, JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
}
func TestJSONEq_ActualIsNotJSON(t *testing.T) {
mockT := new(testing.T)
False(t, JSONEq(mockT, `{"foo": "bar"}`, "Not JSON"))
}
func TestJSONEq_ExpectedIsNotJSON(t *testing.T) {
mockT := new(testing.T)
False(t, JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`))
}
func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) {
mockT := new(testing.T)
False(t, JSONEq(mockT, "Not JSON", "Not JSON"))
}
func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) {
mockT := new(testing.T)
False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`))
}
func TestYAMLEq_EqualYAMLString(t *testing.T) {
mockT := new(testing.T)
True(t, YAMLEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`))
}
func TestYAMLEq_EquivalentButNotEqual(t *testing.T) {
mockT := new(testing.T)
True(t, YAMLEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
}
func TestYAMLEq_HashOfArraysAndHashes(t *testing.T) {
mockT := new(testing.T)
expected := `
numeric: 1.5
array:
- foo: bar
- 1
- "string"
- ["nested", "array", 5.5]
hash:
nested: hash
nested_slice: [this, is, nested]
string: "foo"
`
actual := `
numeric: 1.5
hash:
nested: hash
nested_slice: [this, is, nested]
string: "foo"
array:
- foo: bar
- 1
- "string"
- ["nested", "array", 5.5]
`
True(t, YAMLEq(mockT, expected, actual))
}
func TestYAMLEq_Array(t *testing.T) {
mockT := new(testing.T)
True(t, YAMLEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`))
}
func TestYAMLEq_HashAndArrayNotEquivalent(t *testing.T) {
mockT := new(testing.T)
False(t, YAMLEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`))
}
func TestYAMLEq_HashesNotEquivalent(t *testing.T) {
mockT := new(testing.T)
False(t, YAMLEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
}
func TestYAMLEq_ActualIsSimpleString(t *testing.T) {
mockT := new(testing.T)
False(t, YAMLEq(mockT, `{"foo": "bar"}`, "Simple String"))
}
func TestYAMLEq_ExpectedIsSimpleString(t *testing.T) {
mockT := new(testing.T)
False(t, YAMLEq(mockT, "Simple String", `{"foo": "bar", "hello": "world"}`))
}
func TestYAMLEq_ExpectedAndActualSimpleString(t *testing.T) {
mockT := new(testing.T)
True(t, YAMLEq(mockT, "Simple String", "Simple String"))
}
func TestYAMLEq_ArraysOfDifferentOrder(t *testing.T) {
mockT := new(testing.T)
False(t, YAMLEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`))
}
type diffTestingStruct struct {
A string
B int
}
func (d *diffTestingStruct) String() string {
return d.A
}
func TestDiff(t *testing.T) {
expected := `
Diff:
--- Expected
+++ Actual
@@ -1,3 +1,3 @@
(struct { foo string }) {
- foo: (string) (len=5) "hello"
+ foo: (string) (len=3) "bar"
}
`
actual := diff(
struct{ foo string }{"hello"},
struct{ foo string }{"bar"},
)
Equal(t, expected, actual)
expected = `
Diff:
--- Expected
+++ Actual
@@ -2,5 +2,5 @@
(int) 1,
- (int) 2,
(int) 3,
- (int) 4
+ (int) 5,
+ (int) 7
}
`
actual = diff(
[]int{1, 2, 3, 4},
[]int{1, 3, 5, 7},
)
Equal(t, expected, actual)
expected = `
Diff:
--- Expected
+++ Actual
@@ -2,4 +2,4 @@
(int) 1,
- (int) 2,
- (int) 3
+ (int) 3,
+ (int) 5
}
`
actual = diff(
[]int{1, 2, 3, 4}[0:3],
[]int{1, 3, 5, 7}[0:3],
)
Equal(t, expected, actual)
expected = `
Diff:
--- Expected
+++ Actual
@@ -1,6 +1,6 @@
(map[string]int) (len=4) {
- (string) (len=4) "four": (int) 4,
+ (string) (len=4) "five": (int) 5,
(string) (len=3) "one": (int) 1,
- (string) (len=5) "three": (int) 3,
- (string) (len=3) "two": (int) 2
+ (string) (len=5) "seven": (int) 7,
+ (string) (len=5) "three": (int) 3
}
`
actual = diff(
map[string]int{"one": 1, "two": 2, "three": 3, "four": 4},
map[string]int{"one": 1, "three": 3, "five": 5, "seven": 7},
)
Equal(t, expected, actual)
expected = `
Diff:
--- Expected
+++ Actual
@@ -1,3 +1,3 @@
(*errors.errorString)({
- s: (string) (len=19) "some expected error"
+ s: (string) (len=12) "actual error"
})
`
actual = diff(
errors.New("some expected error"),
errors.New("actual error"),
)
Equal(t, expected, actual)
expected = `
Diff:
--- Expected
+++ Actual
@@ -2,3 +2,3 @@
A: (string) (len=11) "some string",
- B: (int) 10
+ B: (int) 15
}
`
actual = diff(
diffTestingStruct{A: "some string", B: 10},
diffTestingStruct{A: "some string", B: 15},
)
Equal(t, expected, actual)
expected = `
Diff:
--- Expected
+++ Actual
@@ -1,2 +1,2 @@
-(time.Time) 2020-09-24 00:00:00 +0000 UTC
+(time.Time) 2020-09-25 00:00:00 +0000 UTC
`
actual = diff(
time.Date(2020, 9, 24, 0, 0, 0, 0, time.UTC),
time.Date(2020, 9, 25, 0, 0, 0, 0, time.UTC),
)
Equal(t, expected, actual)
}
func TestTimeEqualityErrorFormatting(t *testing.T) {
mockT := new(mockTestingT)
Equal(mockT, time.Second*2, time.Millisecond)
expectedErr := "\\s+Error Trace:\\s+Error:\\s+Not equal:\\s+\n\\s+expected: 2s\n\\s+actual\\s+: 1ms\n"
Regexp(t, regexp.MustCompile(expectedErr), mockT.errorString())
}
func TestDiffEmptyCases(t *testing.T) {
Equal(t, "", diff(nil, nil))
Equal(t, "", diff(struct{ foo string }{}, nil))
Equal(t, "", diff(nil, struct{ foo string }{}))
Equal(t, "", diff(1, 2))
Equal(t, "", diff(1, 2))
Equal(t, "", diff([]int{1}, []bool{true}))
}
// Ensure there are no data races
func TestDiffRace(t *testing.T) {
t.Parallel()
expected := map[string]string{
"a": "A",
"b": "B",
"c": "C",
}
actual := map[string]string{
"d": "D",
"e": "E",
"f": "F",
}
// run diffs in parallel simulating tests with t.Parallel()
numRoutines := 10
rChans := make([]chan string, numRoutines)
for idx := range rChans {
rChans[idx] = make(chan string)
go func(ch chan string) {
defer close(ch)
ch <- diff(expected, actual)
}(rChans[idx])
}
for _, ch := range rChans {
for msg := range ch {
NotZero(t, msg) // dummy assert
}
}
}
type mockTestingT struct {
errorFmt string
args []interface{}
}
func (m *mockTestingT) errorString() string {
return fmt.Sprintf(m.errorFmt, m.args...)
}
func (m *mockTestingT) Errorf(format string, args ...interface{}) {
m.errorFmt = format
m.args = args
}
func TestFailNowWithPlainTestingT(t *testing.T) {
mockT := &mockTestingT{}
Panics(t, func() {
FailNow(mockT, "failed")
}, "should panic since mockT is missing FailNow()")
}
type mockFailNowTestingT struct {
}
func (m *mockFailNowTestingT) Errorf(format string, args ...interface{}) {}
func (m *mockFailNowTestingT) FailNow() {}
func TestFailNowWithFullTestingT(t *testing.T) {
mockT := &mockFailNowTestingT{}
NotPanics(t, func() {
FailNow(mockT, "failed")
}, "should call mockT.FailNow() rather than panicking")
}
func TestBytesEqual(t *testing.T) {
var cases = []struct {
a, b []byte
}{
{make([]byte, 2), make([]byte, 2)},
{make([]byte, 2), make([]byte, 2, 3)},
{nil, make([]byte, 0)},
}
for i, c := range cases {
Equal(t, reflect.DeepEqual(c.a, c.b), ObjectsAreEqual(c.a, c.b), "case %d failed", i+1)
}
}
func BenchmarkBytesEqual(b *testing.B) {
const size = 1024 * 8
s := make([]byte, size)
for i := range s {
s[i] = byte(i % 255)
}
s2 := make([]byte, size)
copy(s2, s)
mockT := &mockFailNowTestingT{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
Equal(mockT, s, s2)
}
}
func BenchmarkNotNil(b *testing.B) {
for i := 0; i < b.N; i++ {
NotNil(b, b)
}
}
func ExampleComparisonAssertionFunc() {
t := &testing.T{} // provided by test
adder := func(x, y int) int {
return x + y
}
type args struct {
x int
y int
}
tests := []struct {
name string
args args
expect int
assertion ComparisonAssertionFunc
}{
{"2+2=4", args{2, 2}, 4, Equal},
{"2+2!=5", args{2, 2}, 5, NotEqual},
{"2+3==5", args{2, 3}, 5, Exactly},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.assertion(t, tt.expect, adder(tt.args.x, tt.args.y))
})
}
}
func TestComparisonAssertionFunc(t *testing.T) {
type iface interface {
Name() string
}
tests := []struct {
name string
expect interface{}
got interface{}
assertion ComparisonAssertionFunc
}{
{"implements", (*iface)(nil), t, Implements},
{"isType", (*testing.T)(nil), t, IsType},
{"equal", t, t, Equal},
{"equalValues", t, t, EqualValues},
{"notEqualValues", t, nil, NotEqualValues},
{"exactly", t, t, Exactly},
{"notEqual", t, nil, NotEqual},
{"notContains", []int{1, 2, 3}, 4, NotContains},
{"subset", []int{1, 2, 3, 4}, []int{2, 3}, Subset},
{"notSubset", []int{1, 2, 3, 4}, []int{0, 3}, NotSubset},
{"elementsMatch", []byte("abc"), []byte("bac"), ElementsMatch},
{"regexp", "^t.*y$", "testify", Regexp},
{"notRegexp", "^t.*y$", "Testify", NotRegexp},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.assertion(t, tt.expect, tt.got)
})
}
}
func ExampleValueAssertionFunc() {
t := &testing.T{} // provided by test
dumbParse := func(input string) interface{} {
var x interface{}
_ = json.Unmarshal([]byte(input), &x)
return x
}
tests := []struct {
name string
arg string
assertion ValueAssertionFunc
}{
{"true is not nil", "true", NotNil},
{"empty string is nil", "", Nil},
{"zero is not nil", "0", NotNil},
{"zero is zero", "0", Zero},
{"false is zero", "false", Zero},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.assertion(t, dumbParse(tt.arg))
})
}
}
func TestValueAssertionFunc(t *testing.T) {
tests := []struct {
name string
value interface{}
assertion ValueAssertionFunc
}{
{"notNil", true, NotNil},
{"nil", nil, Nil},
{"empty", []int{}, Empty},
{"notEmpty", []int{1}, NotEmpty},
{"zero", false, Zero},
{"notZero", 42, NotZero},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.assertion(t, tt.value)
})
}
}
func ExampleBoolAssertionFunc() {
t := &testing.T{} // provided by test
isOkay := func(x int) bool {
return x >= 42
}
tests := []struct {
name string
arg int
assertion BoolAssertionFunc
}{
{"-1 is bad", -1, False},
{"42 is good", 42, True},
{"41 is bad", 41, False},
{"45 is cool", 45, True},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.assertion(t, isOkay(tt.arg))
})
}
}
func TestBoolAssertionFunc(t *testing.T) {
tests := []struct {
name string
value bool
assertion BoolAssertionFunc
}{
{"true", true, True},
{"false", false, False},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.assertion(t, tt.value)
})
}
}
func ExampleErrorAssertionFunc() {
t := &testing.T{} // provided by test
dumbParseNum := func(input string, v interface{}) error {
return json.Unmarshal([]byte(input), v)
}
tests := []struct {
name string
arg string
assertion ErrorAssertionFunc
}{
{"1.2 is number", "1.2", NoError},
{"1.2.3 not number", "1.2.3", Error},
{"true is not number", "true", Error},
{"3 is number", "3", NoError},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var x float64
tt.assertion(t, dumbParseNum(tt.arg, &x))
})
}
}
func TestErrorAssertionFunc(t *testing.T) {
tests := []struct {
name string
err error
assertion ErrorAssertionFunc
}{
{"noError", nil, NoError},
{"error", errors.New("whoops"), Error},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.assertion(t, tt.err)
})
}
}
func TestEventuallyFalse(t *testing.T) {
mockT := new(testing.T)
condition := func() bool {
return false
}
False(t, Eventually(mockT, condition, 100*time.Millisecond, 20*time.Millisecond))
}
func TestEventuallyTrue(t *testing.T) {
state := 0
condition := func() bool {
defer func() {
state += 1
}()
return state == 2
}
True(t, Eventually(t, condition, 100*time.Millisecond, 20*time.Millisecond))
}
func TestNeverFalse(t *testing.T) {
condition := func() bool {
return false
}
True(t, Never(t, condition, 100*time.Millisecond, 20*time.Millisecond))
}
func TestNeverTrue(t *testing.T) {
mockT := new(testing.T)
state := 0
condition := func() bool {
defer func() {
state = state + 1
}()
return state == 2
}
False(t, Never(mockT, condition, 100*time.Millisecond, 20*time.Millisecond))
}
func TestEventuallyIssue805(t *testing.T) {
mockT := new(testing.T)
NotPanics(t, func() {
condition := func() bool { <-time.After(time.Millisecond); return true }
False(t, Eventually(mockT, condition, time.Millisecond, time.Microsecond))
})
}
func Test_validateEqualArgs(t *testing.T) {
if validateEqualArgs(func() {}, func() {}) == nil {
t.Error("non-nil functions should error")
}
if validateEqualArgs(func() {}, func() {}) == nil {
t.Error("non-nil functions should error")
}
if validateEqualArgs(nil, nil) != nil {
t.Error("nil functions are equal")
}
}
func Test_truncatingFormat(t *testing.T) {
original := strings.Repeat("a", bufio.MaxScanTokenSize-102)
result := truncatingFormat(original)
Equal(t, fmt.Sprintf("%#v", original), result, "string should not be truncated")
original = original + "x"
result = truncatingFormat(original)
NotEqual(t, fmt.Sprintf("%#v", original), result, "string should have been truncated.")
if !strings.HasSuffix(result, "<... truncated>") {
t.Error("truncated string should have <... truncated> suffix")
}
}
func TestErrorIs(t *testing.T) {
mockT := new(testing.T)
tests := []struct {
err error
target error
result bool
}{
{io.EOF, io.EOF, true},
{fmt.Errorf("wrap: %w", io.EOF), io.EOF, true},
{io.EOF, io.ErrClosedPipe, false},
{nil, io.EOF, false},
{io.EOF, nil, false},
{nil, nil, true},
}
for _, tt := range tests {
tt := tt
t.Run(fmt.Sprintf("ErrorIs(%#v,%#v)", tt.err, tt.target), func(t *testing.T) {
res := ErrorIs(mockT, tt.err, tt.target)
if res != tt.result {
t.Errorf("ErrorIs(%#v,%#v) should return %t", tt.err, tt.target, tt.result)
}
})
}
}
func TestNotErrorIs(t *testing.T) {
mockT := new(testing.T)
tests := []struct {
err error
target error
result bool
}{
{io.EOF, io.EOF, false},
{fmt.Errorf("wrap: %w", io.EOF), io.EOF, false},
{io.EOF, io.ErrClosedPipe, true},
{nil, io.EOF, true},
{io.EOF, nil, true},
{nil, nil, false},
}
for _, tt := range tests {
tt := tt
t.Run(fmt.Sprintf("NotErrorIs(%#v,%#v)", tt.err, tt.target), func(t *testing.T) {
res := NotErrorIs(mockT, tt.err, tt.target)
if res != tt.result {
t.Errorf("NotErrorIs(%#v,%#v) should return %t", tt.err, tt.target, tt.result)
}
})
}
}
func TestErrorAs(t *testing.T) {
mockT := new(testing.T)
tests := []struct {
err error
result bool
}{
{fmt.Errorf("wrap: %w", &customError{}), true},
{io.EOF, false},
{nil, false},
}
for _, tt := range tests {
tt := tt
var target *customError
t.Run(fmt.Sprintf("ErrorAs(%#v,%#v)", tt.err, target), func(t *testing.T) {
res := ErrorAs(mockT, tt.err, &target)
if res != tt.result {
t.Errorf("ErrorAs(%#v,%#v) should return %t)", tt.err, target, tt.result)
}
})
}
}
|