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
|
// Copyright ©2018 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package testgraph provides a set of testing helper functions
// that test Gonum graph interface implementations.
package testgraph // import "gonum.org/v1/gonum/graph/testgraph"
import (
"cmp"
"fmt"
"reflect"
"slices"
"testing"
"golang.org/x/exp/rand"
"gonum.org/v1/gonum/floats/scalar"
"gonum.org/v1/gonum/graph"
"gonum.org/v1/gonum/graph/internal/set"
"gonum.org/v1/gonum/internal/order"
"gonum.org/v1/gonum/mat"
)
// BUG(kortschak): Edge equality is tested in part with reflect.DeepEqual and
// direct equality of weight values. This means that edges returned by graphs
// must not contain NaN values. Weights returned by the Weight method are
// compared with NaN-awareness, so they may be NaN when there is no edge
// associated with the Weight call.
func isValidIterator(it graph.Iterator) bool {
return it != nil
}
func checkEmptyIterator(t *testing.T, it graph.Iterator, useEmpty bool) {
t.Helper()
if it.Len() != 0 {
return
}
if it != graph.Empty {
if useEmpty {
t.Errorf("unexpected empty iterator: got:%T", it)
return
}
// Only log this since we say that a graph should
// return a graph.Empty when it is empty.
t.Logf("unexpected empty iterator: got:%T", it)
}
}
func hasEnds(x, y graph.Node, e Edge) bool {
return (e.From().ID() == x.ID() && e.To().ID() == y.ID()) ||
(e.From().ID() == y.ID() && e.To().ID() == x.ID())
}
// Edge supports basic edge operations.
type Edge interface {
// From returns the from node of the edge.
From() graph.Node
// To returns the to node of the edge.
To() graph.Node
}
// WeightedLine is a generalized graph edge that supports all graph
// edge operations except reversal.
type WeightedLine interface {
Edge
// ID returns the unique ID for the Line.
ID() int64
// Weight returns the weight of the edge.
Weight() float64
}
// A Builder function returns a graph constructed from the nodes, edges and
// default weights passed in, potentially altering the nodes and edges to
// conform to the requirements of the graph. The graph is returned along with
// the nodes, edges and default weights used to construct the graph.
// The returned edges may be any of graph.Edge, graph.WeightedEdge, graph.Line
// or graph.WeightedLine depending on what the graph requires.
// The client may skip a test case by returning ok=false when the input is not
// a valid graph construction.
type Builder func(nodes []graph.Node, edges []WeightedLine, self, absent float64) (g graph.Graph, n []graph.Node, e []Edge, s, a float64, ok bool)
// edgeLister is a graph that can return all its edges.
type edgeLister interface {
// Edges returns all the edges of a graph.
Edges() graph.Edges
}
// weightedEdgeLister is a graph that can return all its weighted edges.
type weightedEdgeLister interface {
// WeightedEdges returns all the weighted edges of a graph.
WeightedEdges() graph.WeightedEdges
}
// matrixer is a graph that can return an adjacency matrix.
type matrixer interface {
// Matrix returns the graph's adjacency matrix.
Matrix() mat.Matrix
}
// ReturnAllNodes tests the constructed graph for the ability to return all
// the nodes it claims it has used in its construction. This is a check of
// the Nodes method of graph.Graph and the iterator that is returned.
// If useEmpty is true, graph iterators will be checked for the use of
// graph.Empty if they are empty.
func ReturnAllNodes(t *testing.T, b Builder, useEmpty bool) {
for _, test := range testCases {
g, want, _, _, _, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
it := g.Nodes()
if !isValidIterator(it) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, it)
continue
}
checkEmptyIterator(t, it, useEmpty)
var got []graph.Node
for it.Next() {
got = append(got, it.Node())
}
order.ByID(got)
order.ByID(want)
if !reflect.DeepEqual(got, want) {
t.Errorf("unexpected nodes result for test %q:\ngot: %v\nwant:%v", test.name, got, want)
}
}
}
// ReturnNodeSlice tests the constructed graph for the ability to return all
// the nodes it claims it has used in its construction using the NodeSlicer
// interface. This is a check of the Nodes method of graph.Graph and the
// iterator that is returned.
// If useEmpty is true, graph iterators will be checked for the use of
// graph.Empty if they are empty.
func ReturnNodeSlice(t *testing.T, b Builder, useEmpty bool) {
for _, test := range testCases {
g, want, _, _, _, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
it := g.Nodes()
if !isValidIterator(it) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, it)
continue
}
checkEmptyIterator(t, it, useEmpty)
if it == nil {
continue
}
s, ok := it.(graph.NodeSlicer)
if !ok {
t.Errorf("invalid type for test %q: %T cannot return node slicer", test.name, g)
continue
}
got := s.NodeSlice()
order.ByID(got)
order.ByID(want)
if !reflect.DeepEqual(got, want) {
t.Errorf("unexpected nodes result for test %q:\ngot: %v\nwant:%v", test.name, got, want)
}
}
}
// NodeExistence tests the constructed graph for the ability to correctly
// return the existence of nodes within the graph. This is a check of the
// Node method of graph.Graph.
func NodeExistence(t *testing.T, b Builder) {
for _, test := range testCases {
g, want, _, _, _, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
seen := set.NewNodes()
for _, exist := range want {
seen.Add(exist)
if g.Node(exist.ID()) == nil {
t.Errorf("missing node for test %q: %v", test.name, exist)
}
}
for _, ghost := range test.nonexist {
if g.Node(ghost.ID()) != nil {
if seen.Has(ghost) {
// Do not fail nodes that the graph builder says can exist
// even if the test case input thinks they should not.
t.Logf("builder has modified non-exist node set: %v is now allowed and present", ghost)
continue
}
t.Errorf("unexpected node for test %q: %v", test.name, ghost)
}
}
}
}
// ReturnAllEdges tests the constructed graph for the ability to return all
// the edges it claims it has used in its construction. This is a check of
// the Edges method of graph.Graph and the iterator that is returned.
// ReturnAllEdges also checks that the edge end nodes exist within the graph,
// checking the Node method of graph.Graph.
// If useEmpty is true, graph iterators will be checked for the use of
// graph.Empty if they are empty.
func ReturnAllEdges(t *testing.T, b Builder, useEmpty bool) {
for _, test := range testCases {
g, _, want, _, _, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
var got []Edge
switch eg := g.(type) {
case edgeLister:
it := eg.Edges()
if !isValidIterator(it) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, it)
continue
}
checkEmptyIterator(t, it, useEmpty)
for it.Next() {
e := it.Edge()
got = append(got, e)
qe := g.Edge(e.From().ID(), e.To().ID())
if qe == nil {
t.Errorf("missing edge for test %q: %v", test.name, e)
} else if qe.From().ID() != e.From().ID() || qe.To().ID() != e.To().ID() {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, e.From().ID(), e.To().ID(), qe)
}
if g.Node(e.From().ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, e.From().ID())
}
if g.Node(e.To().ID()) == nil {
t.Errorf("missing to node for test %q: %v", test.name, e.To().ID())
}
}
default:
t.Errorf("invalid type for test %q: %T cannot return edge iterator", test.name, g)
continue
}
checkEdges(t, test.name, g, got, want)
}
}
// ReturnEdgeSlice tests the constructed graph for the ability to return all
// the edges it claims it has used in its construction using the EdgeSlicer
// interface. This is a check of the Edges method of graph.Graph and the
// iterator that is returned. ReturnEdgeSlice also checks that the edge end
// nodes exist within the graph, checking the Node method of graph.Graph.
// If useEmpty is true, graph iterators will be checked for the use of
// graph.Empty if they are empty.
func ReturnEdgeSlice(t *testing.T, b Builder, useEmpty bool) {
for _, test := range testCases {
g, _, want, _, _, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
var got []Edge
switch eg := g.(type) {
case edgeLister:
it := eg.Edges()
if !isValidIterator(it) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, it)
continue
}
checkEmptyIterator(t, it, useEmpty)
if it == nil {
continue
}
s, ok := it.(graph.EdgeSlicer)
if !ok {
t.Errorf("invalid type for test %q: %T cannot return edge slicer", test.name, g)
continue
}
gotNative := s.EdgeSlice()
if len(gotNative) != 0 {
got = make([]Edge, len(gotNative))
}
for i, e := range gotNative {
got[i] = e
qe := g.Edge(e.From().ID(), e.To().ID())
if qe == nil {
t.Errorf("missing edge for test %q: %v", test.name, e)
} else if qe.From().ID() != e.From().ID() || qe.To().ID() != e.To().ID() {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, e.From().ID(), e.To().ID(), qe)
}
if g.Node(e.From().ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, e.From().ID())
}
if g.Node(e.To().ID()) == nil {
t.Errorf("missing to node for test %q: %v", test.name, e.To().ID())
}
}
default:
t.Errorf("invalid type for test %T: cannot return edge iterator", g)
continue
}
checkEdges(t, test.name, g, got, want)
}
}
// ReturnAllLines tests the constructed graph for the ability to return all
// the edges it claims it has used in its construction and then recover all
// the lines that contribute to those edges. This is a check of the Edges
// method of graph.Graph and the iterator that is returned and the graph.Lines
// implementation of those edges. ReturnAllLines also checks that the edge
// end nodes exist within the graph, checking the Node method of graph.Graph.
//
// The edges used within and returned by the Builder function should be
// graph.Line. The edge parameter passed to b will contain only graph.Line.
// If useEmpty is true, graph iterators will be checked for the use of
// graph.Empty if they are empty.
func ReturnAllLines(t *testing.T, b Builder, useEmpty bool) {
for _, test := range testCases {
g, _, want, _, _, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
var got []Edge
switch eg := g.(type) {
case edgeLister:
it := eg.Edges()
if !isValidIterator(it) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, it)
continue
}
checkEmptyIterator(t, it, useEmpty)
for _, e := range graph.EdgesOf(it) {
qe := g.Edge(e.From().ID(), e.To().ID())
if qe == nil {
t.Errorf("missing edge for test %q: %v", test.name, e)
} else if qe.From().ID() != e.From().ID() || qe.To().ID() != e.To().ID() {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, e.From().ID(), e.To().ID(), qe)
}
// FIXME(kortschak): This would not be necessary
// if graph.WeightedLines (and by symmetry)
// graph.WeightedEdges also were graph.Lines
// and graph.Edges.
switch lit := e.(type) {
case graph.Lines:
if !isValidIterator(lit) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, lit)
continue
}
checkEmptyIterator(t, lit, useEmpty)
for lit.Next() {
got = append(got, lit.Line())
}
case graph.WeightedLines:
if !isValidIterator(lit) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, lit)
continue
}
checkEmptyIterator(t, lit, useEmpty)
for lit.Next() {
got = append(got, lit.WeightedLine())
}
default:
continue
}
if g.Node(e.From().ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, e.From().ID())
}
if g.Node(e.To().ID()) == nil {
t.Errorf("missing to node for test %q: %v", test.name, e.To().ID())
}
}
default:
t.Errorf("invalid type for test: %T cannot return edge iterator", g)
continue
}
checkEdges(t, test.name, g, got, want)
}
}
// ReturnAllWeightedEdges tests the constructed graph for the ability to return
// all the edges it claims it has used in its construction. This is a check of
// the Edges method of graph.Graph and the iterator that is returned.
// ReturnAllWeightedEdges also checks that the edge end nodes exist within the
// graph, checking the Node method of graph.Graph.
//
// The edges used within and returned by the Builder function should be
// graph.WeightedEdge. The edge parameter passed to b will contain only
// graph.WeightedEdge.
// If useEmpty is true, graph iterators will be checked for the use of
// graph.Empty if they are empty.
func ReturnAllWeightedEdges(t *testing.T, b Builder, useEmpty bool) {
for _, test := range testCases {
g, _, want, _, _, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
var got []Edge
switch eg := g.(type) {
case weightedEdgeLister:
it := eg.WeightedEdges()
if !isValidIterator(it) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, it)
continue
}
checkEmptyIterator(t, it, useEmpty)
for it.Next() {
e := it.WeightedEdge()
got = append(got, e)
switch g := g.(type) {
case graph.Weighted:
qe := g.WeightedEdge(e.From().ID(), e.To().ID())
if qe == nil {
t.Errorf("missing edge for test %q: %v", test.name, e)
} else if qe.From().ID() != e.From().ID() || qe.To().ID() != e.To().ID() {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, e.From().ID(), e.To().ID(), qe)
}
default:
t.Logf("weighted edge lister is not a weighted graph - are you sure?: %T", g)
qe := g.Edge(e.From().ID(), e.To().ID())
if qe == nil {
t.Errorf("missing edge for test %q: %v", test.name, e)
} else if qe.From().ID() != e.From().ID() || qe.To().ID() != e.To().ID() {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, e.From().ID(), e.To().ID(), qe)
}
}
if g.Node(e.From().ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, e.From().ID())
}
if g.Node(e.To().ID()) == nil {
t.Errorf("missing to node for test %q: %v", test.name, e.To().ID())
}
}
default:
t.Errorf("invalid type for test: %T cannot return weighted edge iterator", g)
continue
}
checkEdges(t, test.name, g, got, want)
}
}
// ReturnWeightedEdgeSlice tests the constructed graph for the ability to
// return all the edges it claims it has used in its construction using the
// WeightedEdgeSlicer interface. This is a check of the Edges method of
// graph.Graph and the iterator that is returned. ReturnWeightedEdgeSlice
// also checks that the edge end nodes exist within the graph, checking
// the Node method of graph.Graph.
//
// The edges used within and returned by the Builder function should be
// graph.WeightedEdge. The edge parameter passed to b will contain only
// graph.WeightedEdge.
// If useEmpty is true, graph iterators will be checked for the use of
// graph.Empty if they are empty.
func ReturnWeightedEdgeSlice(t *testing.T, b Builder, useEmpty bool) {
for _, test := range testCases {
g, _, want, _, _, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
var got []Edge
switch eg := g.(type) {
case weightedEdgeLister:
it := eg.WeightedEdges()
if !isValidIterator(it) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, it)
continue
}
checkEmptyIterator(t, it, useEmpty)
s, ok := it.(graph.WeightedEdgeSlicer)
if !ok {
t.Errorf("invalid type for test %T: cannot return weighted edge slice", g)
continue
}
for _, e := range s.WeightedEdgeSlice() {
got = append(got, e)
qe := g.Edge(e.From().ID(), e.To().ID())
if qe == nil {
t.Errorf("missing edge for test %q: %v", test.name, e)
} else if qe.From().ID() != e.From().ID() || qe.To().ID() != e.To().ID() {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, e.From().ID(), e.To().ID(), qe)
}
if g.Node(e.From().ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, e.From().ID())
}
if g.Node(e.To().ID()) == nil {
t.Errorf("missing to node for test %q: %v", test.name, e.To().ID())
}
}
default:
t.Errorf("invalid type for test: %T cannot return weighted edge iterator", g)
continue
}
checkEdges(t, test.name, g, got, want)
}
}
// ReturnAllWeightedLines tests the constructed graph for the ability to return
// all the edges it claims it has used in its construction and then recover all
// the lines that contribute to those edges. This is a check of the Edges
// method of graph.Graph and the iterator that is returned and the graph.Lines
// implementation of those edges. ReturnAllWeightedLines also checks that the
// edge end nodes exist within the graph, checking the Node method of
// graph.Graph.
//
// The edges used within and returned by the Builder function should be
// graph.WeightedLine. The edge parameter passed to b will contain only
// graph.WeightedLine.
// If useEmpty is true, graph iterators will be checked for the use of
// graph.Empty if they are empty.
func ReturnAllWeightedLines(t *testing.T, b Builder, useEmpty bool) {
for _, test := range testCases {
g, _, want, _, _, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
var got []Edge
switch eg := g.(type) {
case weightedEdgeLister:
it := eg.WeightedEdges()
if !isValidIterator(it) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, it)
continue
}
checkEmptyIterator(t, it, useEmpty)
for _, e := range graph.WeightedEdgesOf(it) {
qe := g.Edge(e.From().ID(), e.To().ID())
if qe == nil {
t.Errorf("missing edge for test %q: %v", test.name, e)
} else if qe.From().ID() != e.From().ID() || qe.To().ID() != e.To().ID() {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, e.From().ID(), e.To().ID(), qe)
}
// FIXME(kortschak): This would not be necessary
// if graph.WeightedLines (and by symmetry)
// graph.WeightedEdges also were graph.Lines
// and graph.Edges.
switch lit := e.(type) {
case graph.Lines:
if !isValidIterator(lit) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, lit)
continue
}
checkEmptyIterator(t, lit, useEmpty)
for lit.Next() {
got = append(got, lit.Line())
}
case graph.WeightedLines:
if !isValidIterator(lit) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, lit)
continue
}
checkEmptyIterator(t, lit, useEmpty)
for lit.Next() {
got = append(got, lit.WeightedLine())
}
default:
continue
}
if g.Node(e.From().ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, e.From().ID())
}
if g.Node(e.To().ID()) == nil {
t.Errorf("missing to node for test %q: %v", test.name, e.To().ID())
}
}
default:
t.Errorf("invalid type for test: %T cannot return edge iterator", g)
continue
}
checkEdges(t, test.name, g, got, want)
}
}
// checkEdges compares got and want for the given graph type.
func checkEdges(t *testing.T, name string, g graph.Graph, got, want []Edge) {
t.Helper()
switch g.(type) {
case graph.Undirected:
sortLexicalUndirectedEdges(got)
sortLexicalUndirectedEdges(want)
if !undirectedEdgeSetEqual(got, want) {
t.Errorf("unexpected edges result for test %q:\ngot: %#v\nwant:%#v", name, got, want)
}
default:
sortLexicalEdges(got)
sortLexicalEdges(want)
if !reflect.DeepEqual(got, want) {
t.Errorf("unexpected edges result for test %q:\ngot: %#v\nwant:%#v", name, got, want)
}
}
}
// EdgeExistence tests the constructed graph for the ability to correctly
// return the existence of edges within the graph. This is a check of the
// Edge methods of graph.Graph, the EdgeBetween method of graph.Undirected
// and the EdgeFromTo method of graph.Directed. EdgeExistence also checks
// that the nodes and traversed edges exist within the graph, checking the
// Node, Edge, EdgeBetween and HasEdgeBetween methods of graph.Graph, the
// EdgeBetween method of graph.Undirected and the HasEdgeFromTo method of
// graph.Directed. If reversedEdge is true, edges will be checked to make
// sure edges returned match the orientation of an Edge or WeightedEdge
// call.
func EdgeExistence(t *testing.T, b Builder, reversedEdge bool) {
for _, test := range testCases {
g, nodes, edges, _, _, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
want := make(map[edge]bool)
for _, e := range edges {
want[edge{f: e.From().ID(), t: e.To().ID()}] = true
}
for _, x := range nodes {
for _, y := range nodes {
between := want[edge{f: x.ID(), t: y.ID()}] || want[edge{f: y.ID(), t: x.ID()}]
if has := g.HasEdgeBetween(x.ID(), y.ID()); has != between {
if has {
t.Errorf("unexpected edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
} else {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
}
} else {
if want[edge{f: x.ID(), t: y.ID()}] {
e := g.Edge(x.ID(), y.ID())
if e == nil || !hasEnds(x, y, e) {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
} else if reversedEdge && (e.From().ID() != x.ID() || e.To().ID() != y.ID()) {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, x.ID(), y.ID(), e)
}
}
if between && !g.HasEdgeBetween(x.ID(), y.ID()) {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
}
if g.Node(x.ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, x.ID())
}
if g.Node(y.ID()) == nil {
t.Errorf("missing to node for test %q: %v", test.name, y.ID())
}
}
switch g := g.(type) {
case graph.Directed:
u := x
v := y
if has := g.HasEdgeFromTo(u.ID(), v.ID()); has != want[edge{f: u.ID(), t: v.ID()}] {
if has {
t.Errorf("unexpected edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
} else {
t.Errorf("missing edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
}
continue
}
// Edge has already been tested above.
if g.Node(u.ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, u.ID())
}
if g.Node(v.ID()) == nil {
t.Errorf("missing to node for test %q: %v", test.name, v.ID())
}
case graph.Undirected:
// HasEdgeBetween is already tested above.
if between && g.Edge(x.ID(), y.ID()) == nil {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
}
if between && g.EdgeBetween(x.ID(), y.ID()) == nil {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
}
}
switch g := g.(type) {
case graph.WeightedDirected:
u := x
v := y
if has := g.WeightedEdge(u.ID(), v.ID()) != nil; has != want[edge{f: u.ID(), t: v.ID()}] {
if has {
t.Errorf("unexpected edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
} else {
t.Errorf("missing edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
}
continue
}
case graph.WeightedUndirected:
// HasEdgeBetween is already tested above.
if between && g.WeightedEdge(x.ID(), y.ID()) == nil {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
}
if between && g.WeightedEdgeBetween(x.ID(), y.ID()) == nil {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
}
}
}
}
}
}
// LineExistence tests the constructed graph for the ability to correctly
// return the existence of lines within the graph. This is a check of the
// Line methods of graph.Multigraph, the EdgeBetween method of graph.Undirected
// and the EdgeFromTo method of graph.Directed. LineExistence also checks
// that the nodes and traversed edges exist within the graph, checking the
// Node, Edge, EdgeBetween and HasEdgeBetween methods of graph.Graph, the
// EdgeBetween method of graph.Undirected and the HasEdgeFromTo method of
// graph.Directed. If reversedLine is true, lines will be checked to make
// sure lines returned match the orientation of an Line or WeightedLine
// call.
func LineExistence(t *testing.T, b Builder, useEmpty, reversedLine bool) {
for _, test := range testCases {
g, nodes, edges, _, _, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
switch mg := g.(type) {
case graph.Multigraph:
want := make(map[edge]bool)
for _, e := range edges {
want[edge{f: e.From().ID(), t: e.To().ID()}] = true
}
for _, x := range nodes {
for _, y := range nodes {
between := want[edge{f: x.ID(), t: y.ID()}] || want[edge{f: y.ID(), t: x.ID()}]
if has := g.HasEdgeBetween(x.ID(), y.ID()); has != between {
if has {
t.Errorf("unexpected edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
} else {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
}
} else {
if want[edge{f: x.ID(), t: y.ID()}] {
lit := mg.Lines(x.ID(), y.ID())
if !isValidIterator(lit) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, lit)
continue
}
checkEmptyIterator(t, lit, useEmpty)
if lit.Len() == 0 {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
} else {
for lit.Next() {
l := lit.Line()
if l == nil || !hasEnds(x, y, l) {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
} else if reversedLine && (l.From().ID() != x.ID() || l.To().ID() != y.ID()) {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, x.ID(), y.ID(), l)
}
}
}
}
if between && !g.HasEdgeBetween(x.ID(), y.ID()) {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
}
if g.Node(x.ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, x.ID())
}
if g.Node(y.ID()) == nil {
t.Errorf("missing to node for test %q: %v", test.name, y.ID())
}
}
switch g := g.(type) {
case graph.DirectedMultigraph:
u := x
v := y
if has := g.HasEdgeFromTo(u.ID(), v.ID()); has != want[edge{f: u.ID(), t: v.ID()}] {
if has {
t.Errorf("unexpected edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
} else {
t.Errorf("missing edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
}
continue
}
// Edge has already been tested above.
if g.Node(u.ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, u.ID())
}
if g.Node(v.ID()) == nil {
t.Errorf("missing to node for test %q: %v", test.name, v.ID())
}
case graph.UndirectedMultigraph:
// HasEdgeBetween is already tested above.
lit := g.Lines(x.ID(), y.ID())
if !isValidIterator(lit) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, lit)
continue
}
checkEmptyIterator(t, lit, useEmpty)
if between && lit.Len() == 0 {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
} else {
for lit.Next() {
l := lit.Line()
if l == nil || !hasEnds(x, y, l) {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
} else if reversedLine && (l.From().ID() != x.ID() || l.To().ID() != y.ID()) {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, x.ID(), y.ID(), l)
}
}
}
lit = g.LinesBetween(x.ID(), y.ID())
if !isValidIterator(lit) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, lit)
continue
}
checkEmptyIterator(t, lit, useEmpty)
if between && lit.Len() == 0 {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
} else {
for lit.Next() {
l := lit.Line()
if l == nil || !hasEnds(x, y, l) {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
} else if reversedLine && (l.From().ID() != x.ID() || l.To().ID() != y.ID()) {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, x.ID(), y.ID(), l)
}
}
}
}
switch g := g.(type) {
case graph.WeightedDirectedMultigraph:
u := x
v := y
lit := g.WeightedLines(u.ID(), v.ID())
if !isValidIterator(lit) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, lit)
continue
}
checkEmptyIterator(t, lit, useEmpty)
if has := lit != graph.Empty; has != want[edge{f: u.ID(), t: v.ID()}] {
if has {
t.Errorf("unexpected edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
} else {
t.Errorf("missing edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
}
continue
}
for lit.Next() {
l := lit.WeightedLine()
if l.From().ID() != x.ID() || l.To().ID() != y.ID() {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, x.ID(), y.ID(), l)
}
}
// Edge has already been tested above.
if g.Node(u.ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, u.ID())
}
if g.Node(v.ID()) == nil {
t.Errorf("missing to node for test %q: %v", test.name, v.ID())
}
case graph.WeightedUndirectedMultigraph:
// HasEdgeBetween is already tested above.
lit := g.WeightedLines(x.ID(), y.ID())
if !isValidIterator(lit) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, lit)
continue
}
checkEmptyIterator(t, lit, useEmpty)
if between && lit.Len() == 0 {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
} else {
for lit.Next() {
l := lit.WeightedLine()
if reversedLine && (l.From().ID() != x.ID() || l.To().ID() != y.ID()) {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, x.ID(), y.ID(), l)
}
}
}
lit = g.WeightedLinesBetween(x.ID(), y.ID())
if !isValidIterator(lit) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, lit)
continue
}
checkEmptyIterator(t, lit, useEmpty)
if between && lit.Len() == 0 {
t.Errorf("missing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
} else {
for lit.Next() {
l := lit.WeightedLine()
if reversedLine && (l.From().ID() != x.ID() || l.To().ID() != y.ID()) {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, x.ID(), y.ID(), l)
}
}
}
}
}
}
default:
t.Errorf("invalid type for test: %T not a multigraph", g)
continue
}
}
}
// ReturnAdjacentNodes tests the constructed graph for the ability to correctly
// return the nodes reachable from each node within the graph. This is a check
// of the From method of graph.Graph and the To method of graph.Directed.
// ReturnAdjacentNodes also checks that the nodes and traversed edges exist
// within the graph, checking the Node, Edge, EdgeBetween and HasEdgeBetween
// methods of graph.Graph, the EdgeBetween method of graph.Undirected and the
// HasEdgeFromTo method of graph.Directed.
// If useEmpty is true, graph iterators will be checked for the use of
// graph.Empty if they are empty. If reversedEdge is true, edges will be checked
// to make sure edges returned match the orientation of an Edge or WeightedEdge
// call.
func ReturnAdjacentNodes(t *testing.T, b Builder, useEmpty, reversedEdge bool) {
for _, test := range testCases {
g, nodes, edges, _, _, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
want := make(map[edge]bool)
for _, e := range edges {
want[edge{f: e.From().ID(), t: e.To().ID()}] = true
if g.From(e.From().ID()).Len() == 0 {
t.Errorf("missing path from node %v with outbound edge %v", e.From().ID(), e)
}
}
for _, x := range nodes {
switch g := g.(type) {
case graph.Directed:
// Test forward.
u := x
it := g.From(u.ID())
if !isValidIterator(it) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, it)
continue
}
checkEmptyIterator(t, it, useEmpty)
for i := 0; it.Next(); i++ {
v := it.Node()
if i == 0 && g.Node(u.ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, u.ID())
}
if g.Node(v.ID()) == nil {
t.Errorf("missing to node for test %q: %v", test.name, v.ID())
}
qe := g.Edge(u.ID(), v.ID())
if qe == nil {
t.Errorf("missing from edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
} else if qe.From().ID() != u.ID() || qe.To().ID() != v.ID() {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, u.ID(), v.ID(), qe)
}
if !g.HasEdgeBetween(u.ID(), v.ID()) {
t.Errorf("missing from edge for test %q: (%v)--(%v)", test.name, u.ID(), v.ID())
}
if !g.HasEdgeFromTo(u.ID(), v.ID()) {
t.Errorf("missing from edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
}
if !want[edge{f: u.ID(), t: v.ID()}] {
t.Errorf("unexpected edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
}
}
// Test backward.
v := x
it = g.To(v.ID())
if !isValidIterator(it) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, it)
continue
}
checkEmptyIterator(t, it, useEmpty)
for i := 0; it.Next(); i++ {
u := it.Node()
if i == 0 && g.Node(v.ID()) == nil {
t.Errorf("missing to node for test %q: %v", test.name, v.ID())
}
if g.Node(u.ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, u.ID())
}
qe := g.Edge(u.ID(), v.ID())
if qe == nil {
t.Errorf("missing from edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
continue
}
if qe.From().ID() != u.ID() || qe.To().ID() != v.ID() {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, u.ID(), v.ID(), qe)
}
if !g.HasEdgeBetween(u.ID(), v.ID()) {
t.Errorf("missing from edge for test %q: (%v)--(%v)", test.name, u.ID(), v.ID())
continue
}
if !g.HasEdgeFromTo(u.ID(), v.ID()) {
t.Errorf("missing from edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
continue
}
if !want[edge{f: u.ID(), t: v.ID()}] {
t.Errorf("unexpected edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
}
}
for _, e := range edges {
if g.To(e.To().ID()).Len() == 0 {
t.Errorf("missing path to node %v with inbound edge %v", e.To().ID(), e)
}
}
case graph.Undirected:
u := x
it := g.From(u.ID())
if !isValidIterator(it) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, it)
continue
}
checkEmptyIterator(t, it, useEmpty)
for i := 0; it.Next(); i++ {
v := it.Node()
if i == 0 && g.Node(u.ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, u.ID())
}
qe := g.Edge(u.ID(), v.ID())
if qe == nil || !hasEnds(u, v, qe) {
t.Errorf("missing from edge for test %q: (%v)--(%v)", test.name, u.ID(), v.ID())
continue
}
if reversedEdge && (qe.From().ID() != u.ID() || qe.To().ID() != v.ID()) {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, u.ID(), v.ID(), qe)
}
qe = g.EdgeBetween(u.ID(), v.ID())
if qe == nil || !hasEnds(u, v, qe) {
t.Errorf("missing from edge for test %q: (%v)--(%v)", test.name, u.ID(), v.ID())
continue
}
if reversedEdge && (qe.From().ID() != u.ID() || qe.To().ID() != v.ID()) {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, u.ID(), v.ID(), qe)
}
if !g.HasEdgeBetween(u.ID(), v.ID()) {
t.Errorf("missing from edge for test %q: (%v)--(%v)", test.name, u.ID(), v.ID())
continue
}
between := want[edge{f: u.ID(), t: v.ID()}] || want[edge{f: v.ID(), t: u.ID()}]
if !between {
t.Errorf("unexpected edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
}
}
default:
u := x
it := g.From(u.ID())
if !isValidIterator(it) {
t.Errorf("invalid iterator for test %q: got:%#v", test.name, it)
continue
}
checkEmptyIterator(t, it, useEmpty)
for i := 0; it.Next(); i++ {
v := it.Node()
if i == 0 && g.Node(u.ID()) == nil {
t.Errorf("missing from node for test %q: %v", test.name, u.ID())
}
qe := g.Edge(u.ID(), v.ID())
if qe == nil {
t.Errorf("missing from edge for test %q: (%v)--(%v)", test.name, u.ID(), v.ID())
continue
}
if qe.From().ID() != u.ID() || qe.To().ID() != v.ID() {
t.Errorf("inverted edge for test %q query with F=%d T=%d: got:%#v",
test.name, u.ID(), v.ID(), qe)
}
if !g.HasEdgeBetween(u.ID(), v.ID()) {
t.Errorf("missing from edge for test %q: (%v)--(%v)", test.name, u.ID(), v.ID())
continue
}
between := want[edge{f: u.ID(), t: v.ID()}] || want[edge{f: v.ID(), t: u.ID()}]
if !between {
t.Errorf("unexpected edge for test %q: (%v)->(%v)", test.name, u.ID(), v.ID())
}
}
}
}
}
}
// Weight tests the constructed graph for the ability to correctly return
// the weight between to nodes, checking the Weight method of graph.Weighted.
//
// The self and absent values returned by the Builder should match the values
// used by the Weight method.
func Weight(t *testing.T, b Builder) {
for _, test := range testCases {
g, nodes, _, self, absent, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
wg, ok := g.(graph.Weighted)
if !ok {
t.Errorf("invalid graph type for test %q: %T is not graph.Weighted", test.name, g)
}
_, multi := g.(graph.Multigraph)
for _, x := range nodes {
for _, y := range nodes {
w, ok := wg.Weight(x.ID(), y.ID())
e := wg.WeightedEdge(x.ID(), y.ID())
switch {
case !ok:
if e != nil {
t.Errorf("missing edge weight for existing edge for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
}
if !scalar.Same(w, absent) {
t.Errorf("unexpected absent weight for test %q: got:%v want:%v", test.name, w, absent)
}
case !multi && x.ID() == y.ID():
if !scalar.Same(w, self) {
t.Errorf("unexpected self weight for test %q: got:%v want:%v", test.name, w, self)
}
case e == nil:
t.Errorf("missing edge for existing non-self weight for test %q: (%v)--(%v)", test.name, x.ID(), y.ID())
case e.Weight() != w:
t.Errorf("weight mismatch for test %q: edge=%v graph=%v", test.name, e.Weight(), w)
}
}
}
}
}
// AdjacencyMatrix tests the constructed graph for the ability to correctly
// return an adjacency matrix that matches the weights returned by the graphs
// Weight method.
//
// The self and absent values returned by the Builder should match the values
// used by the Weight method.
func AdjacencyMatrix(t *testing.T, b Builder) {
for _, test := range testCases {
g, nodes, _, self, absent, ok := b(test.nodes, test.edges, test.self, test.absent)
if !ok {
t.Logf("skipping test case: %q", test.name)
continue
}
wg, ok := g.(graph.Weighted)
if !ok {
t.Errorf("invalid graph type for test %q: %T is not graph.Weighted", test.name, g)
}
mg, ok := g.(matrixer)
if !ok {
t.Errorf("invalid graph type for test %q: %T cannot return adjacency matrix", test.name, g)
}
m := mg.Matrix()
r, c := m.Dims()
if r != c || r != len(nodes) {
t.Errorf("dimension mismatch for test %q: r=%d c=%d order=%d", test.name, r, c, len(nodes))
}
for _, x := range nodes {
i := int(x.ID())
for _, y := range nodes {
j := int(y.ID())
w, ok := wg.Weight(x.ID(), y.ID())
switch {
case !ok:
if !scalar.Same(m.At(i, j), absent) {
t.Errorf("weight mismatch for test %q: (%v)--(%v) matrix=%v graph=%v", test.name, x.ID(), y.ID(), m.At(i, j), w)
}
case x.ID() == y.ID():
if !scalar.Same(m.At(i, j), self) {
t.Errorf("weight mismatch for test %q: (%v)--(%v) matrix=%v graph=%v", test.name, x.ID(), y.ID(), m.At(i, j), w)
}
default:
if !scalar.Same(m.At(i, j), w) {
t.Errorf("weight mismatch for test %q: (%v)--(%v) matrix=%v graph=%v", test.name, x.ID(), y.ID(), m.At(i, j), w)
}
}
}
}
}
}
// sortLexicalEdges sorts a collection of edges lexically on the
// keys: from.ID > to.ID > [line.ID] > [weight].
func sortLexicalEdges(edges []Edge) {
slices.SortFunc(edges, func(a, b Edge) int {
if n := cmp.Compare(a.From().ID(), b.From().ID()); n != 0 {
return n
}
if n := cmp.Compare(a.To().ID(), b.To().ID()); n != 0 {
return n
}
la, oka := a.(graph.Line)
lb, okb := b.(graph.Line)
if oka != okb {
panic(fmt.Sprintf("testgraph: mismatched types %T != %T", a, b))
}
if oka {
if n := cmp.Compare(la.ID(), lb.ID()); n != 0 {
return n
}
}
return cmpWeight(a, b)
})
}
// sortLexicalUndirectedEdges sorts a collection of edges lexically on the
// keys: lo.ID > hi.ID > [line.ID] > [weight].
func sortLexicalUndirectedEdges(edges []Edge) {
slices.SortFunc(edges, func(a, b Edge) int {
lida, hida, _ := undirectedIDs(a)
lidb, hidb, _ := undirectedIDs(b)
if n := cmp.Compare(lida, lidb); n != 0 {
return n
}
if n := cmp.Compare(hida, hidb); n != 0 {
return n
}
la, oka := a.(graph.Line)
lb, okb := b.(graph.Line)
if oka != okb {
panic(fmt.Sprintf("testgraph: mismatched types %T != %T", a, b))
}
if oka {
if n := cmp.Compare(la.ID(), lb.ID()); n != 0 {
return n
}
}
return cmpWeight(a, b)
})
}
func cmpWeight(a, b Edge) int {
wea, oka := a.(graph.WeightedEdge)
web, okb := b.(graph.WeightedEdge)
if oka != okb {
panic(fmt.Sprintf("testgraph: mismatched types %T != %T", a, b))
}
if !oka {
return 0
}
return cmp.Compare(wea.Weight(), web.Weight())
}
// undirectedEdgeSetEqual returned whether a pair of undirected edge
// slices sorted by lexicalUndirectedEdges are equal.
func undirectedEdgeSetEqual(a, b []Edge) bool {
if len(a) == 0 && len(b) == 0 {
return true
}
if len(a) == 0 || len(b) == 0 {
return false
}
if !undirectedEdgeEqual(a[0], b[0]) {
return false
}
i, j := 0, 0
for {
switch {
case i == len(a)-1 && j == len(b)-1:
return true
case i < len(a)-1 && undirectedEdgeEqual(a[i+1], b[j]):
i++
case j < len(b)-1 && undirectedEdgeEqual(a[i], b[j+1]):
j++
case i < len(a)-1 && j < len(b)-1 && undirectedEdgeEqual(a[i+1], b[j+1]):
i++
j++
default:
return false
}
}
}
// undirectedEdgeEqual returns whether a pair of undirected edges are equal
// after canonicalising from and to IDs by numerical sort order.
func undirectedEdgeEqual(a, b Edge) bool {
loa, hia, inva := undirectedIDs(a)
lob, hib, invb := undirectedIDs(b)
// Use reflect.DeepEqual if the edges are parallel
// rather anti-parallel.
if inva == invb {
return reflect.DeepEqual(a, b)
}
if loa != lob || hia != hib {
return false
}
la, oka := a.(graph.Line)
lb, okb := b.(graph.Line)
if !oka && !okb {
return true
}
if la.ID() != lb.ID() {
return false
}
wea, oka := a.(graph.WeightedEdge)
web, okb := b.(graph.WeightedEdge)
if !oka && !okb {
return true
}
return wea.Weight() == web.Weight()
}
// NodeAdder is a graph.NodeAdder graph.
type NodeAdder interface {
graph.Graph
graph.NodeAdder
}
// AddNodes tests whether g correctly implements the graph.NodeAdder interface.
// AddNodes gets a new node from g and adds it to the graph, repeating this pair
// of operations n times. The existence of added nodes is confirmed in the graph.
// AddNodes also checks that re-adding each of the added nodes causes a panic.
// If g satisfies NodeWithIDer, the NodeWithID method is tested for an additional
// n rounds of node addition using NodeWithID to create new nodes as well as
// confirming that NodeWithID returns existing nodes.
func AddNodes(t *testing.T, g NodeAdder, n int) {
defer func() {
r := recover()
if r != nil {
t.Errorf("unexpected panic: %v", r)
}
}()
var addedNodes []graph.Node
for i := 0; i < n; i++ {
node := g.NewNode()
prev := len(graph.NodesOf(g.Nodes()))
if g.Node(node.ID()) != nil {
curr := g.Nodes().Len()
if curr != prev {
t.Fatalf("NewNode mutated graph: prev graph order != curr graph order, %d != %d", prev, curr)
}
t.Fatalf("NewNode returned existing: %#v", node)
}
g.AddNode(node)
addedNodes = append(addedNodes, node)
curr := len(graph.NodesOf(g.Nodes()))
if curr != prev+1 {
t.Fatalf("AddNode failed to mutate graph: curr graph order != prev graph order+1, %d != %d", curr, prev+1)
}
if g.Node(node.ID()) == nil {
t.Fatalf("AddNode failed to add node to graph trying to add %#v", node)
}
}
order.ByID(addedNodes)
graphNodes := graph.NodesOf(g.Nodes())
order.ByID(graphNodes)
if !reflect.DeepEqual(addedNodes, graphNodes) {
if n > 20 {
t.Errorf("unexpected node set after node addition: got len:%v want len:%v", len(graphNodes), len(addedNodes))
} else {
t.Errorf("unexpected node set after node addition: got:\n %v\nwant:\n%v", graphNodes, addedNodes)
}
}
it := g.Nodes()
for it.Next() {
panicked := panics(func() {
g.AddNode(it.Node())
})
if !panicked {
t.Fatalf("expected panic adding existing node: %v", it.Node())
}
}
if gwi, ok := g.(graph.NodeWithIDer); ok {
// Test existing nodes.
it := g.Nodes()
for it.Next() {
id := it.Node().ID()
n, new := gwi.NodeWithID(id)
if n == nil {
t.Errorf("unexpected nil node for existing node with ID=%d", id)
}
if new {
t.Errorf("unexpected new node for existing node with ID=%d", id)
}
}
// Run n rounds of ID-specified node addition.
for i := 0; i < n; i++ {
id := g.NewNode().ID() // Get a guaranteed non-existing node.
n, new := gwi.NodeWithID(id)
if n == nil {
// Could not create a node, valid behaviour.
continue
}
if !new {
t.Errorf("unexpected old node for non-existing node with ID=%d", id)
}
g.AddNode(n) // Use the node to advance to a new non-existing node.
}
}
}
// AddArbitraryNodes tests whether g correctly implements the AddNode method. Not all
// graph.NodeAdder graphs are expected to implement the semantics of this test.
// AddArbitraryNodes iterates over add, adding each node to the graph. The existence
// of each added node in the graph is confirmed.
func AddArbitraryNodes(t *testing.T, g NodeAdder, add graph.Nodes) {
defer func() {
r := recover()
if r != nil {
t.Errorf("unexpected panic: %v", r)
}
}()
for add.Next() {
node := add.Node()
prev := len(graph.NodesOf(g.Nodes()))
g.AddNode(node)
curr := len(graph.NodesOf(g.Nodes()))
if curr != prev+1 {
t.Fatalf("AddNode failed to mutate graph: curr graph order != prev graph order+1, %d != %d", curr, prev+1)
}
if g.Node(node.ID()) == nil {
t.Fatalf("AddNode failed to add node to graph trying to add %#v", node)
}
}
add.Reset()
addedNodes := graph.NodesOf(add)
order.ByID(addedNodes)
graphNodes := graph.NodesOf(g.Nodes())
order.ByID(graphNodes)
if !reflect.DeepEqual(addedNodes, graphNodes) {
t.Errorf("unexpected node set after node addition: got:\n %v\nwant:\n%v", graphNodes, addedNodes)
}
it := g.Nodes()
for it.Next() {
panicked := panics(func() {
g.AddNode(it.Node())
})
if !panicked {
t.Fatalf("expected panic adding existing node: %v", it.Node())
}
}
}
// NodeRemover is a graph.NodeRemover graph.
type NodeRemover interface {
graph.Graph
graph.NodeRemover
}
// RemoveNodes tests whether g correctly implements the graph.NodeRemover interface.
// The input graph g must contain a set of nodes with some edges between them.
func RemoveNodes(t *testing.T, g NodeRemover) {
defer func() {
r := recover()
if r != nil {
t.Errorf("unexpected panic: %v", r)
}
}()
it := g.Nodes()
first := true
for it.Next() {
u := it.Node()
seen := make(map[edge]struct{})
// Collect all incident edges.
var incident []graph.Edge
to := g.From(u.ID())
for to.Next() {
v := to.Node()
e := g.Edge(u.ID(), v.ID())
if e == nil {
t.Fatalf("bad graph: neighbors not connected: u=%#v v=%#v", u, v)
}
if _, ok := g.(graph.Undirected); ok {
seen[edge{f: e.To().ID(), t: e.From().ID()}] = struct{}{}
}
seen[edge{f: e.From().ID(), t: e.To().ID()}] = struct{}{}
incident = append(incident, e)
}
// Collect all other edges.
var others []graph.Edge
currit := g.Nodes()
for currit.Next() {
u := currit.Node()
to := g.From(u.ID())
for to.Next() {
v := to.Node()
e := g.Edge(u.ID(), v.ID())
if e == nil {
t.Fatalf("bad graph: neighbors not connected: u=%#v v=%#v", u, v)
}
seen[edge{f: e.From().ID(), t: e.To().ID()}] = struct{}{}
others = append(others, e)
}
}
if first && len(seen) == 0 {
t.Fatal("incomplete test: no edges in graph")
}
first = false
prev := len(graph.NodesOf(g.Nodes()))
g.RemoveNode(u.ID())
curr := len(graph.NodesOf(g.Nodes()))
if curr != prev-1 {
t.Fatalf("RemoveNode failed to mutate graph: curr graph order != prev graph order-1, %d != %d", curr, prev-1)
}
if g.Node(u.ID()) != nil {
t.Fatalf("failed to remove node: %#v", u)
}
for _, e := range incident {
if g.HasEdgeBetween(e.From().ID(), e.To().ID()) {
t.Fatalf("RemoveNode failed to remove connected edge: %#v", e)
}
}
for _, e := range others {
if e.From().ID() == u.ID() || e.To().ID() == u.ID() {
continue
}
if g.Edge(e.From().ID(), e.To().ID()) == nil {
t.Fatalf("RemoveNode %v removed unconnected edge: %#v", u, e)
}
}
}
}
// EdgeAdder is a graph.EdgeAdder graph.
type EdgeAdder interface {
graph.Graph
graph.EdgeAdder
}
// AddEdges tests whether g correctly implements the graph.EdgeAdder interface.
// AddEdges creates n pairs of nodes with random IDs in [0,n) and joins edges
// each node in the pair using SetEdge. AddEdges confirms that the end point
// nodes are added to the graph and that the edges are stored in the graph.
// If canLoop is true, self edges may be created. If canSet is true, a second
// call to SetEdge is made for each edge to confirm that the nodes corresponding
// the end points are updated.
func AddEdges(t *testing.T, n int, g EdgeAdder, newNode func(id int64) graph.Node, canLoop, canSetNode bool) {
defer func() {
r := recover()
if r != nil {
t.Errorf("unexpected panic: %v", r)
}
}()
type altNode struct {
graph.Node
}
rnd := rand.New(rand.NewSource(1))
for i := 0; i < n; i++ {
u := newNode(rnd.Int63n(int64(n)))
var v graph.Node
for {
v = newNode(rnd.Int63n(int64(n)))
if canLoop || u.ID() != v.ID() {
break
}
}
e := g.NewEdge(u, v)
if g.Edge(u.ID(), v.ID()) != nil {
t.Fatalf("NewEdge returned existing: %#v", e)
}
g.SetEdge(e)
if g.Edge(u.ID(), v.ID()) == nil {
t.Fatalf("SetEdge failed to add edge: %#v", e)
}
if g.Node(u.ID()) == nil {
t.Fatalf("SetEdge failed to add from node: %#v", u)
}
if g.Node(v.ID()) == nil {
t.Fatalf("SetEdge failed to add to node: %#v", v)
}
if !canSetNode {
continue
}
g.SetEdge(g.NewEdge(altNode{u}, altNode{v}))
if nu := g.Node(u.ID()); nu == u {
t.Fatalf("SetEdge failed to update from node: u=%#v nu=%#v", u, nu)
}
if nv := g.Node(v.ID()); nv == v {
t.Fatalf("SetEdge failed to update to node: v=%#v nv=%#v", v, nv)
}
}
}
// WeightedEdgeAdder is a graph.EdgeAdder graph.
type WeightedEdgeAdder interface {
graph.Graph
graph.WeightedEdgeAdder
}
// AddWeightedEdges tests whether g correctly implements the graph.WeightedEdgeAdder
// interface. AddWeightedEdges creates n pairs of nodes with random IDs in [0,n) and
// joins edges each node in the pair using SetWeightedEdge with weight w.
// AddWeightedEdges confirms that the end point nodes are added to the graph and that
// the edges are stored in the graph. If canLoop is true, self edges may be created.
// If canSet is true, a second call to SetWeightedEdge is made for each edge to
// confirm that the nodes corresponding the end points are updated.
func AddWeightedEdges(t *testing.T, n int, g WeightedEdgeAdder, w float64, newNode func(id int64) graph.Node, canLoop, canSetNode bool) {
defer func() {
r := recover()
if r != nil {
t.Errorf("unexpected panic: %v", r)
}
}()
type altNode struct {
graph.Node
}
rnd := rand.New(rand.NewSource(1))
for i := 0; i < n; i++ {
u := newNode(rnd.Int63n(int64(n)))
var v graph.Node
for {
v = newNode(rnd.Int63n(int64(n)))
if canLoop || u.ID() != v.ID() {
break
}
}
e := g.NewWeightedEdge(u, v, w)
if g.Edge(u.ID(), v.ID()) != nil {
t.Fatalf("NewEdge returned existing: %#v", e)
}
g.SetWeightedEdge(e)
ne := g.Edge(u.ID(), v.ID())
if ne == nil {
t.Fatalf("SetWeightedEdge failed to add edge: %#v", e)
}
we, ok := ne.(graph.WeightedEdge)
if !ok {
t.Fatalf("SetWeightedEdge failed to add weighted edge: %#v", e)
}
if we.Weight() != w {
t.Fatalf("edge weight mismatch: got:%f want:%f", we.Weight(), w)
}
if g.Node(u.ID()) == nil {
t.Fatalf("SetWeightedEdge failed to add from node: %#v", u)
}
if g.Node(v.ID()) == nil {
t.Fatalf("SetWeightedEdge failed to add to node: %#v", v)
}
if !canSetNode {
continue
}
g.SetWeightedEdge(g.NewWeightedEdge(altNode{u}, altNode{v}, w))
if nu := g.Node(u.ID()); nu == u {
t.Fatalf("SetWeightedEdge failed to update from node: u=%#v nu=%#v", u, nu)
}
if nv := g.Node(v.ID()); nv == v {
t.Fatalf("SetWeightedEdge failed to update to node: v=%#v nv=%#v", v, nv)
}
}
}
// NoLoopAddEdges tests whether g panics for self-loop addition. NoLoopAddEdges
// adds n nodes with IDs in [0,n) and creates an edge from the graph with NewEdge.
// NoLoopAddEdges confirms that this does not panic and then adds the edge to the
// graph to ensure that SetEdge will panic when adding a self-loop.
func NoLoopAddEdges(t *testing.T, n int, g EdgeAdder, newNode func(id int64) graph.Node) {
defer func() {
r := recover()
if r != nil {
t.Errorf("unexpected panic: %v", r)
}
}()
for id := 0; id < n; id++ {
node := newNode(int64(id))
e := g.NewEdge(node, node)
panicked := panics(func() {
g.SetEdge(e)
})
if !panicked {
t.Errorf("expected panic for self-edge: %#v", e)
}
}
}
// NoLoopAddWeightedEdges tests whether g panics for self-loop addition. NoLoopAddWeightedEdges
// adds n nodes with IDs in [0,n) and creates an edge from the graph with NewWeightedEdge.
// NoLoopAddWeightedEdges confirms that this does not panic and then adds the edge to the
// graph to ensure that SetWeightedEdge will panic when adding a self-loop.
func NoLoopAddWeightedEdges(t *testing.T, n int, g WeightedEdgeAdder, w float64, newNode func(id int64) graph.Node) {
defer func() {
r := recover()
if r != nil {
t.Errorf("unexpected panic: %v", r)
}
}()
for id := 0; id < n; id++ {
node := newNode(int64(id))
e := g.NewWeightedEdge(node, node, w)
panicked := panics(func() {
g.SetWeightedEdge(e)
})
if !panicked {
t.Errorf("expected panic for self-edge: %#v", e)
}
}
}
// LineAdder is a graph.LineAdder multigraph.
type LineAdder interface {
graph.Multigraph
graph.LineAdder
}
// AddLines tests whether g correctly implements the graph.LineAdder interface.
// AddLines creates n pairs of nodes with random IDs in [0,n) and joins edges
// each node in the pair using SetLine. AddLines confirms that the end point
// nodes are added to the graph and that the edges are stored in the graph.
// If canSet is true, a second call to SetLine is made for each edge to confirm
// that the nodes corresponding the end points are updated.
func AddLines(t *testing.T, n int, g LineAdder, newNode func(id int64) graph.Node, canSetNode bool) {
defer func() {
r := recover()
if r != nil {
t.Errorf("unexpected panic: %v", r)
}
}()
type altNode struct {
graph.Node
}
rnd := rand.New(rand.NewSource(1))
seen := make(tripleInt64s)
for i := 0; i < n; i++ {
u := newNode(rnd.Int63n(int64(n)))
v := newNode(rnd.Int63n(int64(n)))
prev := g.Lines(u.ID(), v.ID())
l := g.NewLine(u, v)
if seen.has(u.ID(), v.ID(), l.ID()) {
t.Fatalf("NewLine returned an existing line: %#v", l)
}
if g.Lines(u.ID(), v.ID()).Len() != prev.Len() {
t.Fatalf("NewLine added a line: %#v", l)
}
g.SetLine(l)
seen.add(u.ID(), v.ID(), l.ID())
if g.Lines(u.ID(), v.ID()).Len() != prev.Len()+1 {
t.Fatalf("SetLine failed to add line: %#v", l)
}
if g.Node(u.ID()) == nil {
t.Fatalf("SetLine failed to add from node: %#v", u)
}
if g.Node(v.ID()) == nil {
t.Fatalf("SetLine failed to add to node: %#v", v)
}
if !canSetNode {
continue
}
g.SetLine(g.NewLine(altNode{u}, altNode{v}))
if nu := g.Node(u.ID()); nu == u {
t.Fatalf("SetLine failed to update from node: u=%#v nu=%#v", u, nu)
}
if nv := g.Node(v.ID()); nv == v {
t.Fatalf("SetLine failed to update to node: v=%#v nv=%#v", v, nv)
}
}
}
// WeightedLineAdder is a graph.WeightedLineAdder multigraph.
type WeightedLineAdder interface {
graph.Multigraph
graph.WeightedLineAdder
}
// AddWeightedLines tests whether g correctly implements the graph.WeightedEdgeAdder
// interface. AddWeightedLines creates n pairs of nodes with random IDs in [0,n) and
// joins edges each node in the pair using SetWeightedLine with weight w.
// AddWeightedLines confirms that the end point nodes are added to the graph and that
// the edges are stored in the graph. If canSet is true, a second call to SetWeightedLine
// is made for each edge to confirm that the nodes corresponding the end points are
// updated.
func AddWeightedLines(t *testing.T, n int, g WeightedLineAdder, w float64, newNode func(id int64) graph.Node, canSetNode bool) {
defer func() {
r := recover()
if r != nil {
t.Errorf("unexpected panic: %v", r)
}
}()
type altNode struct {
graph.Node
}
rnd := rand.New(rand.NewSource(1))
seen := make(tripleInt64s)
for i := 0; i < n; i++ {
u := newNode(rnd.Int63n(int64(n)))
v := newNode(rnd.Int63n(int64(n)))
prev := g.Lines(u.ID(), v.ID())
l := g.NewWeightedLine(u, v, w)
if seen.has(u.ID(), v.ID(), l.ID()) {
t.Fatalf("NewWeightedLine returned an existing line: %#v", l)
}
if g.Lines(u.ID(), v.ID()).Len() != prev.Len() {
t.Fatalf("NewWeightedLine added a line: %#v", l)
}
g.SetWeightedLine(l)
seen.add(u.ID(), v.ID(), l.ID())
curr := g.Lines(u.ID(), v.ID())
if curr.Len() != prev.Len()+1 {
t.Fatalf("SetWeightedLine failed to add line: %#v", l)
}
var found bool
for curr.Next() {
if curr.Line().ID() == l.ID() {
found = true
wl, ok := curr.Line().(graph.WeightedLine)
if !ok {
t.Fatalf("SetWeightedLine failed to add weighted line: %#v", l)
}
if wl.Weight() != w {
t.Fatalf("line weight mismatch: got:%f want:%f", wl.Weight(), w)
}
break
}
}
if !found {
t.Fatalf("SetWeightedLine failed to add line: %#v", l)
}
if g.Node(u.ID()) == nil {
t.Fatalf("SetWeightedLine failed to add from node: %#v", u)
}
if g.Node(v.ID()) == nil {
t.Fatalf("SetWeightedLine failed to add to node: %#v", v)
}
if !canSetNode {
continue
}
g.SetWeightedLine(g.NewWeightedLine(altNode{u}, altNode{v}, w))
if nu := g.Node(u.ID()); nu == u {
t.Fatalf("SetWeightedLine failed to update from node: u=%#v nu=%#v", u, nu)
}
if nv := g.Node(v.ID()); nv == v {
t.Fatalf("SetWeightedLine failed to update to node: v=%#v nv=%#v", v, nv)
}
}
}
// EdgeRemover is a graph.EdgeRemover graph.
type EdgeRemover interface {
graph.Graph
graph.EdgeRemover
}
// RemoveEdges tests whether g correctly implements the graph.EdgeRemover interface.
// The input graph g must contain a set of nodes with some edges between them.
// RemoveEdges iterates over remove, which must contain edges in g, removing each
// edge. RemoveEdges confirms that the edge is removed, leaving its end-point nodes
// and all other edges in the graph.
func RemoveEdges(t *testing.T, g EdgeRemover, remove graph.Edges) {
edges := make(map[edge]struct{})
nodes := g.Nodes()
for nodes.Next() {
u := nodes.Node()
uid := u.ID()
to := g.From(uid)
for to.Next() {
v := to.Node()
edges[edge{f: u.ID(), t: v.ID()}] = struct{}{}
}
}
for remove.Next() {
e := remove.Edge()
if g.Edge(e.From().ID(), e.To().ID()) == nil {
t.Fatalf("bad tests: missing edge: %#v", e)
}
if g.Node(e.From().ID()) == nil {
t.Fatalf("bad tests: missing from node: %#v", e.From())
}
if g.Node(e.To().ID()) == nil {
t.Fatalf("bad tests: missing to node: %#v", e.To())
}
g.RemoveEdge(e.From().ID(), e.To().ID())
if _, ok := g.(graph.Undirected); ok {
delete(edges, edge{f: e.To().ID(), t: e.From().ID()})
}
delete(edges, edge{f: e.From().ID(), t: e.To().ID()})
for ge := range edges {
if g.Edge(ge.f, ge.t) == nil {
t.Fatalf("unexpected missing edge after removing edge %#v: %#v", e, ge)
}
}
if ne := g.Edge(e.From().ID(), e.To().ID()); ne != nil {
t.Fatalf("expected nil edge: got:%#v", ne)
}
if g.Node(e.From().ID()) == nil {
t.Fatalf("unexpected deletion of from node: %#v", e.From())
}
if g.Node(e.To().ID()) == nil {
t.Fatalf("unexpected deletion to node: %#v", e.To())
}
}
}
// LineRemover is a graph.EdgeRemove graph.
type LineRemover interface {
graph.Multigraph
graph.LineRemover
}
// RemoveLines tests whether g correctly implements the graph.LineRemover interface.
// The input graph g must contain a set of nodes with some lines between them.
// RemoveLines iterates over remove, which must contain lines in g, removing each
// line. RemoveLines confirms that the line is removed, leaving its end-point nodes
// and all other lines in the graph.
func RemoveLines(t *testing.T, g LineRemover, remove graph.Lines) {
// lines is the set of lines in the graph.
// The presence of a key indicates that the
// line should exist in the graph. The value
// for each key is used to indicate whether
// it has been found during testing.
lines := make(map[edge]bool)
nodes := g.Nodes()
for nodes.Next() {
u := nodes.Node()
uid := u.ID()
to := g.From(uid)
for to.Next() {
v := to.Node()
lit := g.Lines(u.ID(), v.ID())
for lit.Next() {
lines[edge{f: u.ID(), t: v.ID(), id: lit.Line().ID()}] = true
}
}
}
for remove.Next() {
l := remove.Line()
if g.Lines(l.From().ID(), l.To().ID()) == graph.Empty {
t.Fatalf("bad tests: missing line: %#v", l)
}
if g.Node(l.From().ID()) == nil {
t.Fatalf("bad tests: missing from node: %#v", l.From())
}
if g.Node(l.To().ID()) == nil {
t.Fatalf("bad tests: missing to node: %#v", l.To())
}
prev := g.Lines(l.From().ID(), l.To().ID())
g.RemoveLine(l.From().ID(), l.To().ID(), l.ID())
if _, ok := g.(graph.Undirected); ok {
delete(lines, edge{f: l.To().ID(), t: l.From().ID(), id: l.ID()})
}
delete(lines, edge{f: l.From().ID(), t: l.To().ID(), id: l.ID()})
// Mark all lines as not found.
for gl := range lines {
lines[gl] = false
}
// Mark found lines. This could be done far more efficiently.
for gl := range lines {
lit := g.Lines(gl.f, gl.t)
for lit.Next() {
lid := lit.Line().ID()
if lid == gl.id {
lines[gl] = true
break
}
}
}
for gl, found := range lines {
if !found {
t.Fatalf("unexpected missing line after removing line %#v: %#v", l, gl)
}
}
if curr := g.Lines(l.From().ID(), l.To().ID()); curr.Len() != prev.Len()-1 {
t.Fatalf("RemoveLine failed to mutate graph: curr edge size != prev edge size-1, %d != %d", curr.Len(), prev.Len()-1)
}
if g.Node(l.From().ID()) == nil {
t.Fatalf("unexpected deletion of from node: %#v", l.From())
}
if g.Node(l.To().ID()) == nil {
t.Fatalf("unexpected deletion to node: %#v", l.To())
}
}
}
// undirectedIDs returns a numerical sort ordered canonicalisation of the
// IDs of e.
func undirectedIDs(e Edge) (lo, hi int64, inverted bool) {
lid := e.From().ID()
hid := e.To().ID()
if hid < lid {
inverted = true
hid, lid = lid, hid
}
return lid, hid, inverted
}
type edge struct {
f, t, id int64
}
func panics(fn func()) (ok bool) {
defer func() {
ok = recover() != nil
}()
fn()
return
}
// RandomNodes implements the graph.Nodes interface for a set of random nodes.
type RandomNodes struct {
n int
seed uint64
newNode func(int64) graph.Node
curr int64
state *rand.Rand
seen set.Ints[int64]
count int
}
var _ graph.Nodes = (*RandomNodes)(nil)
// NewRandomNodes returns a new implicit node iterator containing a set of n nodes
// with IDs generated from a PRNG seeded by the given seed.
// The provided new func maps the id to a graph.Node.
func NewRandomNodes(n int, seed uint64, new func(id int64) graph.Node) *RandomNodes {
return &RandomNodes{
n: n,
seed: seed,
newNode: new,
state: rand.New(rand.NewSource(seed)),
seen: make(set.Ints[int64]),
count: 0,
}
}
// Len returns the remaining number of nodes to be iterated over.
func (n *RandomNodes) Len() int {
return n.n - n.count
}
// Next returns whether the next call of Node will return a valid node.
func (n *RandomNodes) Next() bool {
if n.count >= n.n {
return false
}
n.count++
for {
sign := int64(1)
if n.state.Float64() < 0.5 {
sign *= -1
}
n.curr = sign * n.state.Int63()
if !n.seen.Has(n.curr) {
n.seen.Add(n.curr)
return true
}
}
}
// Node returns the current node of the iterator. Next must have been
// called prior to a call to Node.
func (n *RandomNodes) Node() graph.Node {
if n.Len() == -1 || n.count == 0 {
return nil
}
return n.newNode(n.curr)
}
// Reset returns the iterator to its initial state.
func (n *RandomNodes) Reset() {
n.state = rand.New(rand.NewSource(n.seed))
n.seen = make(set.Ints[int64])
n.count = 0
}
// tripleInt64s is a set of [3]int64 identifiers.
type tripleInt64s map[[3]int64]struct{}
// add inserts an element into the set.
func (s tripleInt64s) add(x, y, z int64) {
s[[3]int64{x, y, z}] = struct{}{}
}
// has reports the existence of the element in the set.
func (s tripleInt64s) has(x, y, z int64) bool {
_, ok := s[[3]int64{x, y, z}]
return ok
}
|