1/*
2 * Copyright (C) 2011 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 * express or implied. See the License for the specific language governing permissions and
12 * limitations under the License.
13 */
14
15package com.google.common.collect;
16
17import com.google.common.annotations.GwtIncompatible;
18
19import junit.framework.TestCase;
20
21import java.util.Iterator;
22import java.util.List;
23import java.util.NoSuchElementException;
24
25/**
26 * Base class for {@link RangeSet} tests.
27 *
28 * @author Louis Wasserman
29 */
30@GwtIncompatible("TreeRangeSet")
31public abstract class AbstractRangeSetTest extends TestCase {
32  public static void testInvariants(RangeSet<?> rangeSet) {
33    testInvariantsInternal(rangeSet);
34    testInvariantsInternal(rangeSet.complement());
35  }
36
37  private static <C extends Comparable> void testInvariantsInternal(RangeSet<C> rangeSet) {
38    assertEquals(rangeSet.asRanges().isEmpty(), rangeSet.isEmpty());
39    assertEquals(!rangeSet.asRanges().iterator().hasNext(), rangeSet.isEmpty());
40
41    List<Range<C>> asRanges = ImmutableList.copyOf(rangeSet.asRanges());
42
43    // test that connected ranges are coalesced
44    for (int i = 0; i + 1 < asRanges.size(); i++) {
45      Range<C> range1 = asRanges.get(i);
46      Range<C> range2 = asRanges.get(i + 1);
47      assertFalse(range1.isConnected(range2));
48    }
49
50    // test that there are no empty ranges
51    for (Range<C> range : asRanges) {
52      assertFalse(range.isEmpty());
53    }
54
55    Iterator<Range<C>> itr = rangeSet.asRanges().iterator();
56    Range<C> expectedSpan = null;
57    if (itr.hasNext()) {
58      expectedSpan = itr.next();
59      while (itr.hasNext()) {
60        expectedSpan = expectedSpan.span(itr.next());
61      }
62    }
63
64    try {
65      Range<C> span = rangeSet.span();
66      assertEquals(expectedSpan, span);
67    } catch (NoSuchElementException e) {
68      assertNull(expectedSpan);
69    }
70  }
71}
72