aboutsummaryrefslogtreecommitdiff
path: root/android/guava-tests/test/com/google/common/graph/AbstractGraphTest.java
blob: a8209244c03741be966097c026c0ab2146d4edcb (plain)
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
/*
 * Copyright (C) 2014 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.graph;

import static com.google.common.graph.TestUtil.assertNodeNotInGraphErrorMessage;
import static com.google.common.graph.TestUtil.assertStronglyEquivalent;
import static com.google.common.graph.TestUtil.sanityCheckSet;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.junit.Assert.assertThrows;

import com.google.common.collect.ImmutableSet;
import java.util.HashSet;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * Abstract base class for testing implementations of {@link Graph} interface. Graph instances
 * created for testing should have Integer node and String edge objects.
 *
 * <p>Test cases that should be handled similarly in any graph implementation are included in this
 * class. For example, testing that {@code nodes()} method returns the set of the nodes in the
 * graph. The following test cases are left for the subclasses to handle:
 *
 * <ul>
 *   <li>Test cases related to whether the graph is directed or undirected.
 *   <li>Test cases related to the specific implementation of the {@link Graph} interface.
 * </ul>
 *
 * TODO(user): Make this class generic (using <N, E>) for all node and edge types.
 * TODO(user): Differentiate between directed and undirected edge strings.
 */
public abstract class AbstractGraphTest {

  Graph<Integer> graph;

  /**
   * The same reference as {@link #graph}, except as a mutable graph. This field is null in case
   * {@link #createGraph()} didn't return a mutable graph.
   */
  MutableGraph<Integer> graphAsMutableGraph;

  static final Integer N1 = 1;
  static final Integer N2 = 2;
  static final Integer N3 = 3;
  static final Integer N4 = 4;
  static final Integer N5 = 5;
  static final Integer NODE_NOT_IN_GRAPH = 1000;

  // TODO(user): Consider separating Strings that we've defined here to capture
  // identifiable substrings of expected error messages, from Strings that we've defined
  // here to provide error messages.
  // TODO(user): Some Strings used in the subclasses can be added as static Strings
  // here too.
  static final String ERROR_MODIFIABLE_SET = "Set returned is unexpectedly modifiable";
  static final String ERROR_SELF_LOOP = "self-loops are not allowed";
  static final String ERROR_ADDED_SELF_LOOP = "Should not be allowed to add a self-loop edge.";

  /** Creates and returns an instance of the graph to be tested. */
  abstract Graph<Integer> createGraph();

  /**
   * A proxy method that adds the node {@code n} to the graph being tested. In case of Immutable
   * graph implementations, this method should replace {@link #graph} with a new graph that includes
   * this node.
   */
  abstract void addNode(Integer n);

  /**
   * A proxy method that adds the edge {@code e} to the graph being tested. In case of Immutable
   * graph implementations, this method should replace {@link #graph} with a new graph that includes
   * this edge.
   */
  abstract void putEdge(Integer n1, Integer n2);

  final boolean graphIsMutable() {
    return graphAsMutableGraph != null;
  }

  @Before
  public final void init() {
    graph = createGraph();
    if (graph instanceof MutableGraph) {
      graphAsMutableGraph = (MutableGraph<Integer>) graph;
    }
  }

  @After
  public final void validateGraphState() {
    validateGraph(graph);
  }

