1 /* 2 * Copyright (C) 2014 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.graph; 18 19 import static com.google.common.graph.TestUtil.assertEdgeNotInGraphErrorMessage; 20 import static com.google.common.graph.TestUtil.assertNodeNotInGraphErrorMessage; 21 import static com.google.common.graph.TestUtil.assertStronglyEquivalent; 22 import static com.google.common.graph.TestUtil.sanityCheckSet; 23 import static com.google.common.truth.Truth.assertThat; 24 import static com.google.common.truth.TruthJUnit.assume; 25 import static java.util.concurrent.Executors.newFixedThreadPool; 26 import static org.junit.Assert.assertFalse; 27 import static org.junit.Assert.assertThrows; 28 import static org.junit.Assert.assertTrue; 29 import static org.junit.Assert.fail; 30 31 import com.google.common.collect.ImmutableList; 32 import com.google.common.collect.ImmutableSet; 33 import com.google.common.collect.Sets; 34 import java.util.Set; 35 import java.util.concurrent.Callable; 36 import java.util.concurrent.CyclicBarrier; 37 import java.util.concurrent.ExecutorService; 38 import java.util.concurrent.Future; 39 import org.checkerframework.checker.nullness.qual.Nullable; 40 import org.junit.After; 41 import org.junit.Before; 42 import org.junit.Test; 43 44 /** 45 * Abstract base class for testing implementations of {@link Network} interface. Network instances 46 * created for testing should have Integer node and String edge objects. 47 * 48 * <p>Test cases that should be handled similarly in any graph implementation are included in this 49 * class. For example, testing that {@code nodes()} method returns the set of the nodes in the 50 * graph. The following test cases are left for the subclasses to handle: 51 * 52 * <ul> 53 * <li>Test cases related to whether the graph is directed, undirected, mutable, or immutable. 54 * <li>Test cases related to the specific implementation of the {@link Network} interface. 55 * </ul> 56 * 57 * TODO(user): Make this class generic (using <N, E>) for all node and edge types. 58 * TODO(user): Differentiate between directed and undirected edge strings. 59 */ 60 public abstract class AbstractNetworkTest { 61 62 Network<Integer, String> network; 63 64 /** 65 * The same reference as {@link #network}, except as a mutable network. This field is null in case 66 * {@link #createGraph()} didn't return a mutable network. 67 */ 68 MutableNetwork<Integer, String> networkAsMutableNetwork; 69 70 static final Integer N1 = 1; 71 static final Integer N2 = 2; 72 static final Integer N3 = 3; 73 static final Integer N4 = 4; 74 static final Integer N5 = 5; 75 static final Integer NODE_NOT_IN_GRAPH = 1000; 76 77 static final String E11 = "1-1"; 78 static final String E11_A = "1-1a"; 79 static final String E12 = "1-2"; 80 static final String E12_A = "1-2a"; 81 static final String E12_B = "1-2b"; 82 static final String E21 = "2-1"; 83 static final String E13 = "1-3"; 84 static final String E14 = "1-4"; 85 static final String E23 = "2-3"; 86 static final String E31 = "3-1"; 87 static final String E34 = "3-4"; 88 static final String E41 = "4-1"; 89 static final String E15 = "1-5"; 90 static final String EDGE_NOT_IN_GRAPH = "edgeNotInGraph"; 91 92 // TODO(user): Consider separating Strings that we've defined here to capture 93 // identifiable substrings of expected error messages, from Strings that we've defined 94 // here to provide error messages. 95 // TODO(user): Some Strings used in the subclasses can be added as static Strings 96 // here too. 97 static final String ERROR_PARALLEL_EDGE = "connected by a different edge"; 98 static final String ERROR_REUSE_EDGE = "it cannot be reused to connect"; 99 static final String ERROR_MODIFIABLE_COLLECTION = 100 "Collection returned is unexpectedly modifiable"; 101 static final String ERROR_SELF_LOOP = "self-loops are not allowed"; 102 static final String ERROR_EDGE_NOT_IN_GRAPH = 103 "Should not be allowed to pass an edge that is not an element of the graph."; 104 static final String ERROR_ADDED_SELF_LOOP = "Should not be allowed to add a self-loop edge."; 105 static final String ERROR_ADDED_PARALLEL_EDGE = "Should not be allowed to add a parallel edge."; 106 static final String ERROR_ADDED_EXISTING_EDGE = 107 "Reusing an existing edge to connect different nodes succeeded"; 108 109 /** Creates and returns an instance of the graph to be tested. */ createGraph()110 abstract Network<Integer, String> createGraph(); 111 112 /** 113 * A proxy method that adds the node {@code n} to the graph being tested. In case of Immutable 114 * graph implementations, this method should replace {@link #network} with a new graph that 115 * includes this node. 116 */ addNode(Integer n)117 abstract void addNode(Integer n); 118 119 /** 120 * A proxy method that adds the edge {@code e} to the graph being tested. In case of Immutable 121 * graph implementations, this method should replace {@link #network} with a new graph that 122 * includes this edge. 123 */ addEdge(Integer n1, Integer n2, String e)124 abstract void addEdge(Integer n1, Integer n2, String e); 125 graphIsMutable()126 final boolean graphIsMutable() { 127 return networkAsMutableNetwork != null; 128 } 129 130 @Before init()131 public void init() { 132 network = createGraph(); 133 if (network instanceof MutableNetwork) { 134 networkAsMutableNetwork = (MutableNetwork<Integer, String>) network; 135 } 136 } 137 138 @After validateNetworkState()139 public void validateNetworkState() { 140 validateNetwork(network); 141 } 142 validateNetwork(Network<N, E> network)143 static <N, E> void validateNetwork(Network<N, E> network) { 144 assertStronglyEquivalent(network, Graphs.copyOf(network)); 145 assertStronglyEquivalent(network, ImmutableNetwork.copyOf(network)); 146 147 String networkString = network.toString(); 148 assertThat(networkString).contains("isDirected: " + network.isDirected()); 149 assertThat(networkString).contains("allowsParallelEdges: " + network.allowsParallelEdges()); 150 assertThat(networkString).contains("allowsSelfLoops: " + network.allowsSelfLoops()); 151 152 int nodeStart = networkString.indexOf("nodes:"); 153 int edgeStart = networkString.indexOf("edges:"); 154 String nodeString = networkString.substring(nodeStart, edgeStart); 155 String edgeString = networkString.substring(edgeStart); 156 157 Graph<N> asGraph = network.asGraph(); 158 AbstractGraphTest.validateGraph(asGraph); 159 assertThat(network.nodes()).isEqualTo(asGraph.nodes()); 160 assertThat(network.edges().size()).isAtLeast(asGraph.edges().size()); 161 assertThat(network.nodeOrder()).isEqualTo(asGraph.nodeOrder()); 162 assertThat(network.isDirected()).isEqualTo(asGraph.isDirected()); 163 assertThat(network.allowsSelfLoops()).isEqualTo(asGraph.allowsSelfLoops()); 164 165 for (E edge : sanityCheckSet(network.edges())) { 166 // TODO(b/27817069): Consider verifying the edge's incident nodes in the string. 167 assertThat(edgeString).contains(edge.toString()); 168 169 EndpointPair<N> endpointPair = network.incidentNodes(edge); 170 N nodeU = endpointPair.nodeU(); 171 N nodeV = endpointPair.nodeV(); 172 assertThat(asGraph.edges()).contains(EndpointPair.of(network, nodeU, nodeV)); 173 assertThat(network.edgesConnecting(nodeU, nodeV)).contains(edge); 174 assertThat(network.successors(nodeU)).contains(nodeV); 175 assertThat(network.adjacentNodes(nodeU)).contains(nodeV); 176 assertThat(network.outEdges(nodeU)).contains(edge); 177 assertThat(network.incidentEdges(nodeU)).contains(edge); 178 assertThat(network.predecessors(nodeV)).contains(nodeU); 179 assertThat(network.adjacentNodes(nodeV)).contains(nodeU); 180 assertThat(network.inEdges(nodeV)).contains(edge); 181 assertThat(network.incidentEdges(nodeV)).contains(edge); 182 183 for (N incidentNode : network.incidentNodes(edge)) { 184 assertThat(network.nodes()).contains(incidentNode); 185 for (E adjacentEdge : network.incidentEdges(incidentNode)) { 186 assertTrue( 187 edge.equals(adjacentEdge) || network.adjacentEdges(edge).contains(adjacentEdge)); 188 } 189 } 190 } 191 192 for (N node : sanityCheckSet(network.nodes())) { 193 assertThat(nodeString).contains(node.toString()); 194 195 assertThat(network.adjacentNodes(node)).isEqualTo(asGraph.adjacentNodes(node)); 196 assertThat(network.predecessors(node)).isEqualTo(asGraph.predecessors(node)); 197 assertThat(network.successors(node)).isEqualTo(asGraph.successors(node)); 198 199 int selfLoopCount = network.edgesConnecting(node, node).size(); 200 assertThat(network.incidentEdges(node).size() + selfLoopCount) 201 .isEqualTo(network.degree(node)); 202 203 if (network.isDirected()) { 204 assertThat(network.incidentEdges(node).size() + selfLoopCount) 205 .isEqualTo(network.inDegree(node) + network.outDegree(node)); 206 assertThat(network.inEdges(node)).hasSize(network.inDegree(node)); 207 assertThat(network.outEdges(node)).hasSize(network.outDegree(node)); 208 } else { 209 assertThat(network.predecessors(node)).isEqualTo(network.adjacentNodes(node)); 210 assertThat(network.successors(node)).isEqualTo(network.adjacentNodes(node)); 211 assertThat(network.inEdges(node)).isEqualTo(network.incidentEdges(node)); 212 assertThat(network.outEdges(node)).isEqualTo(network.incidentEdges(node)); 213 assertThat(network.inDegree(node)).isEqualTo(network.degree(node)); 214 assertThat(network.outDegree(node)).isEqualTo(network.degree(node)); 215 } 216 217 for (N otherNode : network.nodes()) { 218 Set<E> edgesConnecting = sanityCheckSet(network.edgesConnecting(node, otherNode)); 219 switch (edgesConnecting.size()) { 220 case 0: 221 assertThat(network.edgeConnectingOrNull(node, otherNode)).isNull(); 222 assertThat(network.hasEdgeConnecting(node, otherNode)).isFalse(); 223 break; 224 case 1: 225 assertThat(network.edgeConnectingOrNull(node, otherNode)) 226 .isEqualTo(edgesConnecting.iterator().next()); 227 assertThat(network.hasEdgeConnecting(node, otherNode)).isTrue(); 228 break; 229 default: 230 assertThat(network.hasEdgeConnecting(node, otherNode)).isTrue(); 231 try { 232 network.edgeConnectingOrNull(node, otherNode); 233 fail(); 234 } catch (IllegalArgumentException expected) { 235 } 236 } 237 238 boolean isSelfLoop = node.equals(otherNode); 239 boolean connected = !edgesConnecting.isEmpty(); 240 if (network.isDirected() || !isSelfLoop) { 241 assertThat(edgesConnecting) 242 .isEqualTo(Sets.intersection(network.outEdges(node), network.inEdges(otherNode))); 243 } 244 if (!network.allowsParallelEdges()) { 245 assertThat(edgesConnecting.size()).isAtMost(1); 246 } 247 if (!network.allowsSelfLoops() && isSelfLoop) { 248 assertThat(connected).isFalse(); 249 } 250 251 assertThat(network.successors(node).contains(otherNode)).isEqualTo(connected); 252 assertThat(network.predecessors(otherNode).contains(node)).isEqualTo(connected); 253 for (E edge : edgesConnecting) { 254 assertThat(network.incidentNodes(edge)) 255 .isEqualTo(EndpointPair.of(network, node, otherNode)); 256 assertThat(network.outEdges(node)).contains(edge); 257 assertThat(network.inEdges(otherNode)).contains(edge); 258 } 259 } 260 261 for (N adjacentNode : sanityCheckSet(network.adjacentNodes(node))) { 262 assertTrue( 263 network.predecessors(node).contains(adjacentNode) 264 || network.successors(node).contains(adjacentNode)); 265 assertTrue( 266 !network.edgesConnecting(node, adjacentNode).isEmpty() 267 || !network.edgesConnecting(adjacentNode, node).isEmpty()); 268 } 269 270 for (N predecessor : sanityCheckSet(network.predecessors(node))) { 271 assertThat(network.successors(predecessor)).contains(node); 272 assertThat(network.edgesConnecting(predecessor, node)).isNotEmpty(); 273 } 274 275 for (N successor : sanityCheckSet(network.successors(node))) { 276 assertThat(network.predecessors(successor)).contains(node); 277 assertThat(network.edgesConnecting(node, successor)).isNotEmpty(); 278 } 279 280 for (E incidentEdge : sanityCheckSet(network.incidentEdges(node))) { 281 assertTrue( 282 network.inEdges(node).contains(incidentEdge) 283 || network.outEdges(node).contains(incidentEdge)); 284 assertThat(network.edges()).contains(incidentEdge); 285 assertThat(network.incidentNodes(incidentEdge)).contains(node); 286 } 287 288 for (E inEdge : sanityCheckSet(network.inEdges(node))) { 289 assertThat(network.incidentEdges(node)).contains(inEdge); 290 assertThat(network.outEdges(network.incidentNodes(inEdge).adjacentNode(node))) 291 .contains(inEdge); 292 if (network.isDirected()) { 293 assertThat(network.incidentNodes(inEdge).target()).isEqualTo(node); 294 } 295 } 296 297 for (E outEdge : sanityCheckSet(network.outEdges(node))) { 298 assertThat(network.incidentEdges(node)).contains(outEdge); 299 assertThat(network.inEdges(network.incidentNodes(outEdge).adjacentNode(node))) 300 .contains(outEdge); 301 if (network.isDirected()) { 302 assertThat(network.incidentNodes(outEdge).source()).isEqualTo(node); 303 } 304 } 305 } 306 } 307 308 /** 309 * Verifies that the {@code Set} returned by {@code nodes} has the expected mutability property 310 * (see the {@code Network} documentation for more information). 311 */ 312 @Test nodes_checkReturnedSetMutability()313 public abstract void nodes_checkReturnedSetMutability(); 314 315 /** 316 * Verifies that the {@code Set} returned by {@code edges} has the expected mutability property 317 * (see the {@code Network} documentation for more information). 318 */ 319 @Test edges_checkReturnedSetMutability()320 public abstract void edges_checkReturnedSetMutability(); 321 322 /** 323 * Verifies that the {@code Set} returned by {@code incidentEdges} has the expected mutability 324 * property (see the {@code Network} documentation for more information). 325 */ 326 @Test incidentEdges_checkReturnedSetMutability()327 public abstract void incidentEdges_checkReturnedSetMutability(); 328 329 /** 330 * Verifies that the {@code Set} returned by {@code adjacentNodes} has the expected mutability 331 * property (see the {@code Network} documentation for more information). 332 */ 333 @Test adjacentNodes_checkReturnedSetMutability()334 public abstract void adjacentNodes_checkReturnedSetMutability(); 335 336 /** 337 * Verifies that the {@code Set} returned by {@code adjacentEdges} has the expected mutability 338 * property (see the {@code Network} documentation for more information). 339 */ 340 @Test adjacentEdges_checkReturnedSetMutability()341 public abstract void adjacentEdges_checkReturnedSetMutability(); 342 343 /** 344 * Verifies that the {@code Set} returned by {@code edgesConnecting} has the expected mutability 345 * property (see the {@code Network} documentation for more information). 346 */ 347 @Test edgesConnecting_checkReturnedSetMutability()348 public abstract void edgesConnecting_checkReturnedSetMutability(); 349 350 /** 351 * Verifies that the {@code Set} returned by {@code inEdges} has the expected mutability property 352 * (see the {@code Network} documentation for more information). 353 */ 354 @Test inEdges_checkReturnedSetMutability()355 public abstract void inEdges_checkReturnedSetMutability(); 356 357 /** 358 * Verifies that the {@code Set} returned by {@code outEdges} has the expected mutability property 359 * (see the {@code Network} documentation for more information). 360 */ 361 @Test outEdges_checkReturnedSetMutability()362 public abstract void outEdges_checkReturnedSetMutability(); 363 364 /** 365 * Verifies that the {@code Set} returned by {@code predecessors} has the expected mutability 366 * property (see the {@code Network} documentation for more information). 367 */ 368 @Test predecessors_checkReturnedSetMutability()369 public abstract void predecessors_checkReturnedSetMutability(); 370 371 /** 372 * Verifies that the {@code Set} returned by {@code successors} has the expected mutability 373 * property (see the {@code Network} documentation for more information). 374 */ 375 @Test successors_checkReturnedSetMutability()376 public abstract void successors_checkReturnedSetMutability(); 377 378 @Test nodes_oneNode()379 public void nodes_oneNode() { 380 addNode(N1); 381 assertThat(network.nodes()).containsExactly(N1); 382 } 383 384 @Test nodes_noNodes()385 public void nodes_noNodes() { 386 assertThat(network.nodes()).isEmpty(); 387 } 388 389 @Test edges_oneEdge()390 public void edges_oneEdge() { 391 addEdge(N1, N2, E12); 392 assertThat(network.edges()).containsExactly(E12); 393 } 394 395 @Test edges_noEdges()396 public void edges_noEdges() { 397 assertThat(network.edges()).isEmpty(); 398 // Network with no edges, given disconnected nodes 399 addNode(N1); 400 addNode(N2); 401 assertThat(network.edges()).isEmpty(); 402 } 403 404 @Test incidentEdges_oneEdge()405 public void incidentEdges_oneEdge() { 406 addEdge(N1, N2, E12); 407 assertThat(network.incidentEdges(N2)).containsExactly(E12); 408 assertThat(network.incidentEdges(N1)).containsExactly(E12); 409 } 410 411 @Test incidentEdges_isolatedNode()412 public void incidentEdges_isolatedNode() { 413 addNode(N1); 414 assertThat(network.incidentEdges(N1)).isEmpty(); 415 } 416 417 @Test incidentEdges_nodeNotInGraph()418 public void incidentEdges_nodeNotInGraph() { 419 IllegalArgumentException e = 420 assertThrows( 421 IllegalArgumentException.class, () -> network.incidentEdges(NODE_NOT_IN_GRAPH)); 422 assertNodeNotInGraphErrorMessage(e); 423 } 424 425 @Test incidentNodes_oneEdge()426 public void incidentNodes_oneEdge() { 427 addEdge(N1, N2, E12); 428 assertThat(network.incidentNodes(E12)).containsExactly(N1, N2); 429 } 430 431 @Test incidentNodes_edgeNotInGraph()432 public void incidentNodes_edgeNotInGraph() { 433 IllegalArgumentException e = 434 assertThrows( 435 IllegalArgumentException.class, () -> network.incidentNodes(EDGE_NOT_IN_GRAPH)); 436 assertEdgeNotInGraphErrorMessage(e); 437 } 438 439 @Test adjacentNodes_oneEdge()440 public void adjacentNodes_oneEdge() { 441 addEdge(N1, N2, E12); 442 assertThat(network.adjacentNodes(N1)).containsExactly(N2); 443 assertThat(network.adjacentNodes(N2)).containsExactly(N1); 444 } 445 446 @Test adjacentNodes_noAdjacentNodes()447 public void adjacentNodes_noAdjacentNodes() { 448 addNode(N1); 449 assertThat(network.adjacentNodes(N1)).isEmpty(); 450 } 451 452 @Test adjacentNodes_nodeNotInGraph()453 public void adjacentNodes_nodeNotInGraph() { 454 IllegalArgumentException e = 455 assertThrows( 456 IllegalArgumentException.class, () -> network.adjacentNodes(NODE_NOT_IN_GRAPH)); 457 assertNodeNotInGraphErrorMessage(e); 458 } 459 460 @Test adjacentEdges_bothEndpoints()461 public void adjacentEdges_bothEndpoints() { 462 addEdge(N1, N2, E12); 463 addEdge(N2, N3, E23); 464 addEdge(N3, N1, E31); 465 addEdge(N3, N4, E34); 466 assertThat(network.adjacentEdges(E12)).containsExactly(E31, E23); 467 } 468 469 @Test adjacentEdges_noAdjacentEdges()470 public void adjacentEdges_noAdjacentEdges() { 471 addEdge(N1, N2, E12); 472 addEdge(N3, N4, E34); 473 assertThat(network.adjacentEdges(E12)).isEmpty(); 474 } 475 476 @Test adjacentEdges_edgeNotInGraph()477 public void adjacentEdges_edgeNotInGraph() { 478 IllegalArgumentException e = 479 assertThrows( 480 IllegalArgumentException.class, () -> network.adjacentEdges(EDGE_NOT_IN_GRAPH)); 481 assertEdgeNotInGraphErrorMessage(e); 482 } 483 484 @Test adjacentEdges_parallelEdges()485 public void adjacentEdges_parallelEdges() { 486 assume().that(network.allowsParallelEdges()).isTrue(); 487 488 addEdge(N1, N2, E12); 489 addEdge(N1, N2, E12_A); 490 addEdge(N1, N2, E12_B); 491 addEdge(N3, N4, E34); 492 493 assertThat(network.adjacentEdges(E12)).containsExactly(E12_A, E12_B); 494 } 495 496 @Test edgesConnecting_disconnectedNodes()497 public void edgesConnecting_disconnectedNodes() { 498 addNode(N1); 499 addNode(N2); 500 assertThat(network.edgesConnecting(N1, N2)).isEmpty(); 501 } 502 503 @Test edgesConnecting_nodesNotInGraph()504 public void edgesConnecting_nodesNotInGraph() { 505 addNode(N1); 506 addNode(N2); 507 IllegalArgumentException e = 508 assertThrows( 509 IllegalArgumentException.class, () -> network.edgesConnecting(N1, NODE_NOT_IN_GRAPH)); 510 assertNodeNotInGraphErrorMessage(e); 511 e = 512 assertThrows( 513 IllegalArgumentException.class, () -> network.edgesConnecting(NODE_NOT_IN_GRAPH, N2)); 514 assertNodeNotInGraphErrorMessage(e); 515 e = 516 assertThrows( 517 IllegalArgumentException.class, 518 () -> network.edgesConnecting(NODE_NOT_IN_GRAPH, NODE_NOT_IN_GRAPH)); 519 assertNodeNotInGraphErrorMessage(e); 520 } 521 522 @Test edgesConnecting_parallelEdges_directed()523 public void edgesConnecting_parallelEdges_directed() { 524 assume().that(network.allowsParallelEdges()).isTrue(); 525 assume().that(network.isDirected()).isTrue(); 526 527 addEdge(N1, N2, E12); 528 addEdge(N1, N2, E12_A); 529 530 assertThat(network.edgesConnecting(N1, N2)).containsExactly(E12, E12_A); 531 // Passed nodes should be in the correct edge direction, first is the 532 // source node and the second is the target node 533 assertThat(network.edgesConnecting(N2, N1)).isEmpty(); 534 } 535 536 @Test edgesConnecting_parallelEdges_undirected()537 public void edgesConnecting_parallelEdges_undirected() { 538 assume().that(network.allowsParallelEdges()).isTrue(); 539 assume().that(network.isDirected()).isFalse(); 540 541 addEdge(N1, N2, E12); 542 addEdge(N1, N2, E12_A); 543 addEdge(N2, N1, E21); 544 545 assertThat(network.edgesConnecting(N1, N2)).containsExactly(E12, E12_A, E21); 546 assertThat(network.edgesConnecting(N2, N1)).containsExactly(E12, E12_A, E21); 547 } 548 549 @Test edgesConnecting_parallelSelfLoopEdges()550 public void edgesConnecting_parallelSelfLoopEdges() { 551 assume().that(network.allowsParallelEdges()).isTrue(); 552 assume().that(network.allowsSelfLoops()).isTrue(); 553 554 addEdge(N1, N1, E11); 555 addEdge(N1, N1, E11_A); 556 557 assertThat(network.edgesConnecting(N1, N1)).containsExactly(E11, E11_A); 558 } 559 560 @Test hasEdgeConnecting_disconnectedNodes()561 public void hasEdgeConnecting_disconnectedNodes() { 562 addNode(N1); 563 addNode(N2); 564 assertThat(network.hasEdgeConnecting(N1, N2)).isFalse(); 565 } 566 567 @Test hasEdgesConnecting_nodesNotInGraph()568 public void hasEdgesConnecting_nodesNotInGraph() { 569 addNode(N1); 570 addNode(N2); 571 assertThat(network.hasEdgeConnecting(N1, NODE_NOT_IN_GRAPH)).isFalse(); 572 assertThat(network.hasEdgeConnecting(NODE_NOT_IN_GRAPH, N2)).isFalse(); 573 assertThat(network.hasEdgeConnecting(NODE_NOT_IN_GRAPH, NODE_NOT_IN_GRAPH)).isFalse(); 574 } 575 576 @Test inEdges_noInEdges()577 public void inEdges_noInEdges() { 578 addNode(N1); 579 assertThat(network.inEdges(N1)).isEmpty(); 580 } 581 582 @Test inEdges_nodeNotInGraph()583 public void inEdges_nodeNotInGraph() { 584 IllegalArgumentException e = 585 assertThrows(IllegalArgumentException.class, () -> network.inEdges(NODE_NOT_IN_GRAPH)); 586 assertNodeNotInGraphErrorMessage(e); 587 } 588 589 @Test outEdges_noOutEdges()590 public void outEdges_noOutEdges() { 591 addNode(N1); 592 assertThat(network.outEdges(N1)).isEmpty(); 593 } 594 595 @Test outEdges_nodeNotInGraph()596 public void outEdges_nodeNotInGraph() { 597 IllegalArgumentException e = 598 assertThrows(IllegalArgumentException.class, () -> network.outEdges(NODE_NOT_IN_GRAPH)); 599 assertNodeNotInGraphErrorMessage(e); 600 } 601 602 @Test predecessors_noPredecessors()603 public void predecessors_noPredecessors() { 604 addNode(N1); 605 assertThat(network.predecessors(N1)).isEmpty(); 606 } 607 608 @Test predecessors_nodeNotInGraph()609 public void predecessors_nodeNotInGraph() { 610 IllegalArgumentException e = 611 assertThrows(IllegalArgumentException.class, () -> network.predecessors(NODE_NOT_IN_GRAPH)); 612 assertNodeNotInGraphErrorMessage(e); 613 } 614 615 @Test successors_noSuccessors()616 public void successors_noSuccessors() { 617 addNode(N1); 618 assertThat(network.successors(N1)).isEmpty(); 619 } 620 621 @Test successors_nodeNotInGraph()622 public void successors_nodeNotInGraph() { 623 IllegalArgumentException e = 624 assertThrows(IllegalArgumentException.class, () -> network.successors(NODE_NOT_IN_GRAPH)); 625 assertNodeNotInGraphErrorMessage(e); 626 } 627 628 @Test addNode_newNode()629 public void addNode_newNode() { 630 assume().that(graphIsMutable()).isTrue(); 631 632 assertTrue(networkAsMutableNetwork.addNode(N1)); 633 assertThat(networkAsMutableNetwork.nodes()).contains(N1); 634 } 635 636 @Test addNode_existingNode()637 public void addNode_existingNode() { 638 assume().that(graphIsMutable()).isTrue(); 639 640 addNode(N1); 641 ImmutableSet<Integer> nodes = ImmutableSet.copyOf(networkAsMutableNetwork.nodes()); 642 assertFalse(networkAsMutableNetwork.addNode(N1)); 643 assertThat(networkAsMutableNetwork.nodes()).containsExactlyElementsIn(nodes); 644 } 645 646 @Test removeNode_existingNode()647 public void removeNode_existingNode() { 648 assume().that(graphIsMutable()).isTrue(); 649 650 addEdge(N1, N2, E12); 651 addEdge(N4, N1, E41); 652 assertTrue(networkAsMutableNetwork.removeNode(N1)); 653 assertFalse(networkAsMutableNetwork.removeNode(N1)); 654 assertThat(networkAsMutableNetwork.nodes()).containsExactly(N2, N4); 655 assertThat(networkAsMutableNetwork.edges()).doesNotContain(E12); 656 assertThat(networkAsMutableNetwork.edges()).doesNotContain(E41); 657 } 658 659 @Test removeNode_nodeNotPresent()660 public void removeNode_nodeNotPresent() { 661 assume().that(graphIsMutable()).isTrue(); 662 663 addNode(N1); 664 ImmutableSet<Integer> nodes = ImmutableSet.copyOf(networkAsMutableNetwork.nodes()); 665 assertFalse(networkAsMutableNetwork.removeNode(NODE_NOT_IN_GRAPH)); 666 assertThat(networkAsMutableNetwork.nodes()).containsExactlyElementsIn(nodes); 667 } 668 669 @Test removeNode_queryAfterRemoval()670 public void removeNode_queryAfterRemoval() { 671 assume().that(graphIsMutable()).isTrue(); 672 673 addEdge(N1, N2, E12); 674 Set<Integer> n1AdjacentNodes = networkAsMutableNetwork.adjacentNodes(N1); 675 Set<Integer> n2AdjacentNodes = networkAsMutableNetwork.adjacentNodes(N2); 676 assertTrue(networkAsMutableNetwork.removeNode(N1)); 677 assertThat(n1AdjacentNodes).isEmpty(); 678 assertThat(n2AdjacentNodes).isEmpty(); 679 IllegalArgumentException e = 680 assertThrows( 681 IllegalArgumentException.class, () -> networkAsMutableNetwork.adjacentNodes(N1)); 682 assertNodeNotInGraphErrorMessage(e); 683 } 684 685 @Test removeEdge_existingEdge()686 public void removeEdge_existingEdge() { 687 assume().that(graphIsMutable()).isTrue(); 688 689 addEdge(N1, N2, E12); 690 assertTrue(networkAsMutableNetwork.removeEdge(E12)); 691 assertFalse(networkAsMutableNetwork.removeEdge(E12)); 692 assertThat(networkAsMutableNetwork.edges()).doesNotContain(E12); 693 assertThat(networkAsMutableNetwork.edgesConnecting(N1, N2)).isEmpty(); 694 } 695 696 @Test removeEdge_oneOfMany()697 public void removeEdge_oneOfMany() { 698 assume().that(graphIsMutable()).isTrue(); 699 700 addEdge(N1, N2, E12); 701 addEdge(N1, N3, E13); 702 addEdge(N1, N4, E14); 703 assertThat(networkAsMutableNetwork.edges()).containsExactly(E12, E13, E14); 704 assertTrue(networkAsMutableNetwork.removeEdge(E13)); 705 assertThat(networkAsMutableNetwork.edges()).containsExactly(E12, E14); 706 } 707 708 @Test removeEdge_edgeNotPresent()709 public void removeEdge_edgeNotPresent() { 710 assume().that(graphIsMutable()).isTrue(); 711 712 addEdge(N1, N2, E12); 713 ImmutableSet<String> edges = ImmutableSet.copyOf(networkAsMutableNetwork.edges()); 714 assertFalse(networkAsMutableNetwork.removeEdge(EDGE_NOT_IN_GRAPH)); 715 assertThat(networkAsMutableNetwork.edges()).containsExactlyElementsIn(edges); 716 } 717 718 @Test removeEdge_queryAfterRemoval()719 public void removeEdge_queryAfterRemoval() { 720 assume().that(graphIsMutable()).isTrue(); 721 722 addEdge(N1, N2, E12); 723 @SuppressWarnings("unused") 724 EndpointPair<Integer> unused = 725 networkAsMutableNetwork.incidentNodes(E12); // ensure cache (if any) is populated 726 assertTrue(networkAsMutableNetwork.removeEdge(E12)); 727 IllegalArgumentException e = 728 assertThrows( 729 IllegalArgumentException.class, () -> networkAsMutableNetwork.incidentNodes(E12)); 730 assertEdgeNotInGraphErrorMessage(e); 731 } 732 733 @Test removeEdge_parallelEdge()734 public void removeEdge_parallelEdge() { 735 assume().that(graphIsMutable()).isTrue(); 736 assume().that(network.allowsParallelEdges()).isTrue(); 737 738 addEdge(N1, N2, E12); 739 addEdge(N1, N2, E12_A); 740 assertTrue(networkAsMutableNetwork.removeEdge(E12_A)); 741 assertThat(network.edgesConnecting(N1, N2)).containsExactly(E12); 742 } 743 744 @Test removeEdge_parallelSelfLoopEdge()745 public void removeEdge_parallelSelfLoopEdge() { 746 assume().that(graphIsMutable()).isTrue(); 747 assume().that(network.allowsParallelEdges()).isTrue(); 748 assume().that(network.allowsSelfLoops()).isTrue(); 749 750 addEdge(N1, N1, E11); 751 addEdge(N1, N1, E11_A); 752 addEdge(N1, N2, E12); 753 assertTrue(networkAsMutableNetwork.removeEdge(E11_A)); 754 assertThat(network.edgesConnecting(N1, N1)).containsExactly(E11); 755 assertThat(network.edgesConnecting(N1, N2)).containsExactly(E12); 756 assertTrue(networkAsMutableNetwork.removeEdge(E11)); 757 assertThat(network.edgesConnecting(N1, N1)).isEmpty(); 758 assertThat(network.edgesConnecting(N1, N2)).containsExactly(E12); 759 } 760 761 @Test concurrentIteration()762 public void concurrentIteration() throws Exception { 763 addEdge(1, 2, "foo"); 764 addEdge(3, 4, "bar"); 765 addEdge(5, 6, "baz"); 766 767 int threadCount = 20; 768 ExecutorService executor = newFixedThreadPool(threadCount); 769 final CyclicBarrier barrier = new CyclicBarrier(threadCount); 770 ImmutableList.Builder<Future<?>> futures = ImmutableList.builder(); 771 for (int i = 0; i < threadCount; i++) { 772 futures.add( 773 executor.submit( 774 new Callable<@Nullable Void>() { 775 @Override 776 public @Nullable Void call() throws Exception { 777 barrier.await(); 778 Integer first = network.nodes().iterator().next(); 779 for (Integer node : network.nodes()) { 780 Set<Integer> unused = network.successors(node); 781 } 782 /* 783 * Also look up an earlier node so that, if the graph is using MapRetrievalCache, 784 * we read one of the fields declared in that class. 785 */ 786 Set<Integer> unused = network.successors(first); 787 return null; 788 } 789 })); 790 } 791 792 /* 793 * It's unlikely that any operations would fail by throwing an exception, but let's check them 794 * just to be safe. 795 * 796 * The real purpose of this test is to produce a TSAN failure if MapIteratorCache is unsafe for 797 * reads from multiple threads -- unsafe, in fact, even in the absence of a concurrent write. 798 * The specific problem we had was unsafe reads of lastEntryReturnedBySomeIterator. (To fix the 799 * problem, we've since marked that field as volatile.) 800 * 801 * When MapIteratorCache is used from Immutable* classes, the TSAN failure doesn't indicate a 802 * real problem: The Entry objects are ImmutableMap entries, whose fields are all final and thus 803 * safe to read even when the Entry object is unsafely published. But with a mutable graph, the 804 * Entry object is likely to have a non-final value field, which is not safe to read when 805 * unsafely published. (The Entry object might even be newly created by each iterator.next() 806 * call, so we can't assume that writes to the Entry have been safely published by some other 807 * synchronization actions.) 808 * 809 * All that said: I haven't actually managed to make this particular test produce a TSAN error 810 * for the field accesses in MapIteratorCache. This teset *has* found other TSAN errors, 811 * including in MapRetrievalCache, so I'm not sure why this one is different. I did at least 812 * confirm that my change to MapIteratorCache fixes the TSAN error in the (larger) test it was 813 * originally reported in. 814 */ 815 for (Future<?> future : futures.build()) { 816 future.get(); 817 } 818 executor.shutdown(); 819 } 820 } 821