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 15 package com.google.common.collect; 16 17 import com.google.common.annotations.GwtIncompatible; 18 import java.util.Iterator; 19 import java.util.List; 20 import java.util.NoSuchElementException; 21 import junit.framework.TestCase; 22 23 /** 24 * Base class for {@link RangeSet} tests. 25 * 26 * @author Louis Wasserman 27 */ 28 @GwtIncompatible // TreeRangeSet 29 public abstract class AbstractRangeSetTest extends TestCase { testInvariants(RangeSet<?> rangeSet)30 public static void testInvariants(RangeSet<?> rangeSet) { 31 testInvariantsInternal(rangeSet); 32 testInvariantsInternal(rangeSet.complement()); 33 } 34 testInvariantsInternal(RangeSet<C> rangeSet)35 private static <C extends Comparable> void testInvariantsInternal(RangeSet<C> rangeSet) { 36 assertEquals(rangeSet.asRanges().isEmpty(), rangeSet.isEmpty()); 37 assertEquals(rangeSet.asDescendingSetOfRanges().isEmpty(), rangeSet.isEmpty()); 38 assertEquals(!rangeSet.asRanges().iterator().hasNext(), rangeSet.isEmpty()); 39 assertEquals(!rangeSet.asDescendingSetOfRanges().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 // test that the RangeSet's span is the span of all the ranges 56 Iterator<Range<C>> itr = rangeSet.asRanges().iterator(); 57 Range<C> expectedSpan = null; 58 if (itr.hasNext()) { 59 expectedSpan = itr.next(); 60 while (itr.hasNext()) { 61 expectedSpan = expectedSpan.span(itr.next()); 62 } 63 } 64 65 try { 66 Range<C> span = rangeSet.span(); 67 assertEquals(expectedSpan, span); 68 } catch (NoSuchElementException e) { 69 assertNull(expectedSpan); 70 } 71 72 // test that asDescendingSetOfRanges is the reverse of asRanges 73 assertEquals(Lists.reverse(asRanges), ImmutableList.copyOf(rangeSet.asDescendingSetOfRanges())); 74 } 75 } 76