  static <N> void validateGraph(Graph<N> graph) {
    assertStronglyEquivalent(graph, Graphs.copyOf(graph));
    assertStronglyEquivalent(graph, ImmutableGraph.copyOf(graph));

    String graphString = graph.toString();
    assertThat(graphString).contains("isDirected: " + graph.isDirected());
    assertThat(graphString).contains("allowsSelfLoops: " + graph.allowsSelfLoops());

    int nodeStart = graphString.indexOf("nodes:");
    int edgeStart = graphString.indexOf("edges:");
    String nodeString = graphString.substring(nodeStart, edgeStart);

    Set<EndpointPair<N>> allEndpointPairs = new HashSet<>();

    for (N node : sanityCheckSet(graph.nodes())) {
      assertThat(nodeString).contains(node.toString());

      if (graph.isDirected()) {
        assertThat(graph.degree(node)).isEqualTo(graph.inDegree(node) + graph.outDegree(node));
        assertThat(graph.predecessors(node)).hasSize(graph.inDegree(node));
        assertThat(graph.successors(node)).hasSize(graph.outDegree(node));
      } else {
        int selfLoopCount = graph.adjacentNodes(node).contains(node) ? 1 : 0;
        assertThat(graph.degree(node)).isEqualTo(graph.adjacentNodes(node).size() + selfLoopCount);
        assertThat(graph.predecessors(node)).isEqualTo(graph.adjacentNodes(node));
        assertThat(graph.successors(node)).isEqualTo(graph.adjacentNodes(node));
        assertThat(graph.inDegree(node)).isEqualTo(graph.degree(node));
        assertThat(graph.outDegree(node)).isEqualTo(graph.degree(node));
      }

      for (N adjacentNode : sanityCheckSet(graph.adjacentNodes(node))) {
        if (!graph.allowsSelfLoops()) {
          assertThat(node).isNotEqualTo(adjacentNode);
        }
        assertThat(
                graph.predecessors(node).contains(adjacentNode)
                    || graph.successors(node).contains(adjacentNode))
            .isTrue();
      }

      for (N predecessor : sanityCheckSet(graph.predecessors(node))) {
        assertThat(graph.successors(predecessor)).contains(node);
        assertThat(graph.hasEdgeConnecting(predecessor, node)).isTrue();
        assertThat(graph.incidentEdges(node)).contains(EndpointPair.of(graph, predecessor, node));
      }

      for (N successor : sanityCheckSet(graph.successors(node))) {
        allEndpointPairs.add(EndpointPair.of(graph, node, successor));
        assertThat(graph.predecessors(successor)).contains(node);
        assertThat(graph.hasEdgeConnecting(node, successor)).isTrue();
        assertThat(graph.incidentEdges(node)).contains(EndpointPair.of(graph, node, successor));
      }

      for (EndpointPair<N> endpoints : sanityCheckSet(graph.incidentEdges(node))) {
        if (graph.isDirected()) {
          assertThat(graph.hasEdgeConnecting(endpoints.source(), endpoints.target())).isTrue();
        } else {
          assertThat(graph.hasEdgeConnecting(endpoints.nodeU(), endpoints.nodeV())).isTrue();
        }
      }
    }

    sanityCheckSet(graph.edges());
    assertThat(graph.edges()).doesNotContain(EndpointPair.of(graph, new Object(), new Object()));
    assertThat(graph.edges()).isEqualTo(allEndpointPairs);
  }

  /**
   * Verifies that the {@code Set} returned by {@code nodes} has the expected mutability property
   * (see the {@code Graph} documentation for more information).
   */
  @Test
  public abstract void nodes_checkReturnedSetMutability();

  /**
   * Verifies that the {@code Set} returned by {@code adjacentNodes} has the expected mutability
   * property (see the {@code Graph} documentation for more information).
   */
  @Test
  public abstract void adjacentNodes_checkReturnedSetMutability();

  /**
   * Verifies that the {@code Set} returned by {@code predecessors} has the expected mutability
   * property (see the {@code Graph} documentation for more information).
   */
  @Test
  public abstract void predecessors_checkReturnedSetMutability();

  /**
   * Verifies that the {@code Set} returned by {@code successors} has the expected mutability
   * property (see the {@code Graph} documentation for more information).
   */
  @Test
  public abstract void successors_checkReturnedSetMutability();

  /**
   * Verifies that the {@code Set} returned by {@code incidentEdges} has the expected mutability
   * property (see the {@code Graph} documentation for more information).
   */
  @Test
  public abstract void incidentEdges_checkReturnedSetMutability();

  @Test
  public void nodes_oneNode() {
    addNode(N1);
    assertThat(graph.nodes()).containsExactly(N1);
  }

  @Test
  public void nodes_noNodes() {
    assertThat(graph.nodes()).isEmpty();
  }

