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.ERROR_NODE_NOT_IN_GRAPH; 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 org.junit.Assert.fail; 26 27 import com.google.common.collect.ImmutableSet; 28 import java.util.HashSet; 29 import java.util.Set; 30 import org.junit.After; 31 import org.junit.Before; 32 import org.junit.Test; 33 34 /** 35 * Abstract base class for testing implementations of {@link Graph} interface. Graph instances 36 * created for testing should have Integer node and String edge objects. 37 * 38 * <p>Test cases that should be handled similarly in any graph implementation are included in this 39 * class. For example, testing that {@code nodes()} method returns the set of the nodes in the 40 * graph. The following test cases are left for the subclasses to handle: 41 * 42 * <ul> 43 * <li>Test cases related to whether the graph is directed or undirected. 44 * <li>Test cases related to the specific implementation of the {@link Graph} interface. 45 * </ul> 46 * 47 * TODO(user): Make this class generic (using <N, E>) for all node and edge types. 48 * TODO(user): Differentiate between directed and undirected edge strings. 49 */ 50 public abstract class AbstractGraphTest { 51 52 Graph<Integer> graph; 53 54 /** 55 * The same reference as {@link #graph}, except as a mutable graph. This field is null in case 56 * {@link #createGraph()} didn't return a mutable graph. 57 */ 58 MutableGraph<Integer> graphAsMutableGraph; 59 60 static final Integer N1 = 1; 61 static final Integer N2 = 2; 62 static final Integer N3 = 3; 63 static final Integer N4 = 4; 64 static final Integer N5 = 5; 65 static final Integer NODE_NOT_IN_GRAPH = 1000; 66 67 // TODO(user): Consider separating Strings that we've defined here to capture 68 // identifiable substrings of expected error messages, from Strings that we've defined 69 // here to provide error messages. 70 // TODO(user): Some Strings used in the subclasses can be added as static Strings 71 // here too. 72 static final String ERROR_MODIFIABLE_SET = "Set returned is unexpectedly modifiable"; 73 static final String ERROR_SELF_LOOP = "self-loops are not allowed"; 74 static final String ERROR_ADDED_SELF_LOOP = "Should not be allowed to add a self-loop edge."; 75 76 /** Creates and returns an instance of the graph to be tested. */ createGraph()77 abstract Graph<Integer> createGraph(); 78 79 /** 80 * A proxy method that adds the node {@code n} to the graph being tested. In case of Immutable 81 * graph implementations, this method should replace {@link #graph} with a new graph that includes 82 * this node. 83 */ addNode(Integer n)84 abstract void addNode(Integer n); 85 86 /** 87 * A proxy method that adds the edge {@code e} to the graph being tested. In case of Immutable 88 * graph implementations, this method should replace {@link #graph} with a new graph that includes 89 * this edge. 90 */ putEdge(Integer n1, Integer n2)91 abstract void putEdge(Integer n1, Integer n2); 92 graphIsMutable()93 final boolean graphIsMutable() { 94 return graphAsMutableGraph != null; 95 } 96 97 @Before init()98 public final void init() { 99 graph = createGraph(); 100 if (graph instanceof MutableGraph) { 101 graphAsMutableGraph = (MutableGraph<Integer>) graph; 102 } 103 } 104 105 @After validateGraphState()106 public final void validateGraphState() { 107 validateGraph(graph); 108 } 109 validateGraph(Graph<N> graph)110 static <N> void validateGraph(Graph<N> graph) { 111 assertStronglyEquivalent(graph, Graphs.copyOf(graph)); 112 assertStronglyEquivalent(graph, ImmutableGraph.copyOf(graph)); 113 114 String graphString = graph.toString(); 115 assertThat(graphString).contains("isDirected: " + graph.isDirected()); 116 assertThat(graphString).contains("allowsSelfLoops: " + graph.allowsSelfLoops()); 117 118 int nodeStart = graphString.indexOf("nodes:"); 119 int edgeStart = graphString.indexOf("edges:"); 120 String nodeString = graphString.substring(nodeStart, edgeStart); 121 122 Set<EndpointPair<N>> allEndpointPairs = new HashSet<>(); 123 124 for (N node : sanityCheckSet(graph.nodes())) { 125 assertThat(nodeString).contains(node.toString()); 126 127 if (graph.isDirected()) { 128 assertThat(graph.degree(node)).isEqualTo(graph.inDegree(node) + graph.outDegree(node)); 129 assertThat(graph.predecessors(node)).hasSize(graph.inDegree(node)); 130 assertThat(graph.successors(node)).hasSize(graph.outDegree(node)); 131 } else { 132 int selfLoopCount = graph.adjacentNodes(node).contains(node) ? 1 : 0; 133 assertThat(graph.degree(node)).isEqualTo(graph.adjacentNodes(node).size() + selfLoopCount); 134 assertThat(graph.predecessors(node)).isEqualTo(graph.adjacentNodes(node)); 135 assertThat(graph.successors(node)).isEqualTo(graph.adjacentNodes(node)); 136 assertThat(graph.inDegree(node)).isEqualTo(graph.degree(node)); 137 assertThat(graph.outDegree(node)).isEqualTo(graph.degree(node)); 138 } 139 140 for (N adjacentNode : sanityCheckSet(graph.adjacentNodes(node))) { 141 if (!graph.allowsSelfLoops()) { 142 assertThat(node).isNotEqualTo(adjacentNode); 143 } 144 assertThat( 145 graph.predecessors(node).contains(adjacentNode) 146 || graph.successors(node).contains(adjacentNode)) 147 .isTrue(); 148 } 149 150 for (N predecessor : sanityCheckSet(graph.predecessors(node))) { 151 assertThat(graph.successors(predecessor)).contains(node); 152 assertThat(graph.hasEdgeConnecting(predecessor, node)).isTrue(); 153 assertThat(graph.incidentEdges(node)).contains(EndpointPair.of(graph, predecessor, node)); 154 } 155 156 for (N successor : sanityCheckSet(graph.successors(node))) { 157 allEndpointPairs.add(EndpointPair.of(graph, node, successor)); 158 assertThat(graph.predecessors(successor)).contains(node); 159 assertThat(graph.hasEdgeConnecting(node, successor)).isTrue(); 160 assertThat(graph.incidentEdges(node)).contains(EndpointPair.of(graph, node, successor)); 161 } 162 163 for (EndpointPair<N> endpoints : sanityCheckSet(graph.incidentEdges(node))) { 164 if (graph.isDirected()) { 165 assertThat(graph.hasEdgeConnecting(endpoints.source(), endpoints.target())).isTrue(); 166 } else { 167 assertThat(graph.hasEdgeConnecting(endpoints.nodeU(), endpoints.nodeV())).isTrue(); 168 } 169 } 170 } 171 172 sanityCheckSet(graph.edges()); 173 assertThat(graph.edges()).doesNotContain(EndpointPair.of(graph, new Object(), new Object())); 174 assertThat(graph.edges()).isEqualTo(allEndpointPairs); 175 } 176 177 /** 178 * Verifies that the {@code Set} returned by {@code nodes} has the expected mutability property 179 * (see the {@code Graph} documentation for more information). 180 */ 181 @Test nodes_checkReturnedSetMutability()182 public abstract void nodes_checkReturnedSetMutability(); 183 184 /** 185 * Verifies that the {@code Set} returned by {@code adjacentNodes} has the expected mutability 186 * property (see the {@code Graph} documentation for more information). 187 */ 188 @Test adjacentNodes_checkReturnedSetMutability()189 public abstract void adjacentNodes_checkReturnedSetMutability(); 190 191 /** 192 * Verifies that the {@code Set} returned by {@code predecessors} has the expected mutability 193 * property (see the {@code Graph} documentation for more information). 194 */ 195 @Test predecessors_checkReturnedSetMutability()196 public abstract void predecessors_checkReturnedSetMutability(); 197 198 /** 199 * Verifies that the {@code Set} returned by {@code successors} has the expected mutability 200 * property (see the {@code Graph} documentation for more information). 201 */ 202 @Test successors_checkReturnedSetMutability()203 public abstract void successors_checkReturnedSetMutability(); 204 205 /** 206 * Verifies that the {@code Set} returned by {@code incidentEdges} has the expected mutability 207 * property (see the {@code Graph} documentation for more information). 208 */ 209 @Test incidentEdges_checkReturnedSetMutability()210 public abstract void incidentEdges_checkReturnedSetMutability(); 211 212 @Test nodes_oneNode()213 public void nodes_oneNode() { 214 addNode(N1); 215 assertThat(graph.nodes()).containsExactly(N1); 216 } 217 218 @Test nodes_noNodes()219 public void nodes_noNodes() { 220 assertThat(graph.nodes()).isEmpty(); 221 } 222 223 @Test adjacentNodes_oneEdge()224 public void adjacentNodes_oneEdge() { 225 putEdge(N1, N2); 226 assertThat(graph.adjacentNodes(N1)).containsExactly(N2); 227 assertThat(graph.adjacentNodes(N2)).containsExactly(N1); 228 } 229 230 @Test adjacentNodes_noAdjacentNodes()231 public void adjacentNodes_noAdjacentNodes() { 232 addNode(N1); 233 assertThat(graph.adjacentNodes(N1)).isEmpty(); 234 } 235 236 @Test adjacentNodes_nodeNotInGraph()237 public void adjacentNodes_nodeNotInGraph() { 238 try { 239 graph.adjacentNodes(NODE_NOT_IN_GRAPH); 240 fail(ERROR_NODE_NOT_IN_GRAPH); 241 } catch (IllegalArgumentException e) { 242 assertNodeNotInGraphErrorMessage(e); 243 } 244 } 245 246 @Test predecessors_noPredecessors()247 public void predecessors_noPredecessors() { 248 addNode(N1); 249 assertThat(graph.predecessors(N1)).isEmpty(); 250 } 251 252 @Test predecessors_nodeNotInGraph()253 public void predecessors_nodeNotInGraph() { 254 try { 255 graph.predecessors(NODE_NOT_IN_GRAPH); 256 fail(ERROR_NODE_NOT_IN_GRAPH); 257 } catch (IllegalArgumentException e) { 258 assertNodeNotInGraphErrorMessage(e); 259 } 260 } 261 262 @Test successors_noSuccessors()263 public void successors_noSuccessors() { 264 addNode(N1); 265 assertThat(graph.successors(N1)).isEmpty(); 266 } 267 268 @Test successors_nodeNotInGraph()269 public void successors_nodeNotInGraph() { 270 try { 271 graph.successors(NODE_NOT_IN_GRAPH); 272 fail(ERROR_NODE_NOT_IN_GRAPH); 273 } catch (IllegalArgumentException e) { 274 assertNodeNotInGraphErrorMessage(e); 275 } 276 } 277 278 @Test incidentEdges_noIncidentEdges()279 public void incidentEdges_noIncidentEdges() { 280 addNode(N1); 281 assertThat(graph.incidentEdges(N1)).isEmpty(); 282 } 283 284 @Test incidentEdges_nodeNotInGraph()285 public void incidentEdges_nodeNotInGraph() { 286 try { 287 graph.incidentEdges(NODE_NOT_IN_GRAPH); 288 fail(ERROR_NODE_NOT_IN_GRAPH); 289 } catch (IllegalArgumentException e) { 290 assertNodeNotInGraphErrorMessage(e); 291 } 292 } 293 294 @Test degree_oneEdge()295 public void degree_oneEdge() { 296 putEdge(N1, N2); 297 assertThat(graph.degree(N1)).isEqualTo(1); 298 assertThat(graph.degree(N2)).isEqualTo(1); 299 } 300 301 @Test degree_isolatedNode()302 public void degree_isolatedNode() { 303 addNode(N1); 304 assertThat(graph.degree(N1)).isEqualTo(0); 305 } 306 307 @Test degree_nodeNotInGraph()308 public void degree_nodeNotInGraph() { 309 try { 310 graph.degree(NODE_NOT_IN_GRAPH); 311 fail(ERROR_NODE_NOT_IN_GRAPH); 312 } catch (IllegalArgumentException e) { 313 assertNodeNotInGraphErrorMessage(e); 314 } 315 } 316 317 @Test inDegree_isolatedNode()318 public void inDegree_isolatedNode() { 319 addNode(N1); 320 assertThat(graph.inDegree(N1)).isEqualTo(0); 321 } 322 323 @Test inDegree_nodeNotInGraph()324 public void inDegree_nodeNotInGraph() { 325 try { 326 graph.inDegree(NODE_NOT_IN_GRAPH); 327 fail(ERROR_NODE_NOT_IN_GRAPH); 328 } catch (IllegalArgumentException e) { 329 assertNodeNotInGraphErrorMessage(e); 330 } 331 } 332 333 @Test outDegree_isolatedNode()334 public void outDegree_isolatedNode() { 335 addNode(N1); 336 assertThat(graph.outDegree(N1)).isEqualTo(0); 337 } 338 339 @Test outDegree_nodeNotInGraph()340 public void outDegree_nodeNotInGraph() { 341 try { 342 graph.outDegree(NODE_NOT_IN_GRAPH); 343 fail(ERROR_NODE_NOT_IN_GRAPH); 344 } catch (IllegalArgumentException e) { 345 assertNodeNotInGraphErrorMessage(e); 346 } 347 } 348 349 @Test addNode_newNode()350 public void addNode_newNode() { 351 assume().that(graphIsMutable()).isTrue(); 352 353 assertThat(graphAsMutableGraph.addNode(N1)).isTrue(); 354 assertThat(graph.nodes()).contains(N1); 355 } 356 357 @Test addNode_existingNode()358 public void addNode_existingNode() { 359 assume().that(graphIsMutable()).isTrue(); 360 361 addNode(N1); 362 ImmutableSet<Integer> nodes = ImmutableSet.copyOf(graph.nodes()); 363 assertThat(graphAsMutableGraph.addNode(N1)).isFalse(); 364 assertThat(graph.nodes()).containsExactlyElementsIn(nodes); 365 } 366 367 @Test removeNode_existingNode()368 public void removeNode_existingNode() { 369 assume().that(graphIsMutable()).isTrue(); 370 371 putEdge(N1, N2); 372 putEdge(N4, N1); 373 assertThat(graphAsMutableGraph.removeNode(N1)).isTrue(); 374 assertThat(graphAsMutableGraph.removeNode(N1)).isFalse(); 375 assertThat(graph.nodes()).containsExactly(N2, N4); 376 assertThat(graph.adjacentNodes(N2)).isEmpty(); 377 assertThat(graph.adjacentNodes(N4)).isEmpty(); 378 } 379 380 @Test removeNode_antiparallelEdges()381 public void removeNode_antiparallelEdges() { 382 assume().that(graphIsMutable()).isTrue(); 383 384 putEdge(N1, N2); 385 putEdge(N2, N1); 386 387 assertThat(graphAsMutableGraph.removeNode(N1)).isTrue(); 388 assertThat(graph.nodes()).containsExactly(N2); 389 assertThat(graph.edges()).isEmpty(); 390 391 assertThat(graphAsMutableGraph.removeNode(N2)).isTrue(); 392 assertThat(graph.nodes()).isEmpty(); 393 assertThat(graph.edges()).isEmpty(); 394 } 395 396 @Test removeNode_nodeNotPresent()397 public void removeNode_nodeNotPresent() { 398 assume().that(graphIsMutable()).isTrue(); 399 400 addNode(N1); 401 ImmutableSet<Integer> nodes = ImmutableSet.copyOf(graph.nodes()); 402 assertThat(graphAsMutableGraph.removeNode(NODE_NOT_IN_GRAPH)).isFalse(); 403 assertThat(graph.nodes()).containsExactlyElementsIn(nodes); 404 } 405 406 @Test removeNode_queryAfterRemoval()407 public void removeNode_queryAfterRemoval() { 408 assume().that(graphIsMutable()).isTrue(); 409 410 addNode(N1); 411 @SuppressWarnings("unused") 412 Set<Integer> unused = graph.adjacentNodes(N1); // ensure cache (if any) is populated 413 assertThat(graphAsMutableGraph.removeNode(N1)).isTrue(); 414 try { 415 graph.adjacentNodes(N1); 416 fail(ERROR_NODE_NOT_IN_GRAPH); 417 } catch (IllegalArgumentException e) { 418 assertNodeNotInGraphErrorMessage(e); 419 } 420 } 421 422 @Test removeEdge_existingEdge()423 public void removeEdge_existingEdge() { 424 assume().that(graphIsMutable()).isTrue(); 425 426 putEdge(N1, N2); 427 assertThat(graph.successors(N1)).containsExactly(N2); 428 assertThat(graph.predecessors(N2)).containsExactly(N1); 429 assertThat(graphAsMutableGraph.removeEdge(N1, N2)).isTrue(); 430 assertThat(graphAsMutableGraph.removeEdge(N1, N2)).isFalse(); 431 assertThat(graph.successors(N1)).isEmpty(); 432 assertThat(graph.predecessors(N2)).isEmpty(); 433 } 434 435 @Test removeEdge_oneOfMany()436 public void removeEdge_oneOfMany() { 437 assume().that(graphIsMutable()).isTrue(); 438 439 putEdge(N1, N2); 440 putEdge(N1, N3); 441 putEdge(N1, N4); 442 assertThat(graphAsMutableGraph.removeEdge(N1, N3)).isTrue(); 443 assertThat(graph.adjacentNodes(N1)).containsExactly(N2, N4); 444 } 445 446 @Test removeEdge_nodeNotPresent()447 public void removeEdge_nodeNotPresent() { 448 assume().that(graphIsMutable()).isTrue(); 449 450 putEdge(N1, N2); 451 assertThat(graphAsMutableGraph.removeEdge(N1, NODE_NOT_IN_GRAPH)).isFalse(); 452 assertThat(graph.successors(N1)).contains(N2); 453 } 454 455 @Test removeEdge_edgeNotPresent()456 public void removeEdge_edgeNotPresent() { 457 assume().that(graphIsMutable()).isTrue(); 458 459 putEdge(N1, N2); 460 addNode(N3); 461 462 assertThat(graphAsMutableGraph.removeEdge(N1, N3)).isFalse(); 463 assertThat(graph.successors(N1)).contains(N2); 464 } 465 } 466