  @Test
  public void adjacentNodes_oneEdge() {
    putEdge(N1, N2);
    assertThat(graph.adjacentNodes(N1)).containsExactly(N2);
    assertThat(graph.adjacentNodes(N2)).containsExactly(N1);
  }

  @Test
  public void adjacentNodes_noAdjacentNodes() {
    addNode(N1);
    assertThat(graph.adjacentNodes(N1)).isEmpty();
  }

  @Test
  public void adjacentNodes_nodeNotInGraph() {
    IllegalArgumentException e =
        assertThrows(IllegalArgumentException.class, () -> graph.adjacentNodes(NODE_NOT_IN_GRAPH));
    assertNodeNotInGraphErrorMessage(e);
  }

  @Test
  public void predecessors_noPredecessors() {
    addNode(N1);
    assertThat(graph.predecessors(N1)).isEmpty();
  }

  @Test
  public void predecessors_nodeNotInGraph() {
    IllegalArgumentException e =
        assertThrows(IllegalArgumentException.class, () -> graph.predecessors(NODE_NOT_IN_GRAPH));
    assertNodeNotInGraphErrorMessage(e);
  }

  @Test
  public void successors_noSuccessors() {
    addNode(N1);
    assertThat(graph.successors(N1)).isEmpty();
  }

  @Test
  public void successors_nodeNotInGraph() {
    IllegalArgumentException e =
        assertThrows(IllegalArgumentException.class, () -> graph.successors(NODE_NOT_IN_GRAPH));
    assertNodeNotInGraphErrorMessage(e);
  }

  @Test
  public void incidentEdges_noIncidentEdges() {
    addNode(N1);
    assertThat(graph.incidentEdges(N1)).isEmpty();
  }

  @Test
  public void incidentEdges_nodeNotInGraph() {
    IllegalArgumentException e =
        assertThrows(IllegalArgumentException.class, () -> graph.incidentEdges(NODE_NOT_IN_GRAPH));
    assertNodeNotInGraphErrorMessage(e);
  }

  @Test
  public void degree_oneEdge() {
    putEdge(N1, N2);
    assertThat(graph.degree(N1)).isEqualTo(1);
    assertThat(graph.degree(N2)).isEqualTo(1);
  }

  @Test
  public void degree_isolatedNode() {
    addNode(N1);
    assertThat(graph.degree(N1)).isEqualTo(0);
  }

  @Test
  public void degree_nodeNotInGraph() {
    IllegalArgumentException e =
        assertThrows(IllegalArgumentException.class, () -> graph.degree(NODE_NOT_IN_GRAPH));
    assertNodeNotInGraphErrorMessage(e);
  }

  @Test
  public void inDegree_isolatedNode() {
    addNode(N1);
    assertThat(graph.inDegree(N1)).isEqualTo(0);
  }

  @Test
  public void inDegree_nodeNotInGraph() {
    IllegalArgumentException e =
        assertThrows(IllegalArgumentException.class, () -> graph.inDegree(NODE_NOT_IN_GRAPH));
    assertNodeNotInGraphErrorMessage(e);
  }

  @Test
  public void outDegree_isolatedNode() {
    addNode(N1);
    assertThat(graph.outDegree(N1)).isEqualTo(0);
  }

  @Test
  public void outDegree_nodeNotInGraph() {
    IllegalArgumentException e =
        assertThrows(IllegalArgumentException.class, () -> graph.outDegree(NODE_NOT_IN_GRAPH));
    assertNodeNotInGraphErrorMessage(e);
  }

  @Test
  public void addNode_newNode() {
    assume().that(graphIsMutable()).isTrue();

    assertThat(graphAsMutableGraph.addNode(N1)).isTrue();
    assertThat(graph.nodes()).contains(N1);
  }

  @Test
  public void addNode_existingNode() {
    assume().that(graphIsMutable()).isTrue();

    addNode(N1);
    ImmutableSet<Integer> nodes = ImmutableSet.copyOf(graph.nodes());
    assertThat(graphAsMutableGraph.addNode(N1)).isFalse();
    assertThat(graph.nodes()).containsExactlyElementsIn(nodes);
  }

  @Test
  public void removeNode_existingNode() {
    assume().that(graphIsMutable()).isTrue();

    putEdge(N1, N2);
    putEdge(N4, N1);
    assertThat(graphAsMutableGraph.removeNode(N1)).isTrue();
    assertThat(graphAsMutableGraph.removeNode(N1)).isFalse();
    assertThat(graph.nodes()).containsExactly(N2, N4);
    assertThat(graph.adjacentNodes(N2)).isEmpty();
    assertThat(graph.adjacentNodes(N4)).isEmpty();
  }

  @Test
  public void removeNode_antiparallelEdges() {
    assume().that(graphIsMutable()).isTrue();

    putEdge(N1, N2);
    putEdge(N2, N1);

    assertThat(graphAsMutableGraph.removeNode(N1)).isTrue();
    assertThat(graph.nodes()).containsExactly(N2);
    assertThat(graph.edges()).isEmpty();

    assertThat(graphAsMutableGraph.removeNode(N2)).isTrue();
    assertThat(graph.nodes()).isEmpty();
    assertThat(graph.edges()).isEmpty();
  }

  @Test
  public void removeNode_nodeNotPresent() {
    assume().that(graphIsMutable()).isTrue();

    addNode(N1);
    ImmutableSet<Integer> nodes = ImmutableSet.copyOf(graph.nodes());
    assertThat(graphAsMutableGraph.removeNode(NODE_NOT_IN_GRAPH)).isFalse();
    assertThat(graph.nodes()).containsExactlyElementsIn(nodes);
  }

  @Test
  public void removeNode_queryAfterRemoval() {
    assume().that(graphIsMutable()).isTrue();

    putEdge(N1, N2);
    putEdge(N2, N1);
    Set<Integer> n1AdjacentNodes = graph.adjacentNodes(N1);
    Set<Integer> n2AdjacentNodes = graph.adjacentNodes(N2);
    assertThat(graphAsMutableGraph.removeNode(N1)).isTrue();
    assertThat(n1AdjacentNodes).isEmpty();
    assertThat(n2AdjacentNodes).isEmpty();
    IllegalArgumentException e =
        assertThrows(IllegalArgumentException.class, () -> graph.adjacentNodes(N1));
    assertNodeNotInGraphErrorMessage(e);
  }

  @Test
  public void removeEdge_existingEdge() {
    assume().that(graphIsMutable()).isTrue();

    putEdge(N1, N2);
    assertThat(graph.successors(N1)).containsExactly(N2);
    assertThat(graph.predecessors(N2)).containsExactly(N1);
    assertThat(graphAsMutableGraph.removeEdge(N1, N2)).isTrue();
    assertThat(graphAsMutableGraph.removeEdge(N1, N2)).isFalse();
    assertThat(graph.successors(N1)).isEmpty();
    assertThat(graph.predecessors(N2)).isEmpty();
  }

  @Test
  public void removeEdge_oneOfMany() {
    assume().that(graphIsMutable()).isTrue();

    putEdge(N1, N2);
    putEdge(N1, N3);
    putEdge(N1, N4);
    assertThat(graphAsMutableGraph.removeEdge(N1, N3)).isTrue();
    assertThat(graph.adjacentNodes(N1)).containsExactly(N2, N4);
  }

  @Test
  public void removeEdge_nodeNotPresent() {
    assume().that(graphIsMutable()).isTrue();

    putEdge(N1, N2);
    assertThat(graphAsMutableGraph.removeEdge(N1, NODE_NOT_IN_GRAPH)).isFalse();
    assertThat(graph.successors(N1)).contains(N2);
  }

  @Test
  public void removeEdge_edgeNotPresent() {
    assume().that(graphIsMutable()).isTrue();

    putEdge(N1, N2);
    addNode(N3);

    assertThat(graphAsMutableGraph.removeEdge(N1, N3)).isFalse();
    assertThat(graph.successors(N1)).contains(N2);
  }
}