code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2008 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.primitives; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Unit test for {@link Bytes}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class BytesTest extends TestCase { private static final byte[] EMPTY = {}; private static final byte[] ARRAY1 = {(byte) 1}; private static final byte[] ARRAY234 = {(byte) 2, (byte) 3, (byte) 4}; private static final byte[] VALUES = { Byte.MIN_VALUE, -1, 0, 1, Byte.MAX_VALUE }; public void testHashCode() { for (byte value : VALUES) { assertEquals(((Byte) value).hashCode(), Bytes.hashCode(value)); } } public void testContains() { assertFalse(Bytes.contains(EMPTY, (byte) 1)); assertFalse(Bytes.contains(ARRAY1, (byte) 2)); assertFalse(Bytes.contains(ARRAY234, (byte) 1)); assertTrue(Bytes.contains(new byte[] {(byte) -1}, (byte) -1)); assertTrue(Bytes.contains(ARRAY234, (byte) 2)); assertTrue(Bytes.contains(ARRAY234, (byte) 3)); assertTrue(Bytes.contains(ARRAY234, (byte) 4)); } public void testIndexOf() { assertEquals(-1, Bytes.indexOf(EMPTY, (byte) 1)); assertEquals(-1, Bytes.indexOf(ARRAY1, (byte) 2)); assertEquals(-1, Bytes.indexOf(ARRAY234, (byte) 1)); assertEquals(0, Bytes.indexOf( new byte[] {(byte) -1}, (byte) -1)); assertEquals(0, Bytes.indexOf(ARRAY234, (byte) 2)); assertEquals(1, Bytes.indexOf(ARRAY234, (byte) 3)); assertEquals(2, Bytes.indexOf(ARRAY234, (byte) 4)); assertEquals(1, Bytes.indexOf( new byte[] { (byte) 2, (byte) 3, (byte) 2, (byte) 3 }, (byte) 3)); } public void testIndexOf_arrayTarget() { assertEquals(0, Bytes.indexOf(EMPTY, EMPTY)); assertEquals(0, Bytes.indexOf(ARRAY234, EMPTY)); assertEquals(-1, Bytes.indexOf(EMPTY, ARRAY234)); assertEquals(-1, Bytes.indexOf(ARRAY234, ARRAY1)); assertEquals(-1, Bytes.indexOf(ARRAY1, ARRAY234)); assertEquals(0, Bytes.indexOf(ARRAY1, ARRAY1)); assertEquals(0, Bytes.indexOf(ARRAY234, ARRAY234)); assertEquals(0, Bytes.indexOf( ARRAY234, new byte[] { (byte) 2, (byte) 3 })); assertEquals(1, Bytes.indexOf( ARRAY234, new byte[] { (byte) 3, (byte) 4 })); assertEquals(1, Bytes.indexOf(ARRAY234, new byte[] { (byte) 3 })); assertEquals(2, Bytes.indexOf(ARRAY234, new byte[] { (byte) 4 })); assertEquals(1, Bytes.indexOf(new byte[] { (byte) 2, (byte) 3, (byte) 3, (byte) 3, (byte) 3 }, new byte[] { (byte) 3 } )); assertEquals(2, Bytes.indexOf( new byte[] { (byte) 2, (byte) 3, (byte) 2, (byte) 3, (byte) 4, (byte) 2, (byte) 3}, new byte[] { (byte) 2, (byte) 3, (byte) 4} )); assertEquals(1, Bytes.indexOf( new byte[] { (byte) 2, (byte) 2, (byte) 3, (byte) 4, (byte) 2, (byte) 3, (byte) 4}, new byte[] { (byte) 2, (byte) 3, (byte) 4} )); assertEquals(-1, Bytes.indexOf( new byte[] { (byte) 4, (byte) 3, (byte) 2}, new byte[] { (byte) 2, (byte) 3, (byte) 4} )); } public void testLastIndexOf() { assertEquals(-1, Bytes.lastIndexOf(EMPTY, (byte) 1)); assertEquals(-1, Bytes.lastIndexOf(ARRAY1, (byte) 2)); assertEquals(-1, Bytes.lastIndexOf(ARRAY234, (byte) 1)); assertEquals(0, Bytes.lastIndexOf( new byte[] {(byte) -1}, (byte) -1)); assertEquals(0, Bytes.lastIndexOf(ARRAY234, (byte) 2)); assertEquals(1, Bytes.lastIndexOf(ARRAY234, (byte) 3)); assertEquals(2, Bytes.lastIndexOf(ARRAY234, (byte) 4)); assertEquals(3, Bytes.lastIndexOf( new byte[] { (byte) 2, (byte) 3, (byte) 2, (byte) 3 }, (byte) 3)); } public void testConcat() { assertTrue(Arrays.equals(EMPTY, Bytes.concat())); assertTrue(Arrays.equals(EMPTY, Bytes.concat(EMPTY))); assertTrue(Arrays.equals(EMPTY, Bytes.concat(EMPTY, EMPTY, EMPTY))); assertTrue(Arrays.equals(ARRAY1, Bytes.concat(ARRAY1))); assertNotSame(ARRAY1, Bytes.concat(ARRAY1)); assertTrue(Arrays.equals(ARRAY1, Bytes.concat(EMPTY, ARRAY1, EMPTY))); assertTrue(Arrays.equals( new byte[] {(byte) 1, (byte) 1, (byte) 1}, Bytes.concat(ARRAY1, ARRAY1, ARRAY1))); assertTrue(Arrays.equals( new byte[] {(byte) 1, (byte) 2, (byte) 3, (byte) 4}, Bytes.concat(ARRAY1, ARRAY234))); } public void testEnsureCapacity() { assertSame(EMPTY, Bytes.ensureCapacity(EMPTY, 0, 1)); assertSame(ARRAY1, Bytes.ensureCapacity(ARRAY1, 0, 1)); assertSame(ARRAY1, Bytes.ensureCapacity(ARRAY1, 1, 1)); assertTrue(Arrays.equals( new byte[] {(byte) 1, (byte) 0, (byte) 0}, Bytes.ensureCapacity(ARRAY1, 2, 1))); } public void testEnsureCapacity_fail() { try { Bytes.ensureCapacity(ARRAY1, -1, 1); fail(); } catch (IllegalArgumentException expected) { } try { // notice that this should even fail when no growth was needed Bytes.ensureCapacity(ARRAY1, 1, -1); fail(); } catch (IllegalArgumentException expected) { } } public void testToArray() { // need explicit type parameter to avoid javac warning!? List<Byte> none = Arrays.<Byte>asList(); assertTrue(Arrays.equals(EMPTY, Bytes.toArray(none))); List<Byte> one = Arrays.asList((byte) 1); assertTrue(Arrays.equals(ARRAY1, Bytes.toArray(one))); byte[] array = {(byte) 0, (byte) 1, (byte) 0x55}; List<Byte> three = Arrays.asList((byte) 0, (byte) 1, (byte) 0x55); assertTrue(Arrays.equals(array, Bytes.toArray(three))); assertTrue(Arrays.equals(array, Bytes.toArray(Bytes.asList(array)))); } public void testToArray_threadSafe() { for (int delta : new int[] { +1, 0, -1 }) { for (int i = 0; i < VALUES.length; i++) { List<Byte> list = Bytes.asList(VALUES).subList(0, i); Collection<Byte> misleadingSize = Helpers.misleadingSizeCollection(delta); misleadingSize.addAll(list); byte[] arr = Bytes.toArray(misleadingSize); assertEquals(i, arr.length); for (int j = 0; j < i; j++) { assertEquals(VALUES[j], arr[j]); } } } } public void testToArray_withNull() { List<Byte> list = Arrays.asList((byte) 0, (byte) 1, null); try { Bytes.toArray(list); fail(); } catch (NullPointerException expected) { } } public void testToArray_withConversion() { byte[] array = {(byte) 0, (byte) 1, (byte) 2}; List<Byte> bytes = Arrays.asList((byte) 0, (byte) 1, (byte) 2); List<Short> shorts = Arrays.asList((short) 0, (short) 1, (short) 2); List<Integer> ints = Arrays.asList(0, 1, 2); List<Float> floats = Arrays.asList((float) 0, (float) 1, (float) 2); List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2); List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2); assertTrue(Arrays.equals(array, Bytes.toArray(bytes))); assertTrue(Arrays.equals(array, Bytes.toArray(shorts))); assertTrue(Arrays.equals(array, Bytes.toArray(ints))); assertTrue(Arrays.equals(array, Bytes.toArray(floats))); assertTrue(Arrays.equals(array, Bytes.toArray(longs))); assertTrue(Arrays.equals(array, Bytes.toArray(doubles))); } public void testAsList_isAView() { byte[] array = {(byte) 0, (byte) 1}; List<Byte> list = Bytes.asList(array); list.set(0, (byte) 2); assertTrue(Arrays.equals(new byte[] {(byte) 2, (byte) 1}, array)); array[1] = (byte) 3; assertEquals(Arrays.asList((byte) 2, (byte) 3), list); } public void testAsList_toArray_roundTrip() { byte[] array = { (byte) 0, (byte) 1, (byte) 2 }; List<Byte> list = Bytes.asList(array); byte[] newArray = Bytes.toArray(list); // Make sure it returned a copy list.set(0, (byte) 4); assertTrue(Arrays.equals( new byte[] { (byte) 0, (byte) 1, (byte) 2 }, newArray)); newArray[1] = (byte) 5; assertEquals((byte) 1, (byte) list.get(1)); } // This test stems from a real bug found by andrewk public void testAsList_subList_toArray_roundTrip() { byte[] array = { (byte) 0, (byte) 1, (byte) 2, (byte) 3 }; List<Byte> list = Bytes.asList(array); assertTrue(Arrays.equals(new byte[] { (byte) 1, (byte) 2 }, Bytes.toArray(list.subList(1, 3)))); assertTrue(Arrays.equals(new byte[] {}, Bytes.toArray(list.subList(2, 2)))); } public void testAsListEmpty() { assertSame(Collections.emptyList(), Bytes.asList(EMPTY)); } }
Java
/* * Copyright (C) 2008 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.primitives; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.TestListGenerator; import junit.framework.TestCase; import java.util.List; /** * Test suite covering {@link Chars#asList(char[])}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class CharArrayAsListTest extends TestCase { private static List<Character> asList(Character[] values) { char[] temp = new char[values.length]; for (int i = 0; i < values.length; i++) { temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize). } return Chars.asList(temp); } // Test generators. To let the GWT test suite generator access them, they need to be // public named classes with a public default constructor. public static final class CharsAsListGenerator extends TestCharListGenerator { @Override protected List<Character> create(Character[] elements) { return asList(elements); } } public static final class CharsAsListHeadSubListGenerator extends TestCharListGenerator { @Override protected List<Character> create(Character[] elements) { Character[] suffix = {Character.MIN_VALUE, Character.MAX_VALUE}; Character[] all = concat(elements, suffix); return asList(all).subList(0, elements.length); } } public static final class CharsAsListTailSubListGenerator extends TestCharListGenerator { @Override protected List<Character> create(Character[] elements) { Character[] prefix = {(char) 86, (char) 99}; Character[] all = concat(prefix, elements); return asList(all).subList(2, elements.length + 2); } } public static final class CharsAsListMiddleSubListGenerator extends TestCharListGenerator { @Override protected List<Character> create(Character[] elements) { Character[] prefix = {Character.MIN_VALUE, Character.MAX_VALUE}; Character[] suffix = {(char) 86, (char) 99}; Character[] all = concat(concat(prefix, elements), suffix); return asList(all).subList(2, elements.length + 2); } } private static Character[] concat(Character[] left, Character[] right) { Character[] result = new Character[left.length + right.length]; System.arraycopy(left, 0, result, 0, left.length); System.arraycopy(right, 0, result, left.length, right.length); return result; } public static abstract class TestCharListGenerator implements TestListGenerator<Character> { @Override public SampleElements<Character> samples() { return new SampleChars(); } @Override public List<Character> create(Object... elements) { Character[] array = new Character[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (Character) e; } return create(array); } /** * Creates a new collection containing the given elements; implement this * method instead of {@link #create(Object...)}. */ protected abstract List<Character> create(Character[] elements); @Override public Character[] createArray(int length) { return new Character[length]; } /** Returns the original element list, unchanged. */ @Override public List<Character> order(List<Character> insertionOrder) { return insertionOrder; } } public static class SampleChars extends SampleElements<Character> { public SampleChars() { super((char) 0, (char) 1, (char) 2, (char) 3, (char) 4); } } }
Java
/* * Copyright (C) 2008 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.primitives; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.TestListGenerator; import junit.framework.TestCase; import java.util.List; /** * Test suite covering {@link Shorts#asList(short[])}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class ShortArrayAsListTest extends TestCase { private static List<Short> asList(Short[] values) { short[] temp = new short[values.length]; for (short i = 0; i < values.length; i++) { temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize). } return Shorts.asList(temp); } // Test generators. To let the GWT test suite generator access them, they need to be // public named classes with a public default constructor. public static final class ShortsAsListGenerator extends TestShortListGenerator { @Override protected List<Short> create(Short[] elements) { return asList(elements); } } public static final class ShortsAsListHeadSubListGenerator extends TestShortListGenerator { @Override protected List<Short> create(Short[] elements) { Short[] suffix = {Short.MIN_VALUE, Short.MAX_VALUE}; Short[] all = concat(elements, suffix); return asList(all).subList(0, elements.length); } } public static final class ShortsAsListTailSubListGenerator extends TestShortListGenerator { @Override protected List<Short> create(Short[] elements) { Short[] prefix = {(short) 86, (short) 99}; Short[] all = concat(prefix, elements); return asList(all).subList(2, elements.length + 2); } } public static final class ShortsAsListMiddleSubListGenerator extends TestShortListGenerator { @Override protected List<Short> create(Short[] elements) { Short[] prefix = {Short.MIN_VALUE, Short.MAX_VALUE}; Short[] suffix = {(short) 86, (short) 99}; Short[] all = concat(concat(prefix, elements), suffix); return asList(all).subList(2, elements.length + 2); } } private static Short[] concat(Short[] left, Short[] right) { Short[] result = new Short[left.length + right.length]; System.arraycopy(left, 0, result, 0, left.length); System.arraycopy(right, 0, result, left.length, right.length); return result; } public static abstract class TestShortListGenerator implements TestListGenerator<Short> { @Override public SampleElements<Short> samples() { return new SampleShorts(); } @Override public List<Short> create(Object... elements) { Short[] array = new Short[elements.length]; short i = 0; for (Object e : elements) { array[i++] = (Short) e; } return create(array); } /** * Creates a new collection containing the given elements; implement this * method instead of {@link #create(Object...)}. */ protected abstract List<Short> create(Short[] elements); @Override public Short[] createArray(int length) { return new Short[length]; } /** Returns the original element list, unchanged. */ @Override public List<Short> order(List<Short> insertionOrder) { return insertionOrder; } } public static class SampleShorts extends SampleElements<Short> { public SampleShorts() { super((short) 0, (short) 1, (short) 2, (short) 3, (short) 4); } } }
Java
/* * Copyright (C) 2008 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.primitives; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Unit test for {@link Chars}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) @SuppressWarnings("cast") // redundant casts are intentional and harmless public class CharsTest extends TestCase { private static final char[] EMPTY = {}; private static final char[] ARRAY1 = {(char) 1}; private static final char[] ARRAY234 = {(char) 2, (char) 3, (char) 4}; private static final char LEAST = Character.MIN_VALUE; private static final char GREATEST = Character.MAX_VALUE; private static final char[] VALUES = {LEAST, 'a', '\u00e0', '\udcaa', GREATEST}; public void testHashCode() { for (char value : VALUES) { assertEquals(((Character) value).hashCode(), Chars.hashCode(value)); } } public void testCheckedCast() { for (char value : VALUES) { assertEquals(value, Chars.checkedCast((long) value)); } assertCastFails(GREATEST + 1L); assertCastFails(LEAST - 1L); assertCastFails(Long.MAX_VALUE); assertCastFails(Long.MIN_VALUE); } public void testSaturatedCast() { for (char value : VALUES) { assertEquals(value, Chars.saturatedCast((long) value)); } assertEquals(GREATEST, Chars.saturatedCast(GREATEST + 1L)); assertEquals(LEAST, Chars.saturatedCast(LEAST - 1L)); assertEquals(GREATEST, Chars.saturatedCast(Long.MAX_VALUE)); assertEquals(LEAST, Chars.saturatedCast(Long.MIN_VALUE)); } private void assertCastFails(long value) { try { Chars.checkedCast(value); fail("Cast to char should have failed: " + value); } catch (IllegalArgumentException ex) { assertTrue(value + " not found in exception text: " + ex.getMessage(), ex.getMessage().contains(String.valueOf(value))); } } public void testCompare() { for (char x : VALUES) { for (char y : VALUES) { // note: spec requires only that the sign is the same assertEquals(x + ", " + y, Character.valueOf(x).compareTo(y), Chars.compare(x, y)); } } } public void testContains() { assertFalse(Chars.contains(EMPTY, (char) 1)); assertFalse(Chars.contains(ARRAY1, (char) 2)); assertFalse(Chars.contains(ARRAY234, (char) 1)); assertTrue(Chars.contains(new char[] {(char) -1}, (char) -1)); assertTrue(Chars.contains(ARRAY234, (char) 2)); assertTrue(Chars.contains(ARRAY234, (char) 3)); assertTrue(Chars.contains(ARRAY234, (char) 4)); } public void testIndexOf() { assertEquals(-1, Chars.indexOf(EMPTY, (char) 1)); assertEquals(-1, Chars.indexOf(ARRAY1, (char) 2)); assertEquals(-1, Chars.indexOf(ARRAY234, (char) 1)); assertEquals(0, Chars.indexOf( new char[] {(char) -1}, (char) -1)); assertEquals(0, Chars.indexOf(ARRAY234, (char) 2)); assertEquals(1, Chars.indexOf(ARRAY234, (char) 3)); assertEquals(2, Chars.indexOf(ARRAY234, (char) 4)); assertEquals(1, Chars.indexOf( new char[] { (char) 2, (char) 3, (char) 2, (char) 3 }, (char) 3)); } public void testIndexOf_arrayTarget() { assertEquals(0, Chars.indexOf(EMPTY, EMPTY)); assertEquals(0, Chars.indexOf(ARRAY234, EMPTY)); assertEquals(-1, Chars.indexOf(EMPTY, ARRAY234)); assertEquals(-1, Chars.indexOf(ARRAY234, ARRAY1)); assertEquals(-1, Chars.indexOf(ARRAY1, ARRAY234)); assertEquals(0, Chars.indexOf(ARRAY1, ARRAY1)); assertEquals(0, Chars.indexOf(ARRAY234, ARRAY234)); assertEquals(0, Chars.indexOf( ARRAY234, new char[] { (char) 2, (char) 3 })); assertEquals(1, Chars.indexOf( ARRAY234, new char[] { (char) 3, (char) 4 })); assertEquals(1, Chars.indexOf(ARRAY234, new char[] { (char) 3 })); assertEquals(2, Chars.indexOf(ARRAY234, new char[] { (char) 4 })); assertEquals(1, Chars.indexOf(new char[] { (char) 2, (char) 3, (char) 3, (char) 3, (char) 3 }, new char[] { (char) 3 } )); assertEquals(2, Chars.indexOf( new char[] { (char) 2, (char) 3, (char) 2, (char) 3, (char) 4, (char) 2, (char) 3}, new char[] { (char) 2, (char) 3, (char) 4} )); assertEquals(1, Chars.indexOf( new char[] { (char) 2, (char) 2, (char) 3, (char) 4, (char) 2, (char) 3, (char) 4}, new char[] { (char) 2, (char) 3, (char) 4} )); assertEquals(-1, Chars.indexOf( new char[] { (char) 4, (char) 3, (char) 2}, new char[] { (char) 2, (char) 3, (char) 4} )); } public void testLastIndexOf() { assertEquals(-1, Chars.lastIndexOf(EMPTY, (char) 1)); assertEquals(-1, Chars.lastIndexOf(ARRAY1, (char) 2)); assertEquals(-1, Chars.lastIndexOf(ARRAY234, (char) 1)); assertEquals(0, Chars.lastIndexOf( new char[] {(char) -1}, (char) -1)); assertEquals(0, Chars.lastIndexOf(ARRAY234, (char) 2)); assertEquals(1, Chars.lastIndexOf(ARRAY234, (char) 3)); assertEquals(2, Chars.lastIndexOf(ARRAY234, (char) 4)); assertEquals(3, Chars.lastIndexOf( new char[] { (char) 2, (char) 3, (char) 2, (char) 3 }, (char) 3)); } public void testMax_noArgs() { try { Chars.max(); fail(); } catch (IllegalArgumentException expected) { } } public void testMax() { assertEquals(LEAST, Chars.max(LEAST)); assertEquals(GREATEST, Chars.max(GREATEST)); assertEquals((char) 9, Chars.max( (char) 8, (char) 6, (char) 7, (char) 5, (char) 3, (char) 0, (char) 9)); } public void testMin_noArgs() { try { Chars.min(); fail(); } catch (IllegalArgumentException expected) { } } public void testMin() { assertEquals(LEAST, Chars.min(LEAST)); assertEquals(GREATEST, Chars.min(GREATEST)); assertEquals((char) 0, Chars.min( (char) 8, (char) 6, (char) 7, (char) 5, (char) 3, (char) 0, (char) 9)); } public void testConcat() { assertTrue(Arrays.equals(EMPTY, Chars.concat())); assertTrue(Arrays.equals(EMPTY, Chars.concat(EMPTY))); assertTrue(Arrays.equals(EMPTY, Chars.concat(EMPTY, EMPTY, EMPTY))); assertTrue(Arrays.equals(ARRAY1, Chars.concat(ARRAY1))); assertNotSame(ARRAY1, Chars.concat(ARRAY1)); assertTrue(Arrays.equals(ARRAY1, Chars.concat(EMPTY, ARRAY1, EMPTY))); assertTrue(Arrays.equals( new char[] {(char) 1, (char) 1, (char) 1}, Chars.concat(ARRAY1, ARRAY1, ARRAY1))); assertTrue(Arrays.equals( new char[] {(char) 1, (char) 2, (char) 3, (char) 4}, Chars.concat(ARRAY1, ARRAY234))); } public void testEnsureCapacity() { assertSame(EMPTY, Chars.ensureCapacity(EMPTY, 0, 1)); assertSame(ARRAY1, Chars.ensureCapacity(ARRAY1, 0, 1)); assertSame(ARRAY1, Chars.ensureCapacity(ARRAY1, 1, 1)); assertTrue(Arrays.equals( new char[] {(char) 1, (char) 0, (char) 0}, Chars.ensureCapacity(ARRAY1, 2, 1))); } public void testEnsureCapacity_fail() { try { Chars.ensureCapacity(ARRAY1, -1, 1); fail(); } catch (IllegalArgumentException expected) { } try { // notice that this should even fail when no growth was needed Chars.ensureCapacity(ARRAY1, 1, -1); fail(); } catch (IllegalArgumentException expected) { } } public void testJoin() { assertEquals("", Chars.join(",", EMPTY)); assertEquals("1", Chars.join(",", '1')); assertEquals("1,2", Chars.join(",", '1', '2')); assertEquals("123", Chars.join("", '1', '2', '3')); } public void testLexicographicalComparator() { List<char[]> ordered = Arrays.asList( new char[] {}, new char[] {LEAST}, new char[] {LEAST, LEAST}, new char[] {LEAST, (char) 1}, new char[] {(char) 1}, new char[] {(char) 1, LEAST}, new char[] {GREATEST, GREATEST - (char) 1}, new char[] {GREATEST, GREATEST}, new char[] {GREATEST, GREATEST, GREATEST}); Comparator<char[]> comparator = Chars.lexicographicalComparator(); Helpers.testComparator(comparator, ordered); } public void testToArray() { // need explicit type parameter to avoid javac warning!? List<Character> none = Arrays.<Character>asList(); assertTrue(Arrays.equals(EMPTY, Chars.toArray(none))); List<Character> one = Arrays.asList((char) 1); assertTrue(Arrays.equals(ARRAY1, Chars.toArray(one))); char[] array = {(char) 0, (char) 1, 'A'}; List<Character> three = Arrays.asList((char) 0, (char) 1, 'A'); assertTrue(Arrays.equals(array, Chars.toArray(three))); assertTrue(Arrays.equals(array, Chars.toArray(Chars.asList(array)))); } public void testToArray_threadSafe() { for (int delta : new int[] { +1, 0, -1 }) { for (int i = 0; i < VALUES.length; i++) { List<Character> list = Chars.asList(VALUES).subList(0, i); Collection<Character> misleadingSize = Helpers.misleadingSizeCollection(delta); misleadingSize.addAll(list); char[] arr = Chars.toArray(misleadingSize); assertEquals(i, arr.length); for (int j = 0; j < i; j++) { assertEquals(VALUES[j], arr[j]); } } } } public void testToArray_withNull() { List<Character> list = Arrays.asList((char) 0, (char) 1, null); try { Chars.toArray(list); fail(); } catch (NullPointerException expected) { } } public void testAsList_isAView() { char[] array = {(char) 0, (char) 1}; List<Character> list = Chars.asList(array); list.set(0, (char) 2); assertTrue(Arrays.equals(new char[] {(char) 2, (char) 1}, array)); array[1] = (char) 3; assertEquals(Arrays.asList((char) 2, (char) 3), list); } public void testAsList_toArray_roundTrip() { char[] array = { (char) 0, (char) 1, (char) 2 }; List<Character> list = Chars.asList(array); char[] newArray = Chars.toArray(list); // Make sure it returned a copy list.set(0, (char) 4); assertTrue(Arrays.equals( new char[] { (char) 0, (char) 1, (char) 2 }, newArray)); newArray[1] = (char) 5; assertEquals((char) 1, (char) list.get(1)); } // This test stems from a real bug found by andrewk public void testAsList_subList_toArray_roundTrip() { char[] array = { (char) 0, (char) 1, (char) 2, (char) 3 }; List<Character> list = Chars.asList(array); assertTrue(Arrays.equals(new char[] { (char) 1, (char) 2 }, Chars.toArray(list.subList(1, 3)))); assertTrue(Arrays.equals(new char[] {}, Chars.toArray(list.subList(2, 2)))); } public void testAsListEmpty() { assertSame(Collections.emptyList(), Chars.asList(EMPTY)); } }
Java
/* * Copyright (C) 2008 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.primitives; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Unit test for {@link Booleans}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class BooleansTest extends TestCase { private static final boolean[] EMPTY = {}; private static final boolean[] ARRAY_FALSE = {false}; private static final boolean[] ARRAY_TRUE = {true}; private static final boolean[] ARRAY_FALSE_FALSE = {false, false}; private static final boolean[] ARRAY_FALSE_TRUE = {false, true}; private static final boolean[] VALUES = {false, true}; public void testHashCode() { assertEquals(Boolean.TRUE.hashCode(), Booleans.hashCode(true)); assertEquals(Boolean.FALSE.hashCode(), Booleans.hashCode(false)); } public void testCompare() { for (boolean x : VALUES) { for (boolean y : VALUES) { // note: spec requires only that the sign is the same assertEquals(x + ", " + y, Boolean.valueOf(x).compareTo(y), Booleans.compare(x, y)); } } } public void testContains() { assertFalse(Booleans.contains(EMPTY, false)); assertFalse(Booleans.contains(ARRAY_FALSE, true)); assertTrue(Booleans.contains(ARRAY_FALSE, false)); assertTrue(Booleans.contains(ARRAY_FALSE_TRUE, false)); assertTrue(Booleans.contains(ARRAY_FALSE_TRUE, true)); } public void testIndexOf() { assertEquals(-1, Booleans.indexOf(EMPTY, ARRAY_FALSE)); assertEquals(-1, Booleans.indexOf(ARRAY_FALSE, ARRAY_FALSE_TRUE)); assertEquals(0, Booleans.indexOf(ARRAY_FALSE_FALSE, ARRAY_FALSE)); assertEquals(0, Booleans.indexOf(ARRAY_FALSE, ARRAY_FALSE)); assertEquals(0, Booleans.indexOf(ARRAY_FALSE_TRUE, ARRAY_FALSE)); assertEquals(1, Booleans.indexOf(ARRAY_FALSE_TRUE, ARRAY_TRUE)); assertEquals(0, Booleans.indexOf(ARRAY_TRUE, new boolean[0])); } public void testIndexOf_arrays() { assertEquals(-1, Booleans.indexOf(EMPTY, false)); assertEquals(-1, Booleans.indexOf(ARRAY_FALSE, true)); assertEquals(-1, Booleans.indexOf(ARRAY_FALSE_FALSE, true)); assertEquals(0, Booleans.indexOf(ARRAY_FALSE, false)); assertEquals(0, Booleans.indexOf(ARRAY_FALSE_TRUE, false)); assertEquals(1, Booleans.indexOf(ARRAY_FALSE_TRUE, true)); assertEquals(2, Booleans.indexOf(new boolean[] {false, false, true}, true)); } public void testLastIndexOf() { assertEquals(-1, Booleans.lastIndexOf(EMPTY, false)); assertEquals(-1, Booleans.lastIndexOf(ARRAY_FALSE, true)); assertEquals(-1, Booleans.lastIndexOf(ARRAY_FALSE_FALSE, true)); assertEquals(0, Booleans.lastIndexOf(ARRAY_FALSE, false)); assertEquals(0, Booleans.lastIndexOf(ARRAY_FALSE_TRUE, false)); assertEquals(1, Booleans.lastIndexOf(ARRAY_FALSE_TRUE, true)); assertEquals(2, Booleans.lastIndexOf(new boolean[] {false, true, true}, true)); } public void testConcat() { assertTrue(Arrays.equals(EMPTY, Booleans.concat())); assertTrue(Arrays.equals(EMPTY, Booleans.concat(EMPTY))); assertTrue(Arrays.equals(EMPTY, Booleans.concat(EMPTY, EMPTY, EMPTY))); assertTrue(Arrays.equals(ARRAY_FALSE, Booleans.concat(ARRAY_FALSE))); assertNotSame(ARRAY_FALSE, Booleans.concat(ARRAY_FALSE)); assertTrue(Arrays.equals(ARRAY_FALSE, Booleans.concat(EMPTY, ARRAY_FALSE, EMPTY))); assertTrue(Arrays.equals( new boolean[] {false, false, false}, Booleans.concat(ARRAY_FALSE, ARRAY_FALSE, ARRAY_FALSE))); assertTrue(Arrays.equals( new boolean[] {false, false, true}, Booleans.concat(ARRAY_FALSE, ARRAY_FALSE_TRUE))); } public void testEnsureCapacity() { assertSame(EMPTY, Booleans.ensureCapacity(EMPTY, 0, 1)); assertSame(ARRAY_FALSE, Booleans.ensureCapacity(ARRAY_FALSE, 0, 1)); assertSame(ARRAY_FALSE, Booleans.ensureCapacity(ARRAY_FALSE, 1, 1)); assertTrue(Arrays.equals( new boolean[] {true, false, false}, Booleans.ensureCapacity(new boolean[] {true}, 2, 1))); } public void testEnsureCapacity_fail() { try { Booleans.ensureCapacity(ARRAY_FALSE, -1, 1); fail(); } catch (IllegalArgumentException expected) { } try { // notice that this should even fail when no growth was needed Booleans.ensureCapacity(ARRAY_FALSE, 1, -1); fail(); } catch (IllegalArgumentException expected) { } } public void testJoin() { assertEquals("", Booleans.join(",", EMPTY)); assertEquals("false", Booleans.join(",", ARRAY_FALSE)); assertEquals("false,true", Booleans.join(",", false, true)); assertEquals("falsetruefalse", Booleans.join("", false, true, false)); } public void testLexicographicalComparator() { List<boolean[]> ordered = Arrays.asList( new boolean[] {}, new boolean[] {false}, new boolean[] {false, false}, new boolean[] {false, true}, new boolean[] {true}, new boolean[] {true, false}, new boolean[] {true, true}, new boolean[] {true, true, true}); Comparator<boolean[]> comparator = Booleans.lexicographicalComparator(); Helpers.testComparator(comparator, ordered); } public void testToArray() { // need explicit type parameter to avoid javac warning!? List<Boolean> none = Arrays.<Boolean>asList(); assertTrue(Arrays.equals(EMPTY, Booleans.toArray(none))); List<Boolean> one = Arrays.asList(false); assertTrue(Arrays.equals(ARRAY_FALSE, Booleans.toArray(one))); boolean[] array = {false, false, true}; List<Boolean> three = Arrays.asList(false, false, true); assertTrue(Arrays.equals(array, Booleans.toArray(three))); assertTrue(Arrays.equals(array, Booleans.toArray(Booleans.asList(array)))); } public void testToArray_threadSafe() { // Only for booleans, we lengthen VALUES boolean[] VALUES = BooleansTest.VALUES; VALUES = Booleans.concat(VALUES, VALUES); for (int delta : new int[] { +1, 0, -1 }) { for (int i = 0; i < VALUES.length; i++) { List<Boolean> list = Booleans.asList(VALUES).subList(0, i); Collection<Boolean> misleadingSize = Helpers.misleadingSizeCollection(delta); misleadingSize.addAll(list); boolean[] arr = Booleans.toArray(misleadingSize); assertEquals(i, arr.length); for (int j = 0; j < i; j++) { assertEquals(VALUES[j], arr[j]); } } } } public void testToArray_withNull() { List<Boolean> list = Arrays.asList(false, true, null); try { Booleans.toArray(list); fail(); } catch (NullPointerException expected) { } } public void testAsListIsEmpty() { assertTrue(Booleans.asList(EMPTY).isEmpty()); assertFalse(Booleans.asList(ARRAY_FALSE).isEmpty()); } public void testAsListSize() { assertEquals(0, Booleans.asList(EMPTY).size()); assertEquals(1, Booleans.asList(ARRAY_FALSE).size()); assertEquals(2, Booleans.asList(ARRAY_FALSE_TRUE).size()); } public void testAsListIndexOf() { assertEquals(-1, Booleans.asList(EMPTY).indexOf("wrong type")); assertEquals(-1, Booleans.asList(EMPTY).indexOf(true)); assertEquals(-1, Booleans.asList(ARRAY_FALSE).indexOf(true)); assertEquals(0, Booleans.asList(ARRAY_FALSE).indexOf(false)); assertEquals(1, Booleans.asList(ARRAY_FALSE_TRUE).indexOf(true)); } public void testAsListLastIndexOf() { assertEquals(-1, Booleans.asList(EMPTY).indexOf("wrong type")); assertEquals(-1, Booleans.asList(EMPTY).indexOf(true)); assertEquals(-1, Booleans.asList(ARRAY_FALSE).lastIndexOf(true)); assertEquals(1, Booleans.asList(ARRAY_FALSE_TRUE).lastIndexOf(true)); assertEquals(1, Booleans.asList(ARRAY_FALSE_FALSE).lastIndexOf(false)); } public void testAsListContains() { assertFalse(Booleans.asList(EMPTY).contains("wrong type")); assertFalse(Booleans.asList(EMPTY).contains(true)); assertFalse(Booleans.asList(ARRAY_FALSE).contains(true)); assertTrue(Booleans.asList(ARRAY_TRUE).contains(true)); assertTrue(Booleans.asList(ARRAY_FALSE_TRUE).contains(false)); assertTrue(Booleans.asList(ARRAY_FALSE_TRUE).contains(true)); } public void testAsListEquals() { assertEquals(Booleans.asList(EMPTY), Collections.emptyList()); assertEquals(Booleans.asList(ARRAY_FALSE), Booleans.asList(ARRAY_FALSE)); assertFalse(Booleans.asList(ARRAY_FALSE).equals(ARRAY_FALSE)); assertFalse(Booleans.asList(ARRAY_FALSE).equals(null)); assertFalse(Booleans.asList(ARRAY_FALSE).equals(Booleans.asList(ARRAY_FALSE_TRUE))); assertFalse(Booleans.asList(ARRAY_FALSE_FALSE).equals(Booleans.asList(ARRAY_FALSE_TRUE))); assertEquals(1, Booleans.asList(ARRAY_FALSE_TRUE).lastIndexOf(true)); List<Boolean> reference = Booleans.asList(ARRAY_FALSE); assertEquals(Booleans.asList(ARRAY_FALSE), reference); assertEquals(reference, reference); } public void testAsListHashcode() { assertEquals(1, Booleans.asList(EMPTY).hashCode()); assertEquals(Booleans.asList(ARRAY_FALSE).hashCode(), Booleans.asList(ARRAY_FALSE).hashCode()); List<Boolean> reference = Booleans.asList(ARRAY_FALSE); assertEquals(Booleans.asList(ARRAY_FALSE).hashCode(), reference.hashCode()); } public void testAsListToString() { assertEquals("[false]", Booleans.asList(ARRAY_FALSE).toString()); assertEquals("[false, true]", Booleans.asList(ARRAY_FALSE_TRUE).toString()); } public void testAsListSet() { List<Boolean> list = Booleans.asList(ARRAY_FALSE); assertFalse(list.set(0, true)); assertTrue(list.set(0, false)); try { list.set(0, null); fail(); } catch (NullPointerException expected) { } try { list.set(1, true); fail(); } catch (IndexOutOfBoundsException expected) { } } }
Java
/* * Copyright (C) 2008 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.primitives; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.TestListGenerator; import junit.framework.TestCase; import java.util.List; /** * Test suite covering {@link Ints#asList(int[])}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) @SuppressWarnings("cast") // redundant casts are intentional and harmless public class IntArrayAsListTest extends TestCase { private static List<Integer> asList(Integer[] values) { int[] temp = new int[values.length]; for (int i = 0; i < values.length; i++) { temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize). } return Ints.asList(temp); } // Test generators. To let the GWT test suite generator access them, they need to be // public named classes with a public default constructor. public static final class IntsAsListGenerator extends TestIntegerListGenerator { @Override protected List<Integer> create(Integer[] elements) { return asList(elements); } } public static final class IntsAsListHeadSubListGenerator extends TestIntegerListGenerator { @Override protected List<Integer> create(Integer[] elements) { Integer[] suffix = {Integer.MIN_VALUE, Integer.MAX_VALUE}; Integer[] all = concat(elements, suffix); return asList(all).subList(0, elements.length); } } public static final class IntsAsListTailSubListGenerator extends TestIntegerListGenerator { @Override protected List<Integer> create(Integer[] elements) { Integer[] prefix = {(int) 86, (int) 99}; Integer[] all = concat(prefix, elements); return asList(all).subList(2, elements.length + 2); } } public static final class IntsAsListMiddleSubListGenerator extends TestIntegerListGenerator { @Override protected List<Integer> create(Integer[] elements) { Integer[] prefix = {Integer.MIN_VALUE, Integer.MAX_VALUE}; Integer[] suffix = {(int) 86, (int) 99}; Integer[] all = concat(concat(prefix, elements), suffix); return asList(all).subList(2, elements.length + 2); } } private static Integer[] concat(Integer[] left, Integer[] right) { Integer[] result = new Integer[left.length + right.length]; System.arraycopy(left, 0, result, 0, left.length); System.arraycopy(right, 0, result, left.length, right.length); return result; } public static abstract class TestIntegerListGenerator implements TestListGenerator<Integer> { @Override public SampleElements<Integer> samples() { return new SampleIntegers(); } @Override public List<Integer> create(Object... elements) { Integer[] array = new Integer[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (Integer) e; } return create(array); } /** * Creates a new collection containing the given elements; implement this * method instead of {@link #create(Object...)}. */ protected abstract List<Integer> create(Integer[] elements); @Override public Integer[] createArray(int length) { return new Integer[length]; } /** Returns the original element list, unchanged. */ @Override public List<Integer> order(List<Integer> insertionOrder) { return insertionOrder; } } public static class SampleIntegers extends SampleElements<Integer> { public SampleIntegers() { super((int) 0, (int) 1, (int) 2, (int) 3, (int) 4); } } }
Java
/* * Copyright (C) 2011 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.primitives; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableSet; import junit.framework.TestCase; import java.math.BigInteger; /** * Tests for {@code UnsignedLong}. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class UnsignedLongTest extends TestCase { private static final ImmutableSet<Long> TEST_LONGS; private static final ImmutableSet<BigInteger> TEST_BIG_INTEGERS; static { ImmutableSet.Builder<Long> testLongsBuilder = ImmutableSet.builder(); ImmutableSet.Builder<BigInteger> testBigIntegersBuilder = ImmutableSet.builder(); for (long i = -3; i <= 3; i++) { testLongsBuilder .add(i) .add(Long.MAX_VALUE + i) .add(Long.MIN_VALUE + i) .add(Integer.MIN_VALUE + i) .add(Integer.MAX_VALUE + i); BigInteger bigI = BigInteger.valueOf(i); testBigIntegersBuilder .add(bigI) .add(BigInteger.valueOf(Long.MAX_VALUE).add(bigI)) .add(BigInteger.valueOf(Long.MIN_VALUE).add(bigI)) .add(BigInteger.valueOf(Integer.MAX_VALUE).add(bigI)) .add(BigInteger.valueOf(Integer.MIN_VALUE).add(bigI)) .add(BigInteger.ONE.shiftLeft(63).add(bigI)) .add(BigInteger.ONE.shiftLeft(64).add(bigI)); } TEST_LONGS = testLongsBuilder.build(); TEST_BIG_INTEGERS = testBigIntegersBuilder.build(); } public void testAsUnsignedAndLongValueAreInverses() { for (long value : TEST_LONGS) { assertEquals( UnsignedLongs.toString(value), value, UnsignedLong.fromLongBits(value).longValue()); } } public void testAsUnsignedBigIntegerValue() { for (long value : TEST_LONGS) { BigInteger expected = (value >= 0) ? BigInteger.valueOf(value) : BigInteger.valueOf(value).add(BigInteger.ZERO.setBit(64)); assertEquals(UnsignedLongs.toString(value), expected, UnsignedLong.fromLongBits(value).bigIntegerValue()); } } public void testValueOfLong() { for (long value : TEST_LONGS) { boolean expectSuccess = value >= 0; try { assertEquals(value, UnsignedLong.valueOf(value).longValue()); assertTrue(expectSuccess); } catch (IllegalArgumentException e) { assertFalse(expectSuccess); } } } public void testValueOfBigInteger() { BigInteger min = BigInteger.ZERO; BigInteger max = UnsignedLong.MAX_VALUE.bigIntegerValue(); for (BigInteger big : TEST_BIG_INTEGERS) { boolean expectSuccess = big.compareTo(min) >= 0 && big.compareTo(max) <= 0; try { assertEquals(big, UnsignedLong.valueOf(big).bigIntegerValue()); assertTrue(expectSuccess); } catch (IllegalArgumentException e) { assertFalse(expectSuccess); } } } public void testToString() { for (long value : TEST_LONGS) { UnsignedLong unsignedValue = UnsignedLong.fromLongBits(value); assertEquals(unsignedValue.bigIntegerValue().toString(), unsignedValue.toString()); } } public void testToStringRadixQuick() { int[] radices = {2, 3, 5, 7, 10, 12, 16, 21, 31, 36}; for (int radix : radices) { for (long l : TEST_LONGS) { UnsignedLong value = UnsignedLong.fromLongBits(l); assertEquals(value.bigIntegerValue().toString(radix), value.toString(radix)); } } } public void testFloatValue() { for (long value : TEST_LONGS) { UnsignedLong unsignedValue = UnsignedLong.fromLongBits(value); assertEquals(unsignedValue.bigIntegerValue().floatValue(), unsignedValue.floatValue()); } } public void testDoubleValue() { for (long value : TEST_LONGS) { UnsignedLong unsignedValue = UnsignedLong.fromLongBits(value); assertEquals(unsignedValue.bigIntegerValue().doubleValue(), unsignedValue.doubleValue()); } } public void testPlus() { for (long a : TEST_LONGS) { for (long b : TEST_LONGS) { UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a); UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b); long expected = aUnsigned .bigIntegerValue() .add(bUnsigned.bigIntegerValue()) .longValue(); UnsignedLong unsignedSum = aUnsigned.plus(bUnsigned); assertEquals(expected, unsignedSum.longValue()); } } } public void testMinus() { for (long a : TEST_LONGS) { for (long b : TEST_LONGS) { UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a); UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b); long expected = aUnsigned .bigIntegerValue() .subtract(bUnsigned.bigIntegerValue()) .longValue(); UnsignedLong unsignedSub = aUnsigned.minus(bUnsigned); assertEquals(expected, unsignedSub.longValue()); } } } public void testTimes() { for (long a : TEST_LONGS) { for (long b : TEST_LONGS) { UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a); UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b); long expected = aUnsigned .bigIntegerValue() .multiply(bUnsigned.bigIntegerValue()) .longValue(); UnsignedLong unsignedMul = aUnsigned.times(bUnsigned); assertEquals(expected, unsignedMul.longValue()); } } } public void testDividedBy() { for (long a : TEST_LONGS) { for (long b : TEST_LONGS) { if (b != 0) { UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a); UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b); long expected = aUnsigned .bigIntegerValue() .divide(bUnsigned.bigIntegerValue()) .longValue(); UnsignedLong unsignedDiv = aUnsigned.dividedBy(bUnsigned); assertEquals(expected, unsignedDiv.longValue()); } } } } @SuppressWarnings("ReturnValueIgnored") public void testDivideByZeroThrows() { for (long a : TEST_LONGS) { try { UnsignedLong.fromLongBits(a).dividedBy(UnsignedLong.ZERO); fail("Expected ArithmeticException"); } catch (ArithmeticException expected) {} } } public void testMod() { for (long a : TEST_LONGS) { for (long b : TEST_LONGS) { if (b != 0) { UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a); UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b); long expected = aUnsigned .bigIntegerValue() .remainder(bUnsigned.bigIntegerValue()) .longValue(); UnsignedLong unsignedRem = aUnsigned.mod(bUnsigned); assertEquals(expected, unsignedRem.longValue()); } } } } @SuppressWarnings("ReturnValueIgnored") public void testModByZero() { for (long a : TEST_LONGS) { try { UnsignedLong.fromLongBits(a).mod(UnsignedLong.ZERO); fail("Expected ArithmeticException"); } catch (ArithmeticException expected) {} } } public void testCompare() { for (long a : TEST_LONGS) { for (long b : TEST_LONGS) { UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a); UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b); assertEquals(aUnsigned.bigIntegerValue().compareTo(bUnsigned.bigIntegerValue()), aUnsigned.compareTo(bUnsigned)); } } } public void testIntValue() { for (long a : TEST_LONGS) { UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a); int intValue = aUnsigned.bigIntegerValue().intValue(); assertEquals(intValue, aUnsigned.intValue()); } } }
Java
/* * Copyright (C) 2011 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.math; import static com.google.common.math.MathTesting.ALL_BIGINTEGER_CANDIDATES; import static com.google.common.math.MathTesting.ALL_ROUNDING_MODES; import static com.google.common.math.MathTesting.POSITIVE_BIGINTEGER_CANDIDATES; import static java.math.BigInteger.ONE; import static java.math.BigInteger.ZERO; import static java.math.RoundingMode.CEILING; import static java.math.RoundingMode.DOWN; import static java.math.RoundingMode.FLOOR; import static java.math.RoundingMode.HALF_DOWN; import static java.math.RoundingMode.HALF_EVEN; import static java.math.RoundingMode.HALF_UP; import static java.math.RoundingMode.UNNECESSARY; import static java.math.RoundingMode.UP; import static java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.math.BigInteger; import java.math.RoundingMode; /** * Tests for BigIntegerMath. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class BigIntegerMathTest extends TestCase { public void testIsPowerOfTwo() { for (BigInteger x : ALL_BIGINTEGER_CANDIDATES) { // Checks for a single bit set. boolean expected = x.signum() > 0 & x.and(x.subtract(ONE)).equals(ZERO); assertEquals(expected, BigIntegerMath.isPowerOfTwo(x)); } } public void testLog2ZeroAlwaysThrows() { for (RoundingMode mode : ALL_ROUNDING_MODES) { try { BigIntegerMath.log2(ZERO, mode); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } } public void testLog2NegativeAlwaysThrows() { for (RoundingMode mode : ALL_ROUNDING_MODES) { try { BigIntegerMath.log2(BigInteger.valueOf(-1), mode); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } } public void testLog2Floor() { for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) { for (RoundingMode mode : asList(FLOOR, DOWN)) { int result = BigIntegerMath.log2(x, mode); assertTrue(ZERO.setBit(result).compareTo(x) <= 0); assertTrue(ZERO.setBit(result + 1).compareTo(x) > 0); } } } public void testLog2Ceiling() { for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) { for (RoundingMode mode : asList(CEILING, UP)) { int result = BigIntegerMath.log2(x, mode); assertTrue(ZERO.setBit(result).compareTo(x) >= 0); assertTrue(result == 0 || ZERO.setBit(result - 1).compareTo(x) < 0); } } } // Relies on the correctness of isPowerOfTwo(BigInteger). public void testLog2Exact() { for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) { // We only expect an exception if x was not a power of 2. boolean isPowerOf2 = BigIntegerMath.isPowerOfTwo(x); try { assertEquals(x, ZERO.setBit(BigIntegerMath.log2(x, UNNECESSARY))); assertTrue(isPowerOf2); } catch (ArithmeticException e) { assertFalse(isPowerOf2); } } } public void testLog2HalfUp() { for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) { int result = BigIntegerMath.log2(x, HALF_UP); BigInteger x2 = x.pow(2); // x^2 < 2^(2 * result + 1), or else we would have rounded up assertTrue(ZERO.setBit(2 * result + 1).compareTo(x2) > 0); // x^2 >= 2^(2 * result - 1), or else we would have rounded down assertTrue(result == 0 || ZERO.setBit(2 * result - 1).compareTo(x2) <= 0); } } public void testLog2HalfDown() { for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) { int result = BigIntegerMath.log2(x, HALF_DOWN); BigInteger x2 = x.pow(2); // x^2 <= 2^(2 * result + 1), or else we would have rounded up assertTrue(ZERO.setBit(2 * result + 1).compareTo(x2) >= 0); // x^2 > 2^(2 * result - 1), or else we would have rounded down assertTrue(result == 0 || ZERO.setBit(2 * result - 1).compareTo(x2) < 0); } } // Relies on the correctness of log2(BigInteger, {HALF_UP,HALF_DOWN}). public void testLog2HalfEven() { for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) { int halfEven = BigIntegerMath.log2(x, HALF_EVEN); // Now figure out what rounding mode we should behave like (it depends if FLOOR was // odd/even). boolean floorWasEven = (BigIntegerMath.log2(x, FLOOR) & 1) == 0; assertEquals(BigIntegerMath.log2(x, floorWasEven ? HALF_DOWN : HALF_UP), halfEven); } } // Relies on the correctness of log10(BigInteger, FLOOR). // Relies on the correctness of log10(BigInteger, {HALF_UP,HALF_DOWN}). // Relies on the correctness of sqrt(BigInteger, FLOOR). // Relies on the correctness of sqrt(BigInteger, {HALF_UP,HALF_DOWN}). public void testFactorial() { BigInteger expected = BigInteger.ONE; for (int i = 1; i <= 200; i++) { expected = expected.multiply(BigInteger.valueOf(i)); assertEquals(expected, BigIntegerMath.factorial(i)); } } public void testFactorial0() { assertEquals(BigInteger.ONE, BigIntegerMath.factorial(0)); } public void testFactorialNegative() { try { BigIntegerMath.factorial(-1); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } public void testBinomialSmall() { runBinomialTest(0, 30); } // Depends on the correctness of BigIntegerMath.factorial private static void runBinomialTest(int firstN, int lastN) { for (int n = firstN; n <= lastN; n++) { for (int k = 0; k <= n; k++) { BigInteger expected = BigIntegerMath .factorial(n) .divide(BigIntegerMath.factorial(k)) .divide(BigIntegerMath.factorial(n - k)); assertEquals(expected, BigIntegerMath.binomial(n, k)); } } } public void testBinomialOutside() { for (int n = 0; n <= 50; n++) { try { BigIntegerMath.binomial(n, -1); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} try { BigIntegerMath.binomial(n, n + 1); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } } }
Java
/* * Copyright (C) 2011 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.math; import static com.google.common.math.MathTesting.ALL_LONG_CANDIDATES; import static com.google.common.math.MathTesting.ALL_ROUNDING_MODES; import static com.google.common.math.MathTesting.ALL_SAFE_ROUNDING_MODES; import static com.google.common.math.MathTesting.NEGATIVE_INTEGER_CANDIDATES; import static com.google.common.math.MathTesting.NEGATIVE_LONG_CANDIDATES; import static com.google.common.math.MathTesting.POSITIVE_LONG_CANDIDATES; import static java.math.BigInteger.valueOf; import static java.math.RoundingMode.UNNECESSARY; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; /** * Tests for LongMath. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class LongMathTest extends TestCase { public void testLessThanBranchFree() { for (long x : ALL_LONG_CANDIDATES) { for (long y : ALL_LONG_CANDIDATES) { BigInteger difference = BigInteger.valueOf(x).subtract(BigInteger.valueOf(y)); if (fitsInLong(difference)) { int expected = (x < y) ? 1 : 0; int actual = LongMath.lessThanBranchFree(x, y); assertEquals(expected, actual); } } } } // Throws an ArithmeticException if "the simple implementation" of binomial coefficients overflows public void testLog2ZeroAlwaysThrows() { for (RoundingMode mode : ALL_ROUNDING_MODES) { try { LongMath.log2(0L, mode); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } } public void testLog2NegativeAlwaysThrows() { for (long x : NEGATIVE_LONG_CANDIDATES) { for (RoundingMode mode : ALL_ROUNDING_MODES) { try { LongMath.log2(x, mode); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } } } /* Relies on the correctness of BigIntegerMath.log2 for all modes except UNNECESSARY. */ public void testLog2MatchesBigInteger() { for (long x : POSITIVE_LONG_CANDIDATES) { for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) { // The BigInteger implementation is tested separately, use it as the reference. assertEquals(BigIntegerMath.log2(valueOf(x), mode), LongMath.log2(x, mode)); } } } /* Relies on the correctness of isPowerOfTwo(long). */ public void testLog2Exact() { for (long x : POSITIVE_LONG_CANDIDATES) { // We only expect an exception if x was not a power of 2. boolean isPowerOf2 = LongMath.isPowerOfTwo(x); try { assertEquals(x, 1L << LongMath.log2(x, UNNECESSARY)); assertTrue(isPowerOf2); } catch (ArithmeticException e) { assertFalse(isPowerOf2); } } } // Relies on the correctness of BigIntegerMath.log10 for all modes except UNNECESSARY. // Relies on the correctness of log10(long, FLOOR) and of pow(long, int). // Relies on the correctness of BigIntegerMath.sqrt for all modes except UNNECESSARY. /* Relies on the correctness of sqrt(long, FLOOR). */ public void testGCDExhaustive() { for (long a : POSITIVE_LONG_CANDIDATES) { for (long b : POSITIVE_LONG_CANDIDATES) { assertEquals(valueOf(a).gcd(valueOf(b)), valueOf(LongMath.gcd(a, b))); } } } // Depends on the correctness of BigIntegerMath.factorial. // Depends on the correctness of BigIntegerMath.binomial. public void testBinomial() { for (int n = 0; n <= 70; n++) { for (int k = 0; k <= n; k++) { BigInteger expectedBig = BigIntegerMath.binomial(n, k); long expectedLong = fitsInLong(expectedBig) ? expectedBig.longValue() : Long.MAX_VALUE; assertEquals(expectedLong, LongMath.binomial(n, k)); } } } public void testBinomialOutside() { for (int n = 0; n <= 50; n++) { try { LongMath.binomial(n, -1); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} try { LongMath.binomial(n, n + 1); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } } public void testBinomialNegative() { for (int n : NEGATIVE_INTEGER_CANDIDATES) { try { LongMath.binomial(n, 0); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } } public void testSqrtOfLongIsAtMostFloorSqrtMaxLong() { long sqrtMaxLong = (long) Math.sqrt(Long.MAX_VALUE); assertTrue(sqrtMaxLong <= LongMath.FLOOR_SQRT_MAX_LONG); } /** * Helper method that asserts the arithmetic mean of x and y is equal * to the expectedMean. */ private static void assertMean(long expectedMean, long x, long y) { assertEquals("The expectedMean should be the same as computeMeanSafely", expectedMean, computeMeanSafely(x, y)); assertMean(x, y); } /** * Helper method that asserts the arithmetic mean of x and y is equal *to the result of computeMeanSafely. */ private static void assertMean(long x, long y) { long expectedMean = computeMeanSafely(x, y); assertEquals(expectedMean, LongMath.mean(x, y)); assertEquals("The mean of x and y should equal the mean of y and x", expectedMean, LongMath.mean(y, x)); } /** * Computes the mean in a way that is obvious and resilient to * overflow by using BigInteger arithmetic. */ private static long computeMeanSafely(long x, long y) { BigInteger bigX = BigInteger.valueOf(x); BigInteger bigY = BigInteger.valueOf(y); BigDecimal bigMean = new BigDecimal(bigX.add(bigY)) .divide(BigDecimal.valueOf(2), BigDecimal.ROUND_FLOOR); // parseInt blows up on overflow as opposed to intValue() which does not. return Long.parseLong(bigMean.toString()); } private static boolean fitsInLong(BigInteger big) { return big.bitLength() <= 63; } }
Java
/* * Copyright (C) 2011 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.math; import static com.google.common.math.MathTesting.ALL_INTEGER_CANDIDATES; import static com.google.common.math.MathTesting.ALL_ROUNDING_MODES; import static com.google.common.math.MathTesting.ALL_SAFE_ROUNDING_MODES; import static com.google.common.math.MathTesting.EXPONENTS; import static com.google.common.math.MathTesting.NEGATIVE_INTEGER_CANDIDATES; import static com.google.common.math.MathTesting.NONZERO_INTEGER_CANDIDATES; import static com.google.common.math.MathTesting.POSITIVE_INTEGER_CANDIDATES; import static com.google.common.math.TestPlatform.intsCanGoOutOfRange; import static java.math.BigInteger.valueOf; import static java.math.RoundingMode.UNNECESSARY; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; /** * Tests for {@link IntMath}. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class IntMathTest extends TestCase { public void testLessThanBranchFree() { for (int x : ALL_INTEGER_CANDIDATES) { for (int y : ALL_INTEGER_CANDIDATES) { if (LongMath.fitsInInt((long) x - y)) { int expected = (x < y) ? 1 : 0; int actual = IntMath.lessThanBranchFree(x, y); assertEquals(expected, actual); } } } } public void testLog2ZeroAlwaysThrows() { for (RoundingMode mode : ALL_ROUNDING_MODES) { try { IntMath.log2(0, mode); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } } public void testLog2NegativeAlwaysThrows() { for (int x : NEGATIVE_INTEGER_CANDIDATES) { for (RoundingMode mode : ALL_ROUNDING_MODES) { try { IntMath.log2(x, mode); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } } } // Relies on the correctness of BigIntegrerMath.log2 for all modes except UNNECESSARY. public void testLog2MatchesBigInteger() { for (int x : POSITIVE_INTEGER_CANDIDATES) { for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) { assertEquals(BigIntegerMath.log2(valueOf(x), mode), IntMath.log2(x, mode)); } } } // Relies on the correctness of isPowerOfTwo(int). public void testLog2Exact() { for (int x : POSITIVE_INTEGER_CANDIDATES) { // We only expect an exception if x was not a power of 2. boolean isPowerOf2 = IntMath.isPowerOfTwo(x); try { assertEquals(x, 1 << IntMath.log2(x, UNNECESSARY)); assertTrue(isPowerOf2); } catch (ArithmeticException e) { assertFalse(isPowerOf2); } } } // Relies on the correctness of BigIntegerMath.log10 for all modes except UNNECESSARY. // Relies on the correctness of log10(int, FLOOR) and of pow(int, int). // Simple test to cover sqrt(0) for all types and all modes. /* Relies on the correctness of BigIntegerMath.sqrt for all modes except UNNECESSARY. */ /* Relies on the correctness of sqrt(int, FLOOR). */ public void testDivNonZero() { for (int p : NONZERO_INTEGER_CANDIDATES) { for (int q : NONZERO_INTEGER_CANDIDATES) { for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) { // Skip some tests that fail due to GWT's non-compliant int implementation. // TODO(cpovirk): does this test fail for only some rounding modes or for all? if (p == -2147483648 && q == -1 && intsCanGoOutOfRange()) { continue; } int expected = new BigDecimal(valueOf(p)).divide(new BigDecimal(valueOf(q)), 0, mode).intValue(); assertEquals(p + "/" + q, force32(expected), IntMath.divide(p, q, mode)); } } } } public void testDivNonZeroExact() { for (int p : NONZERO_INTEGER_CANDIDATES) { for (int q : NONZERO_INTEGER_CANDIDATES) { // Skip some tests that fail due to GWT's non-compliant int implementation. if (p == -2147483648 && q == -1 && intsCanGoOutOfRange()) { continue; } boolean dividesEvenly = (p % q) == 0; try { assertEquals(p + "/" + q, p, IntMath.divide(p, q, UNNECESSARY) * q); assertTrue(p + "/" + q + " not expected to divide evenly", dividesEvenly); } catch (ArithmeticException e) { assertFalse(p + "/" + q + " expected to divide evenly", dividesEvenly); } } } } public void testZeroDivIsAlwaysZero() { for (int q : NONZERO_INTEGER_CANDIDATES) { for (RoundingMode mode : ALL_ROUNDING_MODES) { assertEquals(0, IntMath.divide(0, q, mode)); } } } public void testDivByZeroAlwaysFails() { for (int p : ALL_INTEGER_CANDIDATES) { for (RoundingMode mode : ALL_ROUNDING_MODES) { try { IntMath.divide(p, 0, mode); fail("Expected ArithmeticException"); } catch (ArithmeticException expected) {} } } } public void testMod() { for (int x : ALL_INTEGER_CANDIDATES) { for (int m : POSITIVE_INTEGER_CANDIDATES) { assertEquals(valueOf(x).mod(valueOf(m)).intValue(), IntMath.mod(x, m)); } } } public void testModNegativeModulusFails() { for (int x : POSITIVE_INTEGER_CANDIDATES) { for (int m : NEGATIVE_INTEGER_CANDIDATES) { try { IntMath.mod(x, m); fail("Expected ArithmeticException"); } catch (ArithmeticException expected) {} } } } public void testModZeroModulusFails() { for (int x : ALL_INTEGER_CANDIDATES) { try { IntMath.mod(x, 0); fail("Expected ArithmeticException"); } catch (ArithmeticException expected) {} } } public void testGCD() { for (int a : POSITIVE_INTEGER_CANDIDATES) { for (int b : POSITIVE_INTEGER_CANDIDATES) { assertEquals(valueOf(a).gcd(valueOf(b)), valueOf(IntMath.gcd(a, b))); } } } public void testGCDZero() { for (int a : POSITIVE_INTEGER_CANDIDATES) { assertEquals(a, IntMath.gcd(a, 0)); assertEquals(a, IntMath.gcd(0, a)); } assertEquals(0, IntMath.gcd(0, 0)); } public void testGCDNegativePositiveThrows() { for (int a : NEGATIVE_INTEGER_CANDIDATES) { try { IntMath.gcd(a, 3); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} try { IntMath.gcd(3, a); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } } public void testGCDNegativeZeroThrows() { for (int a : NEGATIVE_INTEGER_CANDIDATES) { try { IntMath.gcd(a, 0); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} try { IntMath.gcd(0, a); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } } public void testCheckedAdd() { for (int a : ALL_INTEGER_CANDIDATES) { for (int b : ALL_INTEGER_CANDIDATES) { BigInteger expectedResult = valueOf(a).add(valueOf(b)); boolean expectedSuccess = fitsInInt(expectedResult); try { assertEquals(a + b, IntMath.checkedAdd(a, b)); assertTrue(expectedSuccess); } catch (ArithmeticException e) { assertFalse(expectedSuccess); } } } } public void testCheckedSubtract() { for (int a : ALL_INTEGER_CANDIDATES) { for (int b : ALL_INTEGER_CANDIDATES) { BigInteger expectedResult = valueOf(a).subtract(valueOf(b)); boolean expectedSuccess = fitsInInt(expectedResult); try { assertEquals(a - b, IntMath.checkedSubtract(a, b)); assertTrue(expectedSuccess); } catch (ArithmeticException e) { assertFalse(expectedSuccess); } } } } public void testCheckedMultiply() { for (int a : ALL_INTEGER_CANDIDATES) { for (int b : ALL_INTEGER_CANDIDATES) { BigInteger expectedResult = valueOf(a).multiply(valueOf(b)); boolean expectedSuccess = fitsInInt(expectedResult); try { assertEquals(a * b, IntMath.checkedMultiply(a, b)); assertTrue(expectedSuccess); } catch (ArithmeticException e) { assertFalse(expectedSuccess); } } } } public void testCheckedPow() { for (int b : ALL_INTEGER_CANDIDATES) { for (int k : EXPONENTS) { BigInteger expectedResult = valueOf(b).pow(k); boolean expectedSuccess = fitsInInt(expectedResult); try { assertEquals(b + "^" + k, force32(expectedResult.intValue()), IntMath.checkedPow(b, k)); assertTrue(b + "^" + k + " should have succeeded", expectedSuccess); } catch (ArithmeticException e) { assertFalse(b + "^" + k + " should have failed", expectedSuccess); } } } } // Depends on the correctness of BigIntegerMath.factorial. public void testFactorial() { for (int n = 0; n <= 50; n++) { BigInteger expectedBig = BigIntegerMath.factorial(n); int expectedInt = fitsInInt(expectedBig) ? expectedBig.intValue() : Integer.MAX_VALUE; assertEquals(expectedInt, IntMath.factorial(n)); } } public void testFactorialNegative() { for (int n : NEGATIVE_INTEGER_CANDIDATES) { try { IntMath.factorial(n); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } } // Depends on the correctness of BigIntegerMath.binomial. /** * Helper method that asserts the arithmetic mean of x and y is equal * to the expectedMean. */ private static void assertMean(int expectedMean, int x, int y) { assertEquals("The expectedMean should be the same as computeMeanSafely", expectedMean, computeMeanSafely(x, y)); assertMean(x, y); } /** * Helper method that asserts the arithmetic mean of x and y is equal * to the result of computeMeanSafely. */ private static void assertMean(int x, int y) { int expectedMean = computeMeanSafely(x, y); assertEquals(expectedMean, IntMath.mean(x, y)); assertEquals("The mean of x and y should equal the mean of y and x", expectedMean, IntMath.mean(y, x)); } /** * Computes the mean in a way that is obvious and resilient to * overflow by using BigInteger arithmetic. */ private static int computeMeanSafely(int x, int y) { BigInteger bigX = BigInteger.valueOf(x); BigInteger bigY = BigInteger.valueOf(y); BigDecimal bigMean = new BigDecimal(bigX.add(bigY)) .divide(BigDecimal.valueOf(2), BigDecimal.ROUND_FLOOR); // parseInt blows up on overflow as opposed to intValue() which does not. return Integer.parseInt(bigMean.toString()); } private static boolean fitsInInt(BigInteger big) { return big.bitLength() <= 31; } private static int force32(int value) { // GWT doesn't consistently overflow values to make them 32-bit, so we need to force it. return value & 0xffffffff; } }
Java
/* * Copyright (C) 2011 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.math; import com.google.common.annotations.GwtCompatible; /** * @author Chris Povirk */ @GwtCompatible(emulated = true) class TestPlatform { static boolean intsCanGoOutOfRange() { return true; } }
Java
/* * Copyright (C) 2011 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.net; import static com.google.common.base.Charsets.UTF_8; import static com.google.common.net.MediaType.ANY_APPLICATION_TYPE; import static com.google.common.net.MediaType.ANY_AUDIO_TYPE; import static com.google.common.net.MediaType.ANY_IMAGE_TYPE; import static com.google.common.net.MediaType.ANY_TEXT_TYPE; import static com.google.common.net.MediaType.ANY_TYPE; import static com.google.common.net.MediaType.ANY_VIDEO_TYPE; import static com.google.common.net.MediaType.HTML_UTF_8; import static com.google.common.net.MediaType.JPEG; import static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Optional; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMultimap; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; /** * Tests for {@link MediaType}. * * @author Gregory Kick */ @Beta @GwtCompatible(emulated = true) public class MediaTypeTest extends TestCase { public void testCreate_invalidType() { try { MediaType.create("te><t", "plaintext"); fail(); } catch (IllegalArgumentException expected) {} } public void testCreate_invalidSubtype() { try { MediaType.create("text", "pl@intext"); fail(); } catch (IllegalArgumentException expected) {} } public void testCreate_wildcardTypeDeclaredSubtype() { try { MediaType.create("*", "text"); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateApplicationType() { MediaType newType = MediaType.createApplicationType("yams"); assertEquals("application", newType.type()); assertEquals("yams", newType.subtype()); } public void testCreateAudioType() { MediaType newType = MediaType.createAudioType("yams"); assertEquals("audio", newType.type()); assertEquals("yams", newType.subtype()); } public void testCreateImageType() { MediaType newType = MediaType.createImageType("yams"); assertEquals("image", newType.type()); assertEquals("yams", newType.subtype()); } public void testCreateTextType() { MediaType newType = MediaType.createTextType("yams"); assertEquals("text", newType.type()); assertEquals("yams", newType.subtype()); } public void testCreateVideoType() { MediaType newType = MediaType.createVideoType("yams"); assertEquals("video", newType.type()); assertEquals("yams", newType.subtype()); } public void testGetType() { assertEquals("text", MediaType.parse("text/plain").type()); assertEquals("application", MediaType.parse("application/atom+xml; charset=utf-8").type()); } public void testGetSubtype() { assertEquals("plain", MediaType.parse("text/plain").subtype()); assertEquals("atom+xml", MediaType.parse("application/atom+xml; charset=utf-8").subtype()); } private static final ImmutableListMultimap<String, String> PARAMETERS = ImmutableListMultimap.of("a", "1", "a", "2", "b", "3"); public void testGetParameters() { assertEquals(ImmutableListMultimap.of(), MediaType.parse("text/plain").parameters()); assertEquals(ImmutableListMultimap.of("charset", "utf-8"), MediaType.parse("application/atom+xml; charset=utf-8").parameters()); assertEquals(PARAMETERS, MediaType.parse("application/atom+xml; a=1; a=2; b=3").parameters()); } public void testWithoutParameters() { assertSame(MediaType.parse("image/gif"), MediaType.parse("image/gif").withoutParameters()); assertEquals(MediaType.parse("image/gif"), MediaType.parse("image/gif; foo=bar").withoutParameters()); } public void testWithParameters() { assertEquals(MediaType.parse("text/plain; a=1; a=2; b=3"), MediaType.parse("text/plain").withParameters(PARAMETERS)); assertEquals(MediaType.parse("text/plain; a=1; a=2; b=3"), MediaType.parse("text/plain; a=1; a=2; b=3").withParameters(PARAMETERS)); } public void testWithParameters_invalidAttribute() { MediaType mediaType = MediaType.parse("text/plain"); ImmutableListMultimap<String, String> parameters = ImmutableListMultimap.of("a", "1", "@", "2", "b", "3"); try { mediaType.withParameters(parameters); fail(); } catch (IllegalArgumentException expected) {} } public void testWithParameter() { assertEquals(MediaType.parse("text/plain; a=1"), MediaType.parse("text/plain").withParameter("a", "1")); assertEquals(MediaType.parse("text/plain; a=1"), MediaType.parse("text/plain; a=1; a=2").withParameter("a", "1")); assertEquals(MediaType.parse("text/plain; a=3"), MediaType.parse("text/plain; a=1; a=2").withParameter("a", "3")); assertEquals(MediaType.parse("text/plain; a=1; a=2; b=3"), MediaType.parse("text/plain; a=1; a=2").withParameter("b", "3")); } public void testWithParameter_invalidAttribute() { MediaType mediaType = MediaType.parse("text/plain"); try { mediaType.withParameter("@", "2"); fail(); } catch (IllegalArgumentException expected) {} } public void testWithCharset() { assertEquals(MediaType.parse("text/plain; charset=utf-8"), MediaType.parse("text/plain").withCharset(UTF_8)); assertEquals(MediaType.parse("text/plain; charset=utf-8"), MediaType.parse("text/plain; charset=utf-16").withCharset(UTF_8)); } public void testHasWildcard() { assertFalse(PLAIN_TEXT_UTF_8.hasWildcard()); assertFalse(JPEG.hasWildcard()); assertTrue(ANY_TYPE.hasWildcard()); assertTrue(ANY_APPLICATION_TYPE.hasWildcard()); assertTrue(ANY_AUDIO_TYPE.hasWildcard()); assertTrue(ANY_IMAGE_TYPE.hasWildcard()); assertTrue(ANY_TEXT_TYPE.hasWildcard()); assertTrue(ANY_VIDEO_TYPE.hasWildcard()); } public void testIs() { assertTrue(PLAIN_TEXT_UTF_8.is(ANY_TYPE)); assertTrue(JPEG.is(ANY_TYPE)); assertTrue(ANY_TEXT_TYPE.is(ANY_TYPE)); assertTrue(PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE)); assertTrue(PLAIN_TEXT_UTF_8.withoutParameters().is(ANY_TEXT_TYPE)); assertFalse(JPEG.is(ANY_TEXT_TYPE)); assertTrue(PLAIN_TEXT_UTF_8.is(PLAIN_TEXT_UTF_8)); assertTrue(PLAIN_TEXT_UTF_8.is(PLAIN_TEXT_UTF_8.withoutParameters())); assertFalse(PLAIN_TEXT_UTF_8.withoutParameters().is(PLAIN_TEXT_UTF_8)); assertFalse(PLAIN_TEXT_UTF_8.is(HTML_UTF_8)); assertFalse(PLAIN_TEXT_UTF_8.withParameter("charset", "UTF-16").is(PLAIN_TEXT_UTF_8)); assertFalse(PLAIN_TEXT_UTF_8.is(PLAIN_TEXT_UTF_8.withParameter("charset", "UTF-16"))); } public void testParse_empty() { try { MediaType.parse(""); fail(); } catch (IllegalArgumentException expected) {} } public void testParse_badInput() { try { MediaType.parse("/"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("te<t/plain"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/pl@in"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain;"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; "); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a="); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=@"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=\"@"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=1;"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=1; "); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=1; b"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=1; b="); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=\u2025"); fail(); } catch (IllegalArgumentException expected) {} } public void testGetCharset() { assertEquals(Optional.absent(), MediaType.parse("text/plain").charset()); assertEquals(Optional.of(UTF_8), MediaType.parse("text/plain; charset=utf-8").charset()); } public void testGetCharset_tooMany() { MediaType mediaType = MediaType.parse("text/plain; charset=utf-8; charset=utf-16"); try { mediaType.charset(); fail(); } catch (IllegalStateException expected) {} } public void testGetCharset_illegalCharset() { MediaType mediaType = MediaType.parse( "text/plain; charset=\"!@#$%^&*()\""); try { mediaType.charset(); fail(); } catch (IllegalCharsetNameException expected) {} } public void testGetCharset_unsupportedCharset() { MediaType mediaType = MediaType.parse( "text/plain; charset=utf-wtf"); try { mediaType.charset(); fail(); } catch (UnsupportedCharsetException expected) {} } public void testEquals() { new EqualsTester() .addEqualityGroup(MediaType.create("text", "plain"), MediaType.create("TEXT", "PLAIN"), MediaType.parse("text/plain"), MediaType.parse("TEXT/PLAIN"), MediaType.create("text", "plain").withParameter("a", "1").withoutParameters()) .addEqualityGroup( MediaType.create("text", "plain").withCharset(UTF_8), MediaType.create("text", "plain").withParameter("CHARSET", "UTF-8"), MediaType.create("text", "plain").withParameters( ImmutableMultimap.of("charset", "utf-8")), MediaType.parse("text/plain;charset=utf-8"), MediaType.parse("text/plain; charset=utf-8"), MediaType.parse("text/plain; charset=utf-8"), MediaType.parse("text/plain; \tcharset=utf-8"), MediaType.parse("text/plain; \r\n\tcharset=utf-8"), MediaType.parse("text/plain; CHARSET=utf-8"), MediaType.parse("text/plain; charset=\"utf-8\""), MediaType.parse("text/plain; charset=\"\\u\\tf-\\8\""), MediaType.parse("text/plain; charset=UTF-8")) .addEqualityGroup(MediaType.parse("text/plain; charset=utf-8; charset=utf-8")) .addEqualityGroup(MediaType.create("text", "plain").withParameter("a", "value"), MediaType.create("text", "plain").withParameter("A", "value")) .addEqualityGroup(MediaType.create("text", "plain").withParameter("a", "VALUE"), MediaType.create("text", "plain").withParameter("A", "VALUE")) .addEqualityGroup( MediaType.create("text", "plain") .withParameters(ImmutableListMultimap.of("a", "1", "a", "2")), MediaType.create("text", "plain") .withParameters(ImmutableListMultimap.of("a", "2", "a", "1"))) .addEqualityGroup(MediaType.create("text", "csv")) .addEqualityGroup(MediaType.create("application", "atom+xml")) .testEquals(); } public void testToString() { assertEquals("text/plain", MediaType.create("text", "plain").toString()); assertEquals("text/plain; something=\"cr@zy\"; something-else=\"crazy with spaces\"", MediaType.create("text", "plain") .withParameter("something", "cr@zy") .withParameter("something-else", "crazy with spaces") .toString()); } }
Java
/* * Copyright (C) 2009 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.net; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.List; /** * {@link TestCase} for {@link InternetDomainName}. * * @author Craig Berry */ @GwtCompatible(emulated = true) public final class InternetDomainNameTest extends TestCase { private static final InternetDomainName UNICODE_EXAMPLE = InternetDomainName.from("j\u00f8rpeland.no"); private static final InternetDomainName PUNYCODE_EXAMPLE = InternetDomainName.from("xn--jrpeland-54a.no"); /** * The Greek letter delta, used in unicode testing. */ private static final String DELTA = "\u0394"; /** * A domain part which is valid under lenient validation, but invalid under * strict validation. */ static final String LOTS_OF_DELTAS = Strings.repeat(DELTA, 62); private static final String ALMOST_TOO_MANY_LEVELS = Strings.repeat("a.", 127); private static final String ALMOST_TOO_LONG = Strings.repeat("aaaaa.", 40) + "1234567890.c"; private static final List<String> VALID_NAME = ImmutableList.of( "foo.com", "f-_-o.cOM", "f--1.com", "f11-1.com", "www", "abc.a23", "biz.com.ua", "x", "fOo", "f--o", "f_a", "foo.net.us\uFF61ocm", "woo.com.", "a" + DELTA + "b.com", ALMOST_TOO_MANY_LEVELS, ALMOST_TOO_LONG); private static final List<String> INVALID_NAME = ImmutableList.of( "", " ", "127.0.0.1", "::1", "13", "abc.12c", "foo-.com", "_bar.quux", "foo+bar.com", "foo!bar.com", ".foo.com", "..bar.com", "baz..com", "..quiffle.com", "fleeb.com..", ".", "..", "...", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com", "a" + DELTA + " .com", ALMOST_TOO_MANY_LEVELS + "com", ALMOST_TOO_LONG + ".c"); private static final List<String> PS = ImmutableList.of( "com", "co.uk", "foo.ar", "xxxxxx.ar", "org.mK", "us", "uk\uFF61com.", // Alternate dot character "\u7f51\u7edc.Cn", // "网络.Cn" "j\u00f8rpeland.no", // "jorpeland.no" (first o slashed) "xn--jrpeland-54a.no" // IDNA (punycode) encoding of above ); private static final List<String> NO_PS = ImmutableList.of( "www", "foo.google", "x.y.z"); private static final List<String> NON_PS = ImmutableList.of( "foo.bar.com", "foo.ca", "foo.bar.ca", "foo.bar.co.il", "state.CA.us", "www.state.pa.us", "pvt.k12.ca.us", "www.google.com", "www4.yahoo.co.uk", "home.netscape.com", "web.MIT.edu", "foo.eDu.au", "utenti.blah.IT", "dominio.com.co"); private static final List<String> TOP_PRIVATE_DOMAIN = ImmutableList.of( "google.com", "foo.Co.uk", "foo.ca.us."); private static final List<String> UNDER_PRIVATE_DOMAIN = ImmutableList.of( "foo.bar.google.com", "a.b.co.uk", "x.y.ca.us"); private static final List<String> VALID_IP_ADDRS = ImmutableList.of( "1.2.3.4", "127.0.0.1", "::1", "2001:db8::1"); private static final List<String> INVALID_IP_ADDRS = ImmutableList.of( "", "1", "1.2.3", "...", "1.2.3.4.5", "400.500.600.700", ":", ":::1", "2001:db8:"); private static final List<String> SOMEWHERE_UNDER_PS = ImmutableList.of( "foo.bar.google.com", "a.b.c.1.2.3.ca.us", "site.jp", "uomi-online.kir.jp", "jprs.co.jp", "site.quick.jp", "site.tenki.jp", "site.or.jp", "site.gr.jp", "site.ne.jp", "site.ac.jp", "site.ad.jp", "site.ed.jp", "site.geo.jp", "site.go.jp", "site.lg.jp", "1.fm", "site.cc", "site.ee", "site.fi", "site.fm", "site.gr", "www.leguide.ma", "site.ma", "some.org.mk", "site.mk", "site.tv", "site.us", "www.odev.us", "www.GOOGLE.com", "www.com", "google.com", "www7.google.co.uk", "google.Co.uK", "jobs.kt.com.", "home.netscape.com", "web.stanford.edu", "stanford.edu", "state.ca.us", "www.state.ca.us", "state.ca.us", "pvt.k12.ca.us", "www.rave.ca.", "cnn.ca", "ledger-enquirer.com", "it-trace.ch", "cool.dk", "cool.co.uk", "cool.de", "cool.es", "cool\uFF61fr", // Alternate dot character "cool.nl", "members.blah.nl.", "cool.se", "utenti.blah.it", "kt.co", "a\u7f51\u7edcA.\u7f51\u7edc.Cn" // "a网络A.网络.Cn" ); public void testValid() { for (String name : VALID_NAME) { InternetDomainName.from(name); } } public void testInvalid() { for (String name : INVALID_NAME) { try { InternetDomainName.from(name); fail("Should have been invalid: '" + name + "'"); } catch (IllegalArgumentException expected) { // Expected case } } } public void testPublicSuffix() { for (String name : PS) { final InternetDomainName domain = InternetDomainName.from(name); assertTrue(name, domain.isPublicSuffix()); assertTrue(name, domain.hasPublicSuffix()); assertFalse(name, domain.isUnderPublicSuffix()); assertFalse(name, domain.isTopPrivateDomain()); assertEquals(domain, domain.publicSuffix()); } for (String name : NO_PS) { final InternetDomainName domain = InternetDomainName.from(name); assertFalse(name, domain.isPublicSuffix()); assertFalse(name, domain.hasPublicSuffix()); assertFalse(name, domain.isUnderPublicSuffix()); assertFalse(name, domain.isTopPrivateDomain()); assertNull(domain.publicSuffix()); } for (String name : NON_PS) { final InternetDomainName domain = InternetDomainName.from(name); assertFalse(name, domain.isPublicSuffix()); assertTrue(name, domain.hasPublicSuffix()); assertTrue(name, domain.isUnderPublicSuffix()); } } public void testUnderPublicSuffix() { for (String name : SOMEWHERE_UNDER_PS) { final InternetDomainName domain = InternetDomainName.from(name); assertFalse(name, domain.isPublicSuffix()); assertTrue(name, domain.hasPublicSuffix()); assertTrue(name, domain.isUnderPublicSuffix()); } } public void testTopPrivateDomain() { for (String name : TOP_PRIVATE_DOMAIN) { final InternetDomainName domain = InternetDomainName.from(name); assertFalse(name, domain.isPublicSuffix()); assertTrue(name, domain.hasPublicSuffix()); assertTrue(name, domain.isUnderPublicSuffix()); assertTrue(name, domain.isTopPrivateDomain()); assertEquals(domain.parent(), domain.publicSuffix()); } } public void testUnderPrivateDomain() { for (String name : UNDER_PRIVATE_DOMAIN) { final InternetDomainName domain = InternetDomainName.from(name); assertFalse(name, domain.isPublicSuffix()); assertTrue(name, domain.hasPublicSuffix()); assertTrue(name, domain.isUnderPublicSuffix()); assertFalse(name, domain.isTopPrivateDomain()); } } public void testParent() { assertEquals( "com", InternetDomainName.from("google.com").parent().name()); assertEquals( "uk", InternetDomainName.from("co.uk").parent().name()); assertEquals( "google.com", InternetDomainName.from("www.google.com").parent().name()); try { InternetDomainName.from("com").parent(); fail("'com' should throw ISE on .parent() call"); } catch (IllegalStateException expected) { } } public void testChild() { InternetDomainName domain = InternetDomainName.from("foo.com"); assertEquals("www.foo.com", domain.child("www").name()); try { domain.child("www."); fail("www..google.com should have been invalid"); } catch (IllegalArgumentException expected) { // Expected outcome } } public void testParentChild() { InternetDomainName origin = InternetDomainName.from("foo.com"); InternetDomainName parent = origin.parent(); assertEquals("com", parent.name()); // These would throw an exception if leniency were not preserved during parent() and child() // calls. InternetDomainName child = parent.child(LOTS_OF_DELTAS); child.child(LOTS_OF_DELTAS); } public void testValidTopPrivateDomain() { InternetDomainName googleDomain = InternetDomainName.from("google.com"); assertEquals(googleDomain, googleDomain.topPrivateDomain()); assertEquals(googleDomain, googleDomain.child("mail").topPrivateDomain()); assertEquals(googleDomain, googleDomain.child("foo.bar").topPrivateDomain()); } public void testInvalidTopPrivateDomain() { List<String> badCookieDomains = ImmutableList.of("co.uk", "foo", "com"); for (String domain : badCookieDomains) { try { InternetDomainName.from(domain).topPrivateDomain(); fail(domain); } catch (IllegalStateException expected) { } } } public void testIsValid() { final Iterable<String> validCases = Iterables.concat( VALID_NAME, PS, NO_PS, NON_PS); final Iterable<String> invalidCases = Iterables.concat( INVALID_NAME, VALID_IP_ADDRS, INVALID_IP_ADDRS); for (String valid : validCases) { assertTrue(valid, InternetDomainName.isValid(valid)); } for (String invalid : invalidCases) { assertFalse(invalid, InternetDomainName.isValid(invalid)); } } // TODO(hhchan): Resurrect this test after removing the reference to // String.toLowerCase(Locale) public void testExclusion() { InternetDomainName domain = InternetDomainName.from("foo.nic.uk"); assertTrue(domain.hasPublicSuffix()); assertEquals("uk", domain.publicSuffix().name()); // Behold the weirdness! assertFalse(domain.publicSuffix().isPublicSuffix()); } public void testMultipleUnders() { // PSL has both *.uk and *.sch.uk; the latter should win. // See http://code.google.com/p/guava-libraries/issues/detail?id=1176 InternetDomainName domain = InternetDomainName.from("www.essex.sch.uk"); assertTrue(domain.hasPublicSuffix()); assertEquals("essex.sch.uk", domain.publicSuffix().name()); assertEquals("www.essex.sch.uk", domain.topPrivateDomain().name()); } public void testEquality() { new EqualsTester() .addEqualityGroup( idn("google.com"), idn("google.com"), idn("GOOGLE.COM")) .addEqualityGroup(idn("www.google.com")) .addEqualityGroup(UNICODE_EXAMPLE) .addEqualityGroup(PUNYCODE_EXAMPLE) .testEquals(); } private static InternetDomainName idn(String domain) { return InternetDomainName.from(domain); } }
Java
/* * Copyright (C) 2012 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.collect.testing.google; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.BiMap; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.testing.SerializableTester; import java.io.Serializable; /** * Tests for the {@code inverse} view of a BiMap. * * <p>This assumes that {@code bimap.inverse().inverse() == bimap}, which is not technically * required but is fulfilled by all current implementations. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class BiMapInverseTester<K, V> extends AbstractBiMapTester<K, V> { public void testInverseSame() { assertSame(getMap(), getMap().inverse().inverse()); } @CollectionFeature.Require(SERIALIZABLE) public void testInverseSerialization() { BiMapPair<K, V> pair = new BiMapPair<K, V>(getMap()); BiMapPair<K, V> copy = SerializableTester.reserialize(pair); assertEquals(pair.forward, copy.forward); assertEquals(pair.backward, copy.backward); assertSame(copy.backward, copy.forward.inverse()); assertSame(copy.forward, copy.backward.inverse()); } private static class BiMapPair<K, V> implements Serializable { final BiMap<K, V> forward; final BiMap<V, K> backward; BiMapPair(BiMap<K, V> original) { this.forward = original; this.backward = original.inverse(); } private static final long serialVersionUID = 0; } }
Java
/* * Copyright (C) 2011 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.collect.testing.google; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.IteratorFeature; import com.google.common.collect.testing.IteratorTester; import com.google.common.collect.testing.features.CollectionFeature; import java.util.Arrays; import java.util.Iterator; /** * Tester to make sure the {@code iterator().remove()} implementation of {@code Multiset} works when * there are multiple occurrences of elements. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class MultisetIteratorTester<E> extends AbstractMultisetTester<E> { @SuppressWarnings("unchecked") @CollectionFeature.Require({SUPPORTS_ITERATOR_REMOVE, KNOWN_ORDER}) public void testRemovingIteratorKnownOrder() { new IteratorTester<E>(4, IteratorFeature.MODIFIABLE, getSubjectGenerator().order( Arrays.asList(samples.e0, samples.e1, samples.e1, samples.e2)), IteratorTester.KnownOrder.KNOWN_ORDER) { @Override protected Iterator<E> newTargetIterator() { return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2) .iterator(); } }.test(); } @SuppressWarnings("unchecked") @CollectionFeature.Require(value = SUPPORTS_ITERATOR_REMOVE, absent = KNOWN_ORDER) public void testRemovingIteratorUnknownOrder() { new IteratorTester<E>(4, IteratorFeature.MODIFIABLE, Arrays.asList(samples.e0, samples.e1, samples.e1, samples.e2), IteratorTester.KnownOrder.UNKNOWN_ORDER) { @Override protected Iterator<E> newTargetIterator() { return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2) .iterator(); } }.test(); } @SuppressWarnings("unchecked") @CollectionFeature.Require(value = KNOWN_ORDER, absent = SUPPORTS_ITERATOR_REMOVE) public void testIteratorKnownOrder() { new IteratorTester<E>(4, IteratorFeature.UNMODIFIABLE, getSubjectGenerator().order( Arrays.asList(samples.e0, samples.e1, samples.e1, samples.e2)), IteratorTester.KnownOrder.KNOWN_ORDER) { @Override protected Iterator<E> newTargetIterator() { return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2) .iterator(); } }.test(); } @SuppressWarnings("unchecked") @CollectionFeature.Require(absent = {SUPPORTS_ITERATOR_REMOVE, KNOWN_ORDER}) public void testIteratorUnknownOrder() { new IteratorTester<E>(4, IteratorFeature.UNMODIFIABLE, Arrays.asList(samples.e0, samples.e1, samples.e1, samples.e2), IteratorTester.KnownOrder.UNKNOWN_ORDER) { @Override protected Iterator<E> newTargetIterator() { return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2) .iterator(); } }.test(); } }
Java
/* * Copyright (C) 2008 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.collect.testing.google; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newTreeSet; import static com.google.common.collect.testing.SampleElements.Strings.AFTER_LAST; import static com.google.common.collect.testing.SampleElements.Strings.AFTER_LAST_2; import static com.google.common.collect.testing.SampleElements.Strings.BEFORE_FIRST; import static com.google.common.collect.testing.SampleElements.Strings.BEFORE_FIRST_2; import static junit.framework.Assert.assertEquals; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ContiguousSet; import com.google.common.collect.DiscreteDomain; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.google.common.collect.Range; import com.google.common.collect.Sets; import com.google.common.collect.testing.TestCollectionGenerator; import com.google.common.collect.testing.TestCollidingSetGenerator; import com.google.common.collect.testing.TestIntegerSortedSetGenerator; import com.google.common.collect.testing.TestSetGenerator; import com.google.common.collect.testing.TestStringListGenerator; import com.google.common.collect.testing.TestStringSetGenerator; import com.google.common.collect.testing.TestStringSortedSetGenerator; import com.google.common.collect.testing.TestUnhashableCollectionGenerator; import com.google.common.collect.testing.UnhashableObject; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.SortedSet; /** * Generators of different types of sets and derived collections from sets. * * @author Kevin Bourrillion * @author Jared Levy * @author Hayward Chan */ @GwtCompatible(emulated = true) public class SetGenerators { public static class ImmutableSetCopyOfGenerator extends TestStringSetGenerator { @Override protected Set<String> create(String[] elements) { return ImmutableSet.copyOf(elements); } } public static class ImmutableSetWithBadHashesGenerator extends TestCollidingSetGenerator // Work around a GWT compiler bug. Not explicitly listing this will // cause the createArray() method missing in the generated javascript. // TODO: Remove this once the GWT bug is fixed. implements TestCollectionGenerator<Object> { @Override public Set<Object> create(Object... elements) { return ImmutableSet.copyOf(elements); } } public static class DegeneratedImmutableSetGenerator extends TestStringSetGenerator { // Make sure we get what we think we're getting, or else this test // is pointless @SuppressWarnings("cast") @Override protected Set<String> create(String[] elements) { return (ImmutableSet<String>) ImmutableSet.of(elements[0], elements[0]); } } public static class ImmutableSortedSetCopyOfGenerator extends TestStringSortedSetGenerator { @Override protected SortedSet<String> create(String[] elements) { return ImmutableSortedSet.copyOf(elements); } } public static class ImmutableSortedSetHeadsetGenerator extends TestStringSortedSetGenerator { @Override protected SortedSet<String> create(String[] elements) { List<String> list = Lists.newArrayList(elements); list.add("zzz"); return ImmutableSortedSet.copyOf(list) .headSet("zzy"); } } public static class ImmutableSortedSetTailsetGenerator extends TestStringSortedSetGenerator { @Override protected SortedSet<String> create(String[] elements) { List<String> list = Lists.newArrayList(elements); list.add("\0"); return ImmutableSortedSet.copyOf(list) .tailSet("\0\0"); } } public static class ImmutableSortedSetSubsetGenerator extends TestStringSortedSetGenerator { @Override protected SortedSet<String> create(String[] elements) { List<String> list = Lists.newArrayList(elements); list.add("\0"); list.add("zzz"); return ImmutableSortedSet.copyOf(list) .subSet("\0\0", "zzy"); } } public static class ImmutableSortedSetExplicitComparator extends TestStringSetGenerator { private static final Comparator<String> STRING_REVERSED = Collections.reverseOrder(); @Override protected SortedSet<String> create(String[] elements) { return ImmutableSortedSet.orderedBy(STRING_REVERSED) .add(elements) .build(); } @Override public List<String> order(List<String> insertionOrder) { Collections.sort(insertionOrder, Collections.reverseOrder()); return insertionOrder; } } public static class ImmutableSortedSetExplicitSuperclassComparatorGenerator extends TestStringSetGenerator { private static final Comparator<Comparable<?>> COMPARABLE_REVERSED = Collections.reverseOrder(); @Override protected SortedSet<String> create(String[] elements) { return new ImmutableSortedSet.Builder<String>(COMPARABLE_REVERSED) .add(elements) .build(); } @Override public List<String> order(List<String> insertionOrder) { Collections.sort(insertionOrder, Collections.reverseOrder()); return insertionOrder; } } public static class ImmutableSortedSetReversedOrderGenerator extends TestStringSetGenerator { @Override protected SortedSet<String> create(String[] elements) { return ImmutableSortedSet.<String>reverseOrder() .addAll(Arrays.asList(elements).iterator()) .build(); } @Override public List<String> order(List<String> insertionOrder) { Collections.sort(insertionOrder, Collections.reverseOrder()); return insertionOrder; } } public static class ImmutableSortedSetUnhashableGenerator extends TestUnhashableSetGenerator { @Override public Set<UnhashableObject> create( UnhashableObject[] elements) { return ImmutableSortedSet.copyOf(elements); } } public static class ImmutableSetAsListGenerator extends TestStringListGenerator { @Override protected List<String> create(String[] elements) { return ImmutableSet.copyOf(elements).asList(); } } public static class ImmutableSortedSetAsListGenerator extends TestStringListGenerator { @Override protected List<String> create(String[] elements) { Comparator<String> comparator = createExplicitComparator(elements); ImmutableSet<String> set = ImmutableSortedSet.copyOf( comparator, Arrays.asList(elements)); return set.asList(); } } public static class ImmutableSortedSetSubsetAsListGenerator extends TestStringListGenerator { @Override protected List<String> create(String[] elements) { Comparator<String> comparator = createExplicitComparator(elements); ImmutableSortedSet.Builder<String> builder = ImmutableSortedSet.orderedBy(comparator); builder.add(BEFORE_FIRST); builder.add(elements); builder.add(AFTER_LAST); return builder.build().subSet(BEFORE_FIRST_2, AFTER_LAST).asList(); } } public static class ImmutableSortedSetAsListSubListGenerator extends TestStringListGenerator { @Override protected List<String> create(String[] elements) { Comparator<String> comparator = createExplicitComparator(elements); ImmutableSortedSet.Builder<String> builder = ImmutableSortedSet.orderedBy(comparator); builder.add(BEFORE_FIRST); builder.add(elements); builder.add(AFTER_LAST); return builder.build().asList().subList(1, elements.length + 1); } } public static class ImmutableSortedSetSubsetAsListSubListGenerator extends TestStringListGenerator { @Override protected List<String> create(String[] elements) { Comparator<String> comparator = createExplicitComparator(elements); ImmutableSortedSet.Builder<String> builder = ImmutableSortedSet.orderedBy(comparator); builder.add(BEFORE_FIRST); builder.add(BEFORE_FIRST_2); builder.add(elements); builder.add(AFTER_LAST); builder.add(AFTER_LAST_2); return builder.build().subSet(BEFORE_FIRST_2, AFTER_LAST_2) .asList().subList(1, elements.length + 1); } } public abstract static class TestUnhashableSetGenerator extends TestUnhashableCollectionGenerator<Set<UnhashableObject>> implements TestSetGenerator<UnhashableObject> { } private static Ordering<String> createExplicitComparator( String[] elements) { // Collapse equal elements, which Ordering.explicit() doesn't support, while // maintaining the ordering by first occurrence. Set<String> elementsPlus = Sets.newLinkedHashSet(); elementsPlus.add(BEFORE_FIRST); elementsPlus.add(BEFORE_FIRST_2); elementsPlus.addAll(Arrays.asList(elements)); elementsPlus.add(AFTER_LAST); elementsPlus.add(AFTER_LAST_2); return Ordering.explicit(Lists.newArrayList(elementsPlus)); } /* * All the ContiguousSet generators below manually reject nulls here. In principle, we'd like to * defer that to Range, since it's ContiguousSet.create() that's used to create the sets. However, * that gets messy here, and we already have null tests for Range. */ /* * These generators also rely on consecutive integer inputs (not necessarily in order, but no * holes). */ // SetCreationTester has some tests that pass in duplicates. Dedup them. private static <E extends Comparable<? super E>> SortedSet<E> nullCheckedTreeSet(E[] elements) { SortedSet<E> set = newTreeSet(); for (E element : elements) { // Explicit null check because TreeSet wrongly accepts add(null) when empty. set.add(checkNotNull(element)); } return set; } public static class ContiguousSetGenerator extends AbstractContiguousSetGenerator { @Override protected SortedSet<Integer> create(Integer[] elements) { return checkedCreate(nullCheckedTreeSet(elements)); } } public static class ContiguousSetHeadsetGenerator extends AbstractContiguousSetGenerator { @Override protected SortedSet<Integer> create(Integer[] elements) { SortedSet<Integer> set = nullCheckedTreeSet(elements); int tooHigh = (set.isEmpty()) ? 0 : set.last() + 1; set.add(tooHigh); return checkedCreate(set).headSet(tooHigh); } } public static class ContiguousSetTailsetGenerator extends AbstractContiguousSetGenerator { @Override protected SortedSet<Integer> create(Integer[] elements) { SortedSet<Integer> set = nullCheckedTreeSet(elements); int tooLow = (set.isEmpty()) ? 0 : set.first() - 1; set.add(tooLow); return checkedCreate(set).tailSet(tooLow + 1); } } public static class ContiguousSetSubsetGenerator extends AbstractContiguousSetGenerator { @Override protected SortedSet<Integer> create(Integer[] elements) { SortedSet<Integer> set = nullCheckedTreeSet(elements); if (set.isEmpty()) { /* * The (tooLow + 1, tooHigh) arguments below would be invalid because tooLow would be * greater than tooHigh. */ return ContiguousSet.create(Range.openClosed(0, 1), DiscreteDomain.integers()).subSet(0, 1); } int tooHigh = set.last() + 1; int tooLow = set.first() - 1; set.add(tooHigh); set.add(tooLow); return checkedCreate(set).subSet(tooLow + 1, tooHigh); } } private abstract static class AbstractContiguousSetGenerator extends TestIntegerSortedSetGenerator { protected final ContiguousSet<Integer> checkedCreate(SortedSet<Integer> elementsSet) { List<Integer> elements = newArrayList(elementsSet); /* * A ContiguousSet can't have holes. If a test demands a hole, it should be changed so that it * doesn't need one, or it should be suppressed for ContiguousSet. */ for (int i = 0; i < elements.size() - 1; i++) { assertEquals(elements.get(i) + 1, (int) elements.get(i + 1)); } Range<Integer> range = (elements.isEmpty()) ? Range.closedOpen(0, 0) : Range.encloseAll(elements); return ContiguousSet.create(range, DiscreteDomain.integers()); } } }
Java
/* * Copyright (C) 2009 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.collect.testing.google; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.Multiset; import com.google.common.collect.Multiset.Entry; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.ConcurrentModificationException; import java.util.Iterator; /** * Common superclass for {@link MultisetSetCountUnconditionallyTester} and * {@link MultisetSetCountConditionallyTester}. It is used by those testers to * test calls to the unconditional {@code setCount()} method and calls to the * conditional {@code setCount()} method when the expected present count is * correct. * * @author Chris Povirk */ @GwtCompatible(emulated = true) public abstract class AbstractMultisetSetCountTester<E> extends AbstractMultisetTester<E> { /* * TODO: consider adding MultisetFeatures.SUPPORTS_SET_COUNT. Currently we * assume that using setCount() to increase the count is permitted iff add() * is permitted and similarly for decrease/remove(). We assume that a * setCount() no-op is permitted if either add() or remove() is permitted, * though we also allow it to "succeed" if neither is permitted. */ private void assertSetCount(E element, int count) { setCountCheckReturnValue(element, count); assertEquals( "multiset.count() should return the value passed to setCount()", count, getMultiset().count(element)); int size = 0; for (Multiset.Entry<E> entry : getMultiset().entrySet()) { size += entry.getCount(); } assertEquals( "multiset.size() should be the sum of the counts of all entries", size, getMultiset().size()); } /** * Call the {@code setCount()} method under test, and check its return value. */ abstract void setCountCheckReturnValue(E element, int count); /** * Call the {@code setCount()} method under test, but do not check its return * value. Callers should use this method over * {@link #setCountCheckReturnValue(Object, int)} when they expect * {@code setCount()} to throw an exception, as checking the return value * could produce an incorrect error message like * "setCount() should return the original count" instead of the message passed * to a later invocation of {@code fail()}, like "setCount should throw * UnsupportedOperationException." */ abstract void setCountNoCheckReturnValue(E element, int count); private void assertSetCountIncreasingFailure(E element, int count) { try { setCountNoCheckReturnValue(element, count); fail("a call to multiset.setCount() to increase an element's count " + "should throw"); } catch (UnsupportedOperationException expected) { } } private void assertSetCountDecreasingFailure(E element, int count) { try { setCountNoCheckReturnValue(element, count); fail("a call to multiset.setCount() to decrease an element's count " + "should throw"); } catch (UnsupportedOperationException expected) { } } // Unconditional setCount no-ops. private void assertZeroToZero() { assertSetCount(samples.e3, 0); } private void assertOneToOne() { assertSetCount(samples.e0, 1); } private void assertThreeToThree() { initThreeCopies(); assertSetCount(samples.e0, 3); } @CollectionFeature.Require(SUPPORTS_ADD) public void testSetCount_zeroToZero_addSupported() { assertZeroToZero(); } @CollectionFeature.Require(SUPPORTS_REMOVE) public void testSetCount_zeroToZero_removeSupported() { assertZeroToZero(); } @CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE}) public void testSetCount_zeroToZero_unsupported() { try { assertZeroToZero(); } catch (UnsupportedOperationException tolerated) { } } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(SUPPORTS_ADD) public void testSetCount_oneToOne_addSupported() { assertOneToOne(); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testSetCount_oneToOne_removeSupported() { assertOneToOne(); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE}) public void testSetCount_oneToOne_unsupported() { try { assertOneToOne(); } catch (UnsupportedOperationException tolerated) { } } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_ADD) public void testSetCount_threeToThree_addSupported() { assertThreeToThree(); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testSetCount_threeToThree_removeSupported() { assertThreeToThree(); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE}) public void testSetCount_threeToThree_unsupported() { try { assertThreeToThree(); } catch (UnsupportedOperationException tolerated) { } } // Unconditional setCount size increases: @CollectionFeature.Require(SUPPORTS_ADD) public void testSetCount_zeroToOne_supported() { assertSetCount(samples.e3, 1); } @CollectionFeature.Require({SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) public void testSetCountZeroToOneConcurrentWithIteration() { try { Iterator<E> iterator = collection.iterator(); assertSetCount(samples.e3, 1); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @CollectionFeature.Require({SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) public void testSetCountZeroToOneConcurrentWithEntrySetIteration() { try { Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator(); assertSetCount(samples.e3, 1); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @CollectionFeature.Require(SUPPORTS_ADD) public void testSetCount_zeroToThree_supported() { assertSetCount(samples.e3, 3); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(SUPPORTS_ADD) public void testSetCount_oneToThree_supported() { assertSetCount(samples.e0, 3); } @CollectionFeature.Require(absent = SUPPORTS_ADD) public void testSetCount_zeroToOne_unsupported() { assertSetCountIncreasingFailure(samples.e3, 1); } @CollectionFeature.Require(absent = SUPPORTS_ADD) public void testSetCount_zeroToThree_unsupported() { assertSetCountIncreasingFailure(samples.e3, 3); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(absent = SUPPORTS_ADD) public void testSetCount_oneToThree_unsupported() { assertSetCountIncreasingFailure(samples.e3, 3); } // Unconditional setCount size decreases: @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testSetCount_oneToZero_supported() { assertSetCount(samples.e0, 0); } @CollectionFeature.Require({SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) @CollectionSize.Require(absent = ZERO) public void testSetCountOneToZeroConcurrentWithIteration() { try { Iterator<E> iterator = collection.iterator(); assertSetCount(samples.e0, 0); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @CollectionFeature.Require({SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) @CollectionSize.Require(absent = ZERO) public void testSetCountOneToZeroConcurrentWithEntrySetIteration() { try { Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator(); assertSetCount(samples.e0, 0); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testSetCount_threeToZero_supported() { initThreeCopies(); assertSetCount(samples.e0, 0); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testSetCount_threeToOne_supported() { initThreeCopies(); assertSetCount(samples.e0, 1); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testSetCount_oneToZero_unsupported() { assertSetCountDecreasingFailure(samples.e0, 0); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testSetCount_threeToZero_unsupported() { initThreeCopies(); assertSetCountDecreasingFailure(samples.e0, 0); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testSetCount_threeToOne_unsupported() { initThreeCopies(); assertSetCountDecreasingFailure(samples.e0, 1); } // setCount with nulls: @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES}) public void testSetCount_removeNull_nullSupported() { initCollectionWithNullElement(); assertSetCount(null, 0); } @CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES}, absent = RESTRICTS_ELEMENTS) public void testSetCount_addNull_nullSupported() { assertSetCount(null, 1); } @CollectionFeature.Require(value = SUPPORTS_ADD, absent = ALLOWS_NULL_VALUES) public void testSetCount_addNull_nullUnsupported() { try { setCountNoCheckReturnValue(null, 1); fail("adding null with setCount() should throw NullPointerException"); } catch (NullPointerException expected) { } } @CollectionFeature.Require(ALLOWS_NULL_VALUES) public void testSetCount_noOpNull_nullSupported() { try { assertSetCount(null, 0); } catch (UnsupportedOperationException tolerated) { } } @CollectionFeature.Require(absent = ALLOWS_NULL_VALUES) public void testSetCount_noOpNull_nullUnsupported() { try { assertSetCount(null, 0); } catch (NullPointerException tolerated) { } catch (UnsupportedOperationException tolerated) { } } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(ALLOWS_NULL_VALUES) public void testSetCount_existingNoNopNull_nullSupported() { initCollectionWithNullElement(); try { assertSetCount(null, 1); } catch (UnsupportedOperationException tolerated) { } } // Negative count. @CollectionFeature.Require(SUPPORTS_REMOVE) public void testSetCount_negative_removeSupported() { try { setCountNoCheckReturnValue(samples.e3, -1); fail("calling setCount() with a negative count should throw " + "IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testSetCount_negative_removeUnsupported() { try { setCountNoCheckReturnValue(samples.e3, -1); fail("calling setCount() with a negative count should throw " + "IllegalArgumentException or UnsupportedOperationException"); } catch (IllegalArgumentException expected) { } catch (UnsupportedOperationException expected) { } } // TODO: test adding element of wrong type }
Java
/* * Copyright (C) 2013 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.collect.testing.google; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.Collections; import java.util.List; /** * Tests for {@code Multiset#remove}, {@code Multiset.removeAll}, and {@code Multiset.retainAll} * not already covered by the corresponding Collection testers. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class MultisetRemoveTester<E> extends AbstractMultisetTester<E> { @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemoveNegative() { try { getMultiset().remove(samples.e0, -1); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} expectUnchanged(); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testRemoveUnsupported() { try { getMultiset().remove(samples.e0, 2); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException expected) {} } @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemoveZeroNoOp() { int originalCount = getMultiset().count(samples.e0); assertEquals("old count", originalCount, getMultiset().remove(samples.e0, 0)); expectUnchanged(); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemove_occurrences_present() { assertEquals("multiset.remove(present, 2) didn't return the old count", 1, getMultiset().remove(samples.e0, 2)); assertFalse("multiset contains present after multiset.remove(present, 2)", getMultiset().contains(samples.e0)); assertEquals(0, getMultiset().count(samples.e0)); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemove_some_occurrences_present() { initThreeCopies(); assertEquals("multiset.remove(present, 2) didn't return the old count", 3, getMultiset().remove(samples.e0, 2)); assertTrue("multiset contains present after multiset.remove(present, 2)", getMultiset().contains(samples.e0)); assertEquals(1, getMultiset().count(samples.e0)); } @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemove_occurrences_absent() { assertEquals("multiset.remove(absent, 0) didn't return 0", 0, getMultiset().remove(samples.e3, 2)); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testRemove_occurrences_unsupported_absent() { // notice: we don't care whether it succeeds, or fails with UOE try { assertEquals( "multiset.remove(absent, 2) didn't return 0 or throw an exception", 0, getMultiset().remove(samples.e3, 2)); } catch (UnsupportedOperationException ok) {} } @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemove_occurrences_0() { int oldCount = getMultiset().count(samples.e0); assertEquals("multiset.remove(E, 0) didn't return the old count", oldCount, getMultiset().remove(samples.e0, 0)); } @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemove_occurrences_negative() { try { getMultiset().remove(samples.e0, -1); fail("multiset.remove(E, -1) didn't throw an exception"); } catch (IllegalArgumentException required) {} } @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemove_occurrences_wrongType() { assertEquals("multiset.remove(wrongType, 1) didn't return 0", 0, getMultiset().remove(WrongType.VALUE, 1)); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES}) public void testRemove_nullPresent() { initCollectionWithNullElement(); assertEquals(1, getMultiset().remove(null, 2)); assertFalse("multiset contains present after multiset.remove(present, 2)", getMultiset().contains(null)); assertEquals(0, getMultiset().count(null)); } @CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_QUERIES}) public void testRemove_nullAbsent() { assertEquals(0, getMultiset().remove(null, 2)); } @CollectionFeature.Require(value = SUPPORTS_REMOVE, absent = ALLOWS_NULL_QUERIES) public void testRemove_nullForbidden() { try { getMultiset().remove(null, 2); fail("Expected NullPointerException"); } catch (NullPointerException expected) {} } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemoveAllIgnoresCount() { initThreeCopies(); assertTrue(getMultiset().removeAll(Collections.singleton(samples.e0))); ASSERT.that(getMultiset()).isEmpty(); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRetainAllIgnoresCount() { initThreeCopies(); List<E> contents = Helpers.copyToList(getMultiset()); assertFalse(getMultiset().retainAll(Collections.singleton(samples.e0))); expectContents(contents); } }
Java
/* * Copyright (C) 2013 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.collect.testing.google; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * Tests for {@code Multiset#count}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class MultisetCountTester<E> extends AbstractMultisetTester<E> { public void testCount_0() { assertEquals("multiset.count(missing) didn't return 0", 0, getMultiset().count(samples.e3)); } @CollectionSize.Require(absent = ZERO) public void testCount_1() { assertEquals("multiset.count(present) didn't return 1", 1, getMultiset().count(samples.e0)); } @CollectionSize.Require(SEVERAL) public void testCount_3() { initThreeCopies(); assertEquals("multiset.count(thriceContained) didn't return 3", 3, getMultiset().count(samples.e0)); } @CollectionFeature.Require(ALLOWS_NULL_QUERIES) public void testCount_nullAbsent() { assertEquals("multiset.count(null) didn't return 0", 0, getMultiset().count(null)); } @CollectionFeature.Require(absent = ALLOWS_NULL_QUERIES) public void testCount_null_forbidden() { try { getMultiset().count(null); fail("Expected NullPointerException"); } catch (NullPointerException expected) {} } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(ALLOWS_NULL_VALUES) public void testCount_nullPresent() { initCollectionWithNullElement(); assertEquals(1, getMultiset().count(null)); } public void testCount_wrongType() { assertEquals("multiset.count(wrongType) didn't return 0", 0, getMultiset().count(WrongType.VALUE)); } }
Java
/* * Copyright (C) 2009 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.collect.testing; import com.google.gwt.core.client.GwtScriptOnly; import com.google.gwt.lang.Array; /** * Version of {@link GwtPlatform} used in web-mode. It includes methods in * {@link Platform} that requires different implementions in web mode and * hosted mode. It is factored out from {@link Platform} because <code> * {@literal @}GwtScriptOnly</code> only supports public classes and methods. * * @author Hayward Chan */ @GwtScriptOnly public final class GwtPlatform { private GwtPlatform() {} public static <T> T[] clone(T[] array) { return (T[]) Array.clone(array); } }
Java
/* * Copyright (C) 2009 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.collect.testing; import static java.util.Collections.sort; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import com.google.common.annotations.GwtCompatible; import junit.framework.Assert; import junit.framework.AssertionFailedError; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; @GwtCompatible(emulated = true) public class Helpers { // Clone of Objects.equal static boolean equal(Object a, Object b) { return a == b || (a != null && a.equals(b)); } // Clone of Lists.newArrayList public static <E> List<E> copyToList(Iterable<? extends E> elements) { List<E> list = new ArrayList<E>(); addAll(list, elements); return list; } public static <E> List<E> copyToList(E[] elements) { return copyToList(Arrays.asList(elements)); } // Clone of Sets.newLinkedHashSet public static <E> Set<E> copyToSet(Iterable<? extends E> elements) { Set<E> set = new LinkedHashSet<E>(); addAll(set, elements); return set; } public static <E> Set<E> copyToSet(E[] elements) { return copyToSet(Arrays.asList(elements)); } // Would use Maps.immutableEntry public static <K, V> Entry<K, V> mapEntry(K key, V value) { return Collections.singletonMap(key, value).entrySet().iterator().next(); } public static void assertEqualIgnoringOrder( Iterable<?> expected, Iterable<?> actual) { List<?> exp = copyToList(expected); List<?> act = copyToList(actual); String actString = act.toString(); // Of course we could take pains to give the complete description of the // problem on any failure. // Yeah it's n^2. for (Object object : exp) { if (!act.remove(object)) { Assert.fail("did not contain expected element " + object + ", " + "expected = " + exp + ", actual = " + actString); } } assertTrue("unexpected elements: " + act, act.isEmpty()); } public static void assertContentsAnyOrder( Iterable<?> actual, Object... expected) { assertEqualIgnoringOrder(Arrays.asList(expected), actual); } public static <E> boolean addAll( Collection<E> addTo, Iterable<? extends E> elementsToAdd) { boolean modified = false; for (E e : elementsToAdd) { modified |= addTo.add(e); } return modified; } static <T> Iterable<T> reverse(final List<T> list) { return new Iterable<T>() { @Override public Iterator<T> iterator() { final ListIterator<T> listIter = list.listIterator(list.size()); return new Iterator<T>() { @Override public boolean hasNext() { return listIter.hasPrevious(); } @Override public T next() { return listIter.previous(); } @Override public void remove() { listIter.remove(); } }; } }; } static <T> Iterator<T> cycle(final Iterable<T> iterable) { return new Iterator<T>() { Iterator<T> iterator = Collections.<T>emptySet().iterator(); @Override public boolean hasNext() { return true; } @Override public T next() { if (!iterator.hasNext()) { iterator = iterable.iterator(); } return iterator.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } static <T> T get(Iterator<T> iterator, int position) { for (int i = 0; i < position; i++) { iterator.next(); } return iterator.next(); } static void fail(Throwable cause, Object message) { AssertionFailedError assertionFailedError = new AssertionFailedError(String.valueOf(message)); assertionFailedError.initCause(cause); throw assertionFailedError; } public static <K, V> Comparator<Entry<K, V>> entryComparator( final Comparator<? super K> keyComparator) { return new Comparator<Entry<K, V>>() { @Override @SuppressWarnings("unchecked") // no less safe than putting it in the map! public int compare(Entry<K, V> a, Entry<K, V> b) { return (keyComparator == null) ? ((Comparable) a.getKey()).compareTo(b.getKey()) : keyComparator.compare(a.getKey(), b.getKey()); } }; } public static <T> void testComparator( Comparator<? super T> comparator, T... valuesInExpectedOrder) { testComparator(comparator, Arrays.asList(valuesInExpectedOrder)); } public static <T> void testComparator( Comparator<? super T> comparator, List<T> valuesInExpectedOrder) { // This does an O(n^2) test of all pairs of values in both orders for (int i = 0; i < valuesInExpectedOrder.size(); i++) { T t = valuesInExpectedOrder.get(i); for (int j = 0; j < i; j++) { T lesser = valuesInExpectedOrder.get(j); assertTrue(comparator + ".compare(" + lesser + ", " + t + ")", comparator.compare(lesser, t) < 0); } assertEquals(comparator + ".compare(" + t + ", " + t + ")", 0, comparator.compare(t, t)); for (int j = i + 1; j < valuesInExpectedOrder.size(); j++) { T greater = valuesInExpectedOrder.get(j); assertTrue(comparator + ".compare(" + greater + ", " + t + ")", comparator.compare(greater, t) > 0); } } } public static <T extends Comparable<? super T>> void testCompareToAndEquals( List<T> valuesInExpectedOrder) { // This does an O(n^2) test of all pairs of values in both orders for (int i = 0; i < valuesInExpectedOrder.size(); i++) { T t = valuesInExpectedOrder.get(i); for (int j = 0; j < i; j++) { T lesser = valuesInExpectedOrder.get(j); assertTrue(lesser + ".compareTo(" + t + ')', lesser.compareTo(t) < 0); assertFalse(lesser.equals(t)); } assertEquals(t + ".compareTo(" + t + ')', 0, t.compareTo(t)); assertTrue(t.equals(t)); for (int j = i + 1; j < valuesInExpectedOrder.size(); j++) { T greater = valuesInExpectedOrder.get(j); assertTrue(greater + ".compareTo(" + t + ')', greater.compareTo(t) > 0); assertFalse(greater.equals(t)); } } } /** * Returns a collection that simulates concurrent modification by * having its size method return incorrect values. This is useful * for testing methods that must treat the return value from size() * as a hint only. * * @param delta the difference between the true size of the * collection and the values returned by the size method */ public static <T> Collection<T> misleadingSizeCollection(final int delta) { // It would be nice to be able to return a real concurrent // collection like ConcurrentLinkedQueue, so that e.g. concurrent // iteration would work, but that would not be GWT-compatible. return new ArrayList<T>() { @Override public int size() { return Math.max(0, super.size() + delta); } }; } /** * Returns a "nefarious" map entry with the specified key and value, * meaning an entry that is suitable for testing that map entries cannot be * modified via a nefarious implementation of equals. This is used for testing * unmodifiable collections of map entries; for example, it should not be * possible to access the raw (modifiable) map entry via a nefarious equals * method. */ public static <K, V> Map.Entry<K, V> nefariousMapEntry(final K key, final V value) { return new Map.Entry<K, V>() { @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(V value) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (o instanceof Map.Entry) { Map.Entry<K, V> e = (Map.Entry<K, V>) o; e.setValue(value); // muhahaha! return equal(this.getKey(), e.getKey()) && equal(this.getValue(), e.getValue()); } return false; } @Override public int hashCode() { K k = getKey(); V v = getValue(); return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode()); } /** * Returns a string representation of the form <code>{key}={value}</code>. */ @Override public String toString() { return getKey() + "=" + getValue(); } }; } static <E> List<E> castOrCopyToList(Iterable<E> iterable) { if (iterable instanceof List) { return (List<E>) iterable; } List<E> list = new ArrayList<E>(); for (E e : iterable) { list.add(e); } return list; } private static final Comparator<Comparable> NATURAL_ORDER = new Comparator<Comparable>() { @SuppressWarnings("unchecked") // assume any Comparable is Comparable<Self> @Override public int compare(Comparable left, Comparable right) { return left.compareTo(right); } }; public static <K extends Comparable, V> Iterable<Entry<K, V>> orderEntriesByKey( List<Entry<K, V>> insertionOrder) { sort(insertionOrder, Helpers.<K, V>entryComparator(NATURAL_ORDER)); return insertionOrder; } /** * Private replacement for {@link com.google.gwt.user.client.rpc.GwtTransient} to work around * build-system quirks. */ private @interface GwtTransient {} /** * Compares strings in natural order except that null comes immediately before a given value. This * works better than Ordering.natural().nullsFirst() because, if null comes before all other * values, it lies outside the submap/submultiset ranges we test, and the variety of tests that * exercise null handling fail on those subcollections. */ public abstract static class NullsBefore implements Comparator<String>, Serializable { /* * We don't serialize this class in GWT, so we don't care about whether GWT will serialize this * field. */ @GwtTransient private final String justAfterNull; protected NullsBefore(String justAfterNull) { if (justAfterNull == null) { throw new NullPointerException(); } this.justAfterNull = justAfterNull; } @Override public int compare(String lhs, String rhs) { if (lhs == rhs) { return 0; } if (lhs == null) { // lhs (null) comes just before justAfterNull. // If rhs is b, lhs comes first. if (rhs.equals(justAfterNull)) { return -1; } return justAfterNull.compareTo(rhs); } if (rhs == null) { // rhs (null) comes just before justAfterNull. // If lhs is b, rhs comes first. if (lhs.equals(justAfterNull)) { return 1; } return lhs.compareTo(justAfterNull); } return lhs.compareTo(rhs); } @Override public boolean equals(Object obj) { if (obj instanceof NullsBefore) { NullsBefore other = (NullsBefore) obj; return justAfterNull.equals(other.justAfterNull); } return false; } @Override public int hashCode() { return justAfterNull.hashCode(); } } public static final class NullsBeforeB extends NullsBefore { public static final NullsBeforeB INSTANCE = new NullsBeforeB(); private NullsBeforeB() { super("b"); } } public static final class NullsBeforeTwo extends NullsBefore { public static final NullsBeforeTwo INSTANCE = new NullsBeforeTwo(); private NullsBeforeTwo() { super("two"); // from TestStringSortedMapGenerator's sample keys } } }
Java
/* * Copyright (C) 2008 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.collect.testing; /** * Minimal GWT emulation of {@code com.google.common.collect.testing.Platform}. * * <p><strong>This .java file should never be consumed by javac.</strong> * * @author Hayward Chan */ class Platform { static boolean checkIsInstance(Class<?> clazz, Object obj) { /* * In GWT, we can't tell whether obj is an instance of clazz because GWT * doesn't support reflections. For testing purposes, we give up this * particular assertion (so that we can keep the rest). */ return true; } // Class.cast is not supported in GWT. static void checkCast(Class<?> clazz, Object obj) { } static <T> T[] clone(T[] array) { return GwtPlatform.clone(array); } // TODO: Consolidate different copies in one single place. static String format(String template, Object... args) { // start substituting the arguments into the '%s' placeholders StringBuilder builder = new StringBuilder( template.length() + 16 * args.length); int templateStart = 0; int i = 0; while (i < args.length) { int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template.substring(templateStart, placeholderStart)); builder.append(args[i++]); templateStart = placeholderStart + 2; } builder.append(template.substring(templateStart)); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { builder.append(" ["); builder.append(args[i++]); while (i < args.length) { builder.append(", "); builder.append(args[i++]); } builder.append("]"); } return builder.toString(); } static String classGetSimpleName(Class<?> clazz) { throw new UnsupportedOperationException("Shouldn't be called in GWT."); } }
Java
/* * Copyright (C) 2007 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests add operations on a set. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.SetTestSuiteBuilder}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class SetAddTester<E> extends AbstractSetTester<E> { @CollectionFeature.Require(SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAdd_supportedPresent() { assertFalse("add(present) should return false", getSet().add(samples.e0)); expectUnchanged(); } @CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testAdd_supportedNullPresent() { E[] array = createArrayWithNullElement(); collection = getSubjectGenerator().create(array); assertFalse("add(nullPresent) should return false", getSet().add(null)); expectContents(array); } }
Java
/* * Copyright (C) 2007 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.Arrays; import java.util.List; /** * A generic JUnit test which tests {@code toArray()} operations on a * collection. Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * @author Kevin Bourrillion * @author Chris Povirk */ @GwtCompatible(emulated = true) public class CollectionToArrayTester<E> extends AbstractCollectionTester<E> { public void testToArray_noArgs() { Object[] array = collection.toArray(); expectArrayContentsAnyOrder(createSamplesArray(), array); } /** * {@link Collection#toArray(Object[])} says: "Note that * <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>." * * <p>For maximum effect, the collection under test should be created from an * element array of a type other than {@code Object[]}. */ public void testToArray_isPlainObjectArray() { Object[] array = collection.toArray(); assertEquals(Object[].class, array.getClass()); } public void testToArray_emptyArray() { E[] empty = getSubjectGenerator().createArray(0); E[] array = collection.toArray(empty); assertEquals("toArray(emptyT[]) should return an array of type T", empty.getClass(), array.getClass()); assertEquals("toArray(emptyT[]).length:", getNumElements(), array.length); expectArrayContentsAnyOrder(createSamplesArray(), array); } @CollectionFeature.Require(KNOWN_ORDER) public void testToArray_emptyArray_ordered() { E[] empty = getSubjectGenerator().createArray(0); E[] array = collection.toArray(empty); assertEquals("toArray(emptyT[]) should return an array of type T", empty.getClass(), array.getClass()); assertEquals("toArray(emptyT[]).length:", getNumElements(), array.length); expectArrayContentsInOrder(getOrderedElements(), array); } public void testToArray_emptyArrayOfObject() { Object[] in = new Object[0]; Object[] array = collection.toArray(in); assertEquals("toArray(emptyObject[]) should return an array of type Object", Object[].class, array.getClass()); assertEquals("toArray(emptyObject[]).length", getNumElements(), array.length); expectArrayContentsAnyOrder(createSamplesArray(), array); } public void testToArray_rightSizedArray() { E[] array = getSubjectGenerator().createArray(getNumElements()); assertSame("toArray(sameSizeE[]) should return the given array", array, collection.toArray(array)); expectArrayContentsAnyOrder(createSamplesArray(), array); } @CollectionFeature.Require(KNOWN_ORDER) public void testToArray_rightSizedArray_ordered() { E[] array = getSubjectGenerator().createArray(getNumElements()); assertSame("toArray(sameSizeE[]) should return the given array", array, collection.toArray(array)); expectArrayContentsInOrder(getOrderedElements(), array); } public void testToArray_rightSizedArrayOfObject() { Object[] array = new Object[getNumElements()]; assertSame("toArray(sameSizeObject[]) should return the given array", array, collection.toArray(array)); expectArrayContentsAnyOrder(createSamplesArray(), array); } @CollectionFeature.Require(KNOWN_ORDER) public void testToArray_rightSizedArrayOfObject_ordered() { Object[] array = new Object[getNumElements()]; assertSame("toArray(sameSizeObject[]) should return the given array", array, collection.toArray(array)); expectArrayContentsInOrder(getOrderedElements(), array); } public void testToArray_oversizedArray() { E[] array = getSubjectGenerator().createArray(getNumElements() + 2); array[getNumElements()] = samples.e3; array[getNumElements() + 1] = samples.e3; assertSame("toArray(overSizedE[]) should return the given array", array, collection.toArray(array)); List<E> subArray = Arrays.asList(array).subList(0, getNumElements()); E[] expectedSubArray = createSamplesArray(); for (int i = 0; i < getNumElements(); i++) { assertTrue( "toArray(overSizedE[]) should contain element " + expectedSubArray[i], subArray.contains(expectedSubArray[i])); } assertNull("The array element " + "immediately following the end of the collection should be nulled", array[getNumElements()]); // array[getNumElements() + 1] might or might not have been nulled } @CollectionFeature.Require(KNOWN_ORDER) public void testToArray_oversizedArray_ordered() { E[] array = getSubjectGenerator().createArray(getNumElements() + 2); array[getNumElements()] = samples.e3; array[getNumElements() + 1] = samples.e3; assertSame("toArray(overSizedE[]) should return the given array", array, collection.toArray(array)); List<E> expected = getOrderedElements(); for (int i = 0; i < getNumElements(); i++) { assertEquals(expected.get(i), array[i]); } assertNull("The array element " + "immediately following the end of the collection should be nulled", array[getNumElements()]); // array[getNumElements() + 1] might or might not have been nulled } @CollectionSize.Require(absent = ZERO) public void testToArray_emptyArrayOfWrongTypeForNonEmptyCollection() { try { WrongType[] array = new WrongType[0]; collection.toArray(array); fail("toArray(notAssignableTo[]) should throw"); } catch (ArrayStoreException expected) { } } @CollectionSize.Require(ZERO) public void testToArray_emptyArrayOfWrongTypeForEmptyCollection() { WrongType[] array = new WrongType[0]; assertSame( "toArray(sameSizeNotAssignableTo[]) should return the given array", array, collection.toArray(array)); } private void expectArrayContentsAnyOrder(Object[] expected, Object[] actual) { Helpers.assertEqualIgnoringOrder( Arrays.asList(expected), Arrays.asList(actual)); } private void expectArrayContentsInOrder(List<E> expected, Object[] actual) { assertEquals("toArray() ordered contents: ", expected, Arrays.asList(actual)); } }
Java
/* * Copyright (C) 2007 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.ConcurrentModificationException; import java.util.Iterator; /** * A generic JUnit test which tests {@code add} operations on a collection. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * @author Chris Povirk * @author Kevin Bourrillion */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class CollectionAddTester<E> extends AbstractCollectionTester<E> { @CollectionFeature.Require(SUPPORTS_ADD) public void testAdd_supportedNotPresent() { assertTrue("add(notPresent) should return true", collection.add(samples.e3)); expectAdded(samples.e3); } @CollectionFeature.Require(absent = SUPPORTS_ADD) public void testAdd_unsupportedNotPresent() { try { collection.add(samples.e3); fail("add(notPresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); expectMissing(samples.e3); } @CollectionFeature.Require(absent = SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAdd_unsupportedPresent() { try { assertFalse("add(present) should return false or throw", collection.add(samples.e0)); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @CollectionFeature.Require( value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES}, absent = RESTRICTS_ELEMENTS) public void testAdd_nullSupported() { assertTrue("add(null) should return true", collection.add(null)); expectAdded((E) null); } @CollectionFeature.Require(value = SUPPORTS_ADD, absent = ALLOWS_NULL_VALUES) public void testAdd_nullUnsupported() { try { collection.add(null); fail("add(null) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullMissingWhenNullUnsupported( "Should not contain null after unsupported add(null)"); } @CollectionFeature.Require({SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) @CollectionSize.Require(absent = ZERO) public void testAddConcurrentWithIteration() { try { Iterator<E> iterator = collection.iterator(); assertTrue(collection.add(samples.e3)); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } }
Java
/* * Copyright (C) 2007 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.collect.testing.testers; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET; import static com.google.common.collect.testing.testers.Platform.listListIteratorTesterNumIterations; import static java.util.Collections.singleton; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.IteratorFeature; import com.google.common.collect.testing.ListIteratorTester; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.ListFeature; import java.util.List; import java.util.ListIterator; import java.util.Set; /** * A generic JUnit test which tests {@code listIterator} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * @author Chris Povirk * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class ListListIteratorTester<E> extends AbstractListTester<E> { // TODO: switch to DerivedIteratorTestSuiteBuilder @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @ListFeature.Require(absent = {SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX}) public void testListIterator_unmodifiable() { runListIteratorTest(UNMODIFIABLE); } /* * For now, we don't cope with testing this when the list supports only some * modification operations. */ @CollectionFeature.Require(SUPPORTS_REMOVE) @ListFeature.Require({SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX}) public void testListIterator_fullyModifiable() { runListIteratorTest(MODIFIABLE); } private void runListIteratorTest(Set<IteratorFeature> features) { new ListIteratorTester<E>( listListIteratorTesterNumIterations(), singleton(samples.e4), features, Helpers.copyToList(getOrderedElements()), 0) { { // TODO: don't set this universally stopTestingWhenAddThrowsException(); } @Override protected ListIterator<E> newTargetIterator() { resetCollection(); return getList().listIterator(); } @Override protected void verify(List<E> elements) { expectContents(elements); } }.test(); } public void testListIterator_tooLow() { try { getList().listIterator(-1); fail(); } catch (IndexOutOfBoundsException expected) { } } public void testListIterator_tooHigh() { try { getList().listIterator(getNumElements() + 1); fail(); } catch (IndexOutOfBoundsException expected) { } } public void testListIterator_atSize() { getList().listIterator(getNumElements()); // TODO: run the iterator through ListIteratorTester } }
Java
/* * Copyright (C) 2008 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_REMOVE_WITH_INDEX; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET; import static java.util.Collections.emptyList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.ListFeature; import com.google.common.testing.SerializableTester; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * A generic JUnit test which tests {@code subList()} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * @author Chris Povirk */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class ListSubListTester<E> extends AbstractListTester<E> { public void testSubList_startNegative() { try { getList().subList(-1, 0); fail("subList(-1, 0) should throw"); } catch (IndexOutOfBoundsException expected) { } } public void testSubList_endTooLarge() { try { getList().subList(0, getNumElements() + 1); fail("subList(0, size + 1) should throw"); } catch (IndexOutOfBoundsException expected) { } } public void testSubList_startGreaterThanEnd() { try { getList().subList(1, 0); fail("subList(1, 0) should throw"); } catch (IndexOutOfBoundsException expected) { } catch (IllegalArgumentException expected) { /* * The subList() docs claim that this should be an * IndexOutOfBoundsException, but many JDK implementations throw * IllegalArgumentException: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4506427 */ } } public void testSubList_empty() { assertEquals("subList(0, 0) should be empty", emptyList(), getList().subList(0, 0)); } public void testSubList_entireList() { assertEquals("subList(0, size) should be equal to the original list", getList(), getList().subList(0, getNumElements())); } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testSubList_subListRemoveAffectsOriginal() { List<E> subList = getList().subList(0, 1); subList.remove(0); List<E> expected = Arrays.asList(createSamplesArray()).subList(1, getNumElements()); expectContents(expected); } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testSubList_subListClearAffectsOriginal() { List<E> subList = getList().subList(0, 1); subList.clear(); List<E> expected = Arrays.asList(createSamplesArray()).subList(1, getNumElements()); expectContents(expected); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testSubList_subListAddAffectsOriginal() { List<E> subList = getList().subList(0, 0); subList.add(samples.e3); expectAdded(0, samples.e3); } @ListFeature.Require(SUPPORTS_SET) @CollectionSize.Require(absent = ZERO) public void testSubList_subListSetAffectsOriginal() { List<E> subList = getList().subList(0, 1); subList.set(0, samples.e3); List<E> expected = Helpers.copyToList(createSamplesArray()); expected.set(0, samples.e3); expectContents(expected); } @ListFeature.Require(SUPPORTS_SET) @CollectionSize.Require(absent = ZERO) public void testSubList_originalListSetAffectsSubList() { List<E> subList = getList().subList(0, 1); getList().set(0, samples.e3); assertEquals("A set() call to a list after a sublist has been created " + "should be reflected in the sublist", Collections.singletonList(samples.e3), subList); } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_subListRemoveAffectsOriginalLargeList() { List<E> subList = getList().subList(1, 3); subList.remove(samples.e2); List<E> expected = Helpers.copyToList(createSamplesArray()); expected.remove(2); expectContents(expected); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_subListAddAtIndexAffectsOriginalLargeList() { List<E> subList = getList().subList(2, 3); subList.add(0, samples.e3); expectAdded(2, samples.e3); } @ListFeature.Require(SUPPORTS_SET) @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_subListSetAffectsOriginalLargeList() { List<E> subList = getList().subList(1, 2); subList.set(0, samples.e3); List<E> expected = Helpers.copyToList(createSamplesArray()); expected.set(1, samples.e3); expectContents(expected); } @ListFeature.Require(SUPPORTS_SET) @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_originalListSetAffectsSubListLargeList() { List<E> subList = getList().subList(1, 3); getList().set(1, samples.e3); assertEquals("A set() call to a list after a sublist has been created " + "should be reflected in the sublist", Arrays.asList(samples.e3, samples.e2), subList); } public void testSubList_ofSubListEmpty() { List<E> subList = getList().subList(0, 0).subList(0, 0); assertEquals("subList(0, 0).subList(0, 0) should be an empty list", emptyList(), subList); } @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_ofSubListNonEmpty() { List<E> subList = getList().subList(0, 2).subList(1, 2); assertEquals("subList(0, 2).subList(1, 2) " + "should be a single-element list of the element at index 1", Collections.singletonList(getOrderedElements().get(1)), subList); } @CollectionSize.Require(absent = {ZERO}) public void testSubList_size() { List<E> list = getList(); int size = getNumElements(); assertEquals(list.subList(0, size).size(), size); assertEquals(list.subList(0, size - 1).size(), size - 1); assertEquals(list.subList(1, size).size(), size - 1); assertEquals(list.subList(size, size).size(), 0); assertEquals(list.subList(0, 0).size(), 0); } @CollectionSize.Require(absent = {ZERO}) public void testSubList_isEmpty() { List<E> list = getList(); int size = getNumElements(); for (List<E> subList : Arrays.asList( list.subList(0, size), list.subList(0, size - 1), list.subList(1, size), list.subList(0, 0), list.subList(size, size))) { assertEquals(subList.isEmpty(), subList.size() == 0); } } @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_get() { List<E> list = getList(); int size = getNumElements(); List<E> copy = list.subList(0, size); List<E> head = list.subList(0, size - 1); List<E> tail = list.subList(1, size); assertEquals(list.get(0), copy.get(0)); assertEquals(list.get(size - 1), copy.get(size - 1)); assertEquals(list.get(1), tail.get(0)); assertEquals(list.get(size - 1), tail.get(size - 2)); assertEquals(list.get(0), head.get(0)); assertEquals(list.get(size - 2), head.get(size - 2)); for (List<E> subList : Arrays.asList(copy, head, tail)) { for (int index : Arrays.asList(-1, subList.size())) { try { subList.get(index); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expected) { } } } } @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_contains() { List<E> list = getList(); int size = getNumElements(); List<E> copy = list.subList(0, size); List<E> head = list.subList(0, size - 1); List<E> tail = list.subList(1, size); assertTrue(copy.contains(list.get(0))); assertTrue(head.contains(list.get(0))); assertTrue(tail.contains(list.get(1))); // The following assumes all elements are distinct. assertTrue(copy.contains(list.get(size - 1))); assertTrue(head.contains(list.get(size - 2))); assertTrue(tail.contains(list.get(size - 1))); assertFalse(head.contains(list.get(size - 1))); assertFalse(tail.contains(list.get(0))); } @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_indexOf() { List<E> list = getList(); int size = getNumElements(); List<E> copy = list.subList(0, size); List<E> head = list.subList(0, size - 1); List<E> tail = list.subList(1, size); assertEquals(copy.indexOf(list.get(0)), 0); assertEquals(head.indexOf(list.get(0)), 0); assertEquals(tail.indexOf(list.get(1)), 0); // The following assumes all elements are distinct. assertEquals(copy.indexOf(list.get(size - 1)), size - 1); assertEquals(head.indexOf(list.get(size - 2)), size - 2); assertEquals(tail.indexOf(list.get(size - 1)), size - 2); assertEquals(head.indexOf(list.get(size - 1)), -1); assertEquals(tail.indexOf(list.get(0)), -1); } @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_lastIndexOf() { List<E> list = getList(); int size = list.size(); List<E> copy = list.subList(0, size); List<E> head = list.subList(0, size - 1); List<E> tail = list.subList(1, size); assertEquals(copy.lastIndexOf(list.get(size - 1)), size - 1); assertEquals(head.lastIndexOf(list.get(size - 2)), size - 2); assertEquals(tail.lastIndexOf(list.get(size - 1)), size - 2); // The following assumes all elements are distinct. assertEquals(copy.lastIndexOf(list.get(0)), 0); assertEquals(head.lastIndexOf(list.get(0)), 0); assertEquals(tail.lastIndexOf(list.get(1)), 0); assertEquals(head.lastIndexOf(list.get(size - 1)), -1); assertEquals(tail.lastIndexOf(list.get(0)), -1); } @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) public void testReserializeWholeSubList() { SerializableTester.reserializeAndAssert(getList().subList(0, getNumElements())); } @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) public void testReserializeEmptySubList() { SerializableTester.reserializeAndAssert(getList().subList(0, 0)); } @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) @CollectionSize.Require(absent = {ZERO, ONE}) public void testReserializeSubList() { SerializableTester.reserializeAndAssert(getList().subList(0, 2)); } /* * TODO: perform all List tests on subList(), but beware infinite recursion */ }
Java
/* * Copyright (C) 2008 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.collect.testing.testers; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.IteratorFeature; import com.google.common.collect.testing.IteratorTester; import com.google.common.collect.testing.features.CollectionFeature; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; /** * A generic JUnit test which tests {@code iterator} operations on a collection. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * @author Chris Povirk */ @GwtCompatible(emulated = true) public class CollectionIteratorTester<E> extends AbstractCollectionTester<E> { public void testIterator() { List<E> iteratorElements = new ArrayList<E>(); for (E element : collection) { // uses iterator() iteratorElements.add(element); } Helpers.assertEqualIgnoringOrder( Arrays.asList(createSamplesArray()), iteratorElements); } @CollectionFeature.Require(KNOWN_ORDER) public void testIterationOrdering() { List<E> iteratorElements = new ArrayList<E>(); for (E element : collection) { // uses iterator() iteratorElements.add(element); } List<E> expected = Helpers.copyToList(getOrderedElements()); assertEquals("Different ordered iteration", expected, iteratorElements); } // TODO: switch to DerivedIteratorTestSuiteBuilder @CollectionFeature.Require({KNOWN_ORDER, SUPPORTS_ITERATOR_REMOVE}) public void testIterator_knownOrderRemoveSupported() { runIteratorTest(MODIFIABLE, IteratorTester.KnownOrder.KNOWN_ORDER, getOrderedElements()); } @CollectionFeature.Require(value = KNOWN_ORDER, absent = SUPPORTS_ITERATOR_REMOVE) public void testIterator_knownOrderRemoveUnsupported() { runIteratorTest(UNMODIFIABLE, IteratorTester.KnownOrder.KNOWN_ORDER, getOrderedElements()); } @CollectionFeature.Require(absent = KNOWN_ORDER, value = SUPPORTS_ITERATOR_REMOVE) public void testIterator_unknownOrderRemoveSupported() { runIteratorTest(MODIFIABLE, IteratorTester.KnownOrder.UNKNOWN_ORDER, getSampleElements()); } @CollectionFeature.Require(absent = {KNOWN_ORDER, SUPPORTS_ITERATOR_REMOVE}) public void testIterator_unknownOrderRemoveUnsupported() { runIteratorTest(UNMODIFIABLE, IteratorTester.KnownOrder.UNKNOWN_ORDER, getSampleElements()); } private void runIteratorTest(Set<IteratorFeature> features, IteratorTester.KnownOrder knownOrder, Iterable<E> elements) { new IteratorTester<E>(Platform.collectionIteratorTesterNumIterations(), features, elements, knownOrder) { { // TODO: don't set this universally ignoreSunJavaBug6529795(); } @Override protected Iterator<E> newTargetIterator() { resetCollection(); return collection.iterator(); } @Override protected void verify(List<E> elements) { expectContents(elements); } }.test(); } public void testIteratorNoSuchElementException() { Iterator<E> iterator = collection.iterator(); while (iterator.hasNext()) { iterator.next(); } try { iterator.next(); fail("iterator.next() should throw NoSuchElementException"); } catch (NoSuchElementException expected) {} } }
Java
/* * Copyright (C) 2009 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.collect.testing.testers; import com.google.common.annotations.GwtCompatible; import com.google.gwt.core.client.GWT; /** * The emulation source used in GWT. * * @author Hayward Chan */ @GwtCompatible(emulated = true) class Platform { // Use fewer steps in the ListIteratorTester in ListListIteratorTester because it's slow in prod // mode. static int listListIteratorTesterNumIterations() { // TODO(hhchan): It's 4 in java. Figure out why even 3 is too slow in prod mode. return GWT.isProdMode() ? 2 : 4; } // Use fewer steps in the IteratorTester in CollectionIteratorTester because it's slow in prod // mode.. static int collectionIteratorTesterNumIterations() { return GWT.isProdMode() ? 3 : 5; } // TODO: Consolidate different copies in one single place. static String format(String template, Object... args) { // start substituting the arguments into the '%s' placeholders StringBuilder builder = new StringBuilder( template.length() + 16 * args.length); int templateStart = 0; int i = 0; while (i < args.length) { int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template.substring(templateStart, placeholderStart)); builder.append(args[i++]); templateStart = placeholderStart + 2; } builder.append(template.substring(templateStart)); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { builder.append(" ["); builder.append(args[i++]); while (i < args.length) { builder.append(", "); builder.append(args[i++]); } builder.append("]"); } return builder.toString(); } }
Java
/* * Copyright (C) 2007 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; import static java.util.Collections.singletonList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * A generic JUnit test which tests {@code putAll} operations on a map. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * @author Chris Povirk * @author Kevin Bourrillion */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class MapPutAllTester<K, V> extends AbstractMapTester<K, V> { private List<Entry<K, V>> containsNullKey; private List<Entry<K, V>> containsNullValue; @Override public void setUp() throws Exception { super.setUp(); containsNullKey = singletonList(entry(null, samples.e3.getValue())); containsNullValue = singletonList(entry(samples.e3.getKey(), null)); } @MapFeature.Require(SUPPORTS_PUT) public void testPutAll_supportedNothing() { getMap().putAll(emptyMap()); expectUnchanged(); } @MapFeature.Require(absent = SUPPORTS_PUT) public void testPutAll_unsupportedNothing() { try { getMap().putAll(emptyMap()); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @MapFeature.Require(SUPPORTS_PUT) public void testPutAll_supportedNonePresent() { putAll(createDisjointCollection()); expectAdded(samples.e3, samples.e4); } @MapFeature.Require(absent = SUPPORTS_PUT) public void testPutAll_unsupportedNonePresent() { try { putAll(createDisjointCollection()); fail("putAll(nonePresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); expectMissing(samples.e3, samples.e4); } @MapFeature.Require(SUPPORTS_PUT) @CollectionSize.Require(absent = ZERO) public void testPutAll_supportedSomePresent() { putAll(MinimalCollection.of(samples.e3, samples.e0)); expectAdded(samples.e3); } @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) @CollectionSize.Require(absent = ZERO) public void testPutAllSomePresentConcurrentWithEntrySetIteration() { try { Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator(); putAll(MinimalCollection.of(samples.e3, samples.e0)); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require(absent = SUPPORTS_PUT) @CollectionSize.Require(absent = ZERO) public void testPutAll_unsupportedSomePresent() { try { putAll(MinimalCollection.of(samples.e3, samples.e0)); fail("putAll(somePresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @MapFeature.Require(absent = SUPPORTS_PUT) @CollectionSize.Require(absent = ZERO) public void testPutAll_unsupportedAllPresent() { try { putAll(MinimalCollection.of(samples.e0)); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS}) public void testPutAll_nullKeySupported() { putAll(containsNullKey); expectAdded(containsNullKey.get(0)); } @MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_KEYS) public void testPutAll_nullKeyUnsupported() { try { putAll(containsNullKey); fail("putAll(containsNullKey) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullKeyMissingWhenNullKeysUnsupported( "Should not contain null key after unsupported " + "putAll(containsNullKey)"); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES}) public void testPutAll_nullValueSupported() { putAll(containsNullValue); expectAdded(containsNullValue.get(0)); } @MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES) public void testPutAll_nullValueUnsupported() { try { putAll(containsNullValue); fail("putAll(containsNullValue) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullValueMissingWhenNullValuesUnsupported( "Should not contain null value after unsupported " + "putAll(containsNullValue)"); } @MapFeature.Require(SUPPORTS_PUT) public void testPutAll_nullCollectionReference() { try { getMap().putAll(null); fail("putAll(null) should throw NullPointerException"); } catch (NullPointerException expected) { } } private Map<K, V> emptyMap() { return Collections.emptyMap(); } private void putAll(Iterable<Entry<K, V>> entries) { Map<K, V> map = new LinkedHashMap<K, V>(); for (Entry<K, V> entry : entries) { map.put(entry.getKey(), entry.getValue()); } getMap().putAll(map); } }
Java
/* * Copyright (C) 2007 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; /** * A generic JUnit test which tests {@code put} operations on a map. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * @author Chris Povirk * @author Kevin Bourrillion */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class MapPutTester<K, V> extends AbstractMapTester<K, V> { private Entry<K, V> nullKeyEntry; private Entry<K, V> nullValueEntry; private Entry<K, V> nullKeyValueEntry; private Entry<K, V> presentKeyNullValueEntry; @Override public void setUp() throws Exception { super.setUp(); nullKeyEntry = entry(null, samples.e3.getValue()); nullValueEntry = entry(samples.e3.getKey(), null); nullKeyValueEntry = entry(null, null); presentKeyNullValueEntry = entry(samples.e0.getKey(), null); } @MapFeature.Require(SUPPORTS_PUT) public void testPut_supportedNotPresent() { assertNull("put(notPresent, value) should return null", put(samples.e3)); expectAdded(samples.e3); } @MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT}) @CollectionSize.Require(absent = ZERO) public void testPutAbsentConcurrentWithEntrySetIteration() { try { Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator(); put(samples.e3); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT}) @CollectionSize.Require(absent = ZERO) public void testPutAbsentConcurrentWithKeySetIteration() { try { Iterator<K> iterator = getMap().keySet().iterator(); put(samples.e3); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT}) @CollectionSize.Require(absent = ZERO) public void testPutAbsentConcurrentWithValueIteration() { try { Iterator<V> iterator = getMap().values().iterator(); put(samples.e3); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require(absent = SUPPORTS_PUT) public void testPut_unsupportedNotPresent() { try { put(samples.e3); fail("put(notPresent, value) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); expectMissing(samples.e3); } @MapFeature.Require(absent = SUPPORTS_PUT) @CollectionSize.Require(absent = ZERO) public void testPut_unsupportedPresentExistingValue() { try { assertEquals("put(present, existingValue) should return present or throw", samples.e0.getValue(), put(samples.e0)); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @MapFeature.Require(absent = SUPPORTS_PUT) @CollectionSize.Require(absent = ZERO) public void testPut_unsupportedPresentDifferentValue() { try { getMap().put(samples.e0.getKey(), samples.e3.getValue()); fail("put(present, differentValue) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS}) public void testPut_nullKeySupportedNotPresent() { assertNull("put(null, value) should return null", put(nullKeyEntry)); expectAdded(nullKeyEntry); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS}) @CollectionSize.Require(absent = ZERO) public void testPut_nullKeySupportedPresent() { Entry<K, V> newEntry = entry(null, samples.e3.getValue()); initMapWithNullKey(); assertEquals("put(present, value) should return the associated value", getValueForNullKey(), put(newEntry)); Entry<K, V>[] expected = createArrayWithNullKey(); expected[getNullLocation()] = newEntry; expectContents(expected); } @MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_KEYS) public void testPut_nullKeyUnsupported() { try { put(nullKeyEntry); fail("put(null, value) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullKeyMissingWhenNullKeysUnsupported( "Should not contain null key after unsupported put(null, value)"); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES}) public void testPut_nullValueSupported() { assertNull("put(key, null) should return null", put(nullValueEntry)); expectAdded(nullValueEntry); } @MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES) public void testPut_nullValueUnsupported() { try { put(nullValueEntry); fail("put(key, null) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullValueMissingWhenNullValuesUnsupported( "Should not contain null value after unsupported put(key, null)"); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testPut_replaceWithNullValueSupported() { assertEquals("put(present, null) should return the associated value", samples.e0.getValue(), put(presentKeyNullValueEntry)); expectReplacement(presentKeyNullValueEntry); } @MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testPut_replaceWithNullValueUnsupported() { try { put(presentKeyNullValueEntry); fail("put(present, null) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullValueMissingWhenNullValuesUnsupported( "Should not contain null after unsupported put(present, null)"); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testPut_replaceNullValueWithNullSupported() { initMapWithNullValue(); assertNull("put(present, null) should return the associated value (null)", getMap().put(getKeyForNullValue(), null)); expectContents(createArrayWithNullValue()); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testPut_replaceNullValueWithNonNullSupported() { Entry<K, V> newEntry = entry(getKeyForNullValue(), samples.e3.getValue()); initMapWithNullValue(); assertNull("put(present, value) should return the associated value (null)", put(newEntry)); Entry<K, V>[] expected = createArrayWithNullValue(); expected[getNullLocation()] = newEntry; expectContents(expected); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES}) public void testPut_nullKeyAndValueSupported() { assertNull("put(null, null) should return null", put(nullKeyValueEntry)); expectAdded(nullKeyValueEntry); } private V put(Map.Entry<K, V> entry) { return getMap().put(entry.getKey(), entry.getValue()); } }
Java
/* * Copyright (C) 2008 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.ListFeature; import java.util.ConcurrentModificationException; import java.util.Iterator; /** * A generic JUnit test which tests {@code add(int, Object)} operations on a * list. Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * @author Chris Povirk */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class ListAddAtIndexTester<E> extends AbstractListTester<E> { @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testAddAtIndex_supportedPresent() { getList().add(0, samples.e0); expectAdded(0, samples.e0); } @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) /* * absent = ZERO isn't required, since unmodList.add() must * throw regardless, but it keeps the method name accurate. */ public void testAddAtIndex_unsupportedPresent() { try { getList().add(0, samples.e0); fail("add(n, present) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndex_supportedNotPresent() { getList().add(0, samples.e3); expectAdded(0, samples.e3); } @CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION) @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndexConcurrentWithIteration() { try { Iterator<E> iterator = collection.iterator(); getList().add(0, samples.e3); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndex_unsupportedNotPresent() { try { getList().add(0, samples.e3); fail("add(n, notPresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); expectMissing(samples.e3); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = {ZERO, ONE}) public void testAddAtIndex_middle() { getList().add(getNumElements() / 2, samples.e3); expectAdded(getNumElements() / 2, samples.e3); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testAddAtIndex_end() { getList().add(getNumElements(), samples.e3); expectAdded(getNumElements(), samples.e3); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionFeature.Require(ALLOWS_NULL_VALUES) public void testAddAtIndex_nullSupported() { getList().add(0, null); expectAdded(0, (E) null); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionFeature.Require(absent = ALLOWS_NULL_VALUES) public void testAddAtIndex_nullUnsupported() { try { getList().add(0, null); fail("add(n, null) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullMissingWhenNullUnsupported( "Should not contain null after unsupported add(n, null)"); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndex_negative() { try { getList().add(-1, samples.e3); fail("add(-1, e) should throw"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); expectMissing(samples.e3); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndex_tooLarge() { try { getList().add(getNumElements() + 1, samples.e3); fail("add(size + 1, e) should throw"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); expectMissing(samples.e3); } }
Java
/* * Copyright (C) 2007 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.List; /** * A generic JUnit test which tests {@code add(Object)} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * @author Chris Povirk */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class ListAddTester<E> extends AbstractListTester<E> { @CollectionFeature.Require(SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAdd_supportedPresent() { assertTrue("add(present) should return true", getList().add(samples.e0)); expectAdded(samples.e0); } @CollectionFeature.Require(absent = SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) /* * absent = ZERO isn't required, since unmodList.add() must * throw regardless, but it keeps the method name accurate. */ public void testAdd_unsupportedPresent() { try { getList().add(samples.e0); fail("add(present) should throw"); } catch (UnsupportedOperationException expected) { } } @CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testAdd_supportedNullPresent() { E[] array = createArrayWithNullElement(); collection = getSubjectGenerator().create(array); assertTrue("add(nullPresent) should return true", getList().add(null)); List<E> expected = Helpers.copyToList(array); expected.add(null); expectContents(expected); } }
Java
/* * Copyright (C) 2007 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static java.util.Collections.singletonList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; /** * A generic JUnit test which tests addAll operations on a collection. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * @author Chris Povirk * @author Kevin Bourrillion */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class CollectionAddAllTester<E> extends AbstractCollectionTester<E> { @CollectionFeature.Require(SUPPORTS_ADD) public void testAddAll_supportedNothing() { assertFalse("addAll(nothing) should return false", collection.addAll(emptyCollection())); expectUnchanged(); } @CollectionFeature.Require(absent = SUPPORTS_ADD) public void testAddAll_unsupportedNothing() { try { assertFalse("addAll(nothing) should return false or throw", collection.addAll(emptyCollection())); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @CollectionFeature.Require(SUPPORTS_ADD) public void testAddAll_supportedNonePresent() { assertTrue("addAll(nonePresent) should return true", collection.addAll(createDisjointCollection())); expectAdded(samples.e3, samples.e4); } @CollectionFeature.Require(absent = SUPPORTS_ADD) public void testAddAll_unsupportedNonePresent() { try { collection.addAll(createDisjointCollection()); fail("addAll(nonePresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); expectMissing(samples.e3, samples.e4); } @CollectionFeature.Require(SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAddAll_supportedSomePresent() { assertTrue("addAll(somePresent) should return true", collection.addAll(MinimalCollection.of(samples.e3, samples.e0))); assertTrue("should contain " + samples.e3, collection.contains(samples.e3)); assertTrue("should contain " + samples.e0, collection.contains(samples.e0)); } @CollectionFeature.Require(absent = SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAddAll_unsupportedSomePresent() { try { collection.addAll(MinimalCollection.of(samples.e3, samples.e0)); fail("addAll(somePresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @CollectionFeature.Require({SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) @CollectionSize.Require(absent = ZERO) public void testAddAllConcurrentWithIteration() { try { Iterator<E> iterator = collection.iterator(); assertTrue(collection.addAll(MinimalCollection.of(samples.e3, samples.e0))); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @CollectionFeature.Require(absent = SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAddAll_unsupportedAllPresent() { try { assertFalse("addAll(allPresent) should return false or throw", collection.addAll(MinimalCollection.of(samples.e0))); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES}, absent = RESTRICTS_ELEMENTS) public void testAddAll_nullSupported() { List<E> containsNull = singletonList(null); assertTrue("addAll(containsNull) should return true", collection .addAll(containsNull)); /* * We need (E) to force interpretation of null as the single element of a * varargs array, not the array itself */ expectAdded((E) null); } @CollectionFeature.Require(value = SUPPORTS_ADD, absent = ALLOWS_NULL_VALUES) public void testAddAll_nullUnsupported() { List<E> containsNull = singletonList(null); try { collection.addAll(containsNull); fail("addAll(containsNull) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullMissingWhenNullUnsupported( "Should not contain null after unsupported addAll(containsNull)"); } @CollectionFeature.Require(SUPPORTS_ADD) public void testAddAll_nullCollectionReference() { try { collection.addAll(null); fail("addAll(null) should throw NullPointerException"); } catch (NullPointerException expected) { } } }
Java
/* * Copyright (C) 2008 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.Collection; /** * Tests {@link java.util.Set#hashCode}. * * @author George van den Driessche */ @GwtCompatible(emulated = true) public class SetHashCodeTester<E> extends AbstractSetTester<E> { public void testHashCode() { int expectedHashCode = 0; for (E element : getSampleElements()) { expectedHashCode += ((element == null) ? 0 : element.hashCode()); } assertEquals( "A Set's hashCode() should be the sum of those of its elements.", expectedHashCode, getSet().hashCode()); } @CollectionSize.Require(absent = CollectionSize.ZERO) @CollectionFeature.Require(ALLOWS_NULL_VALUES) public void testHashCode_containingNull() { Collection<E> elements = getSampleElements(getNumElements() - 1); int expectedHashCode = 0; for (E element : elements) { expectedHashCode += ((element == null) ? 0 : element.hashCode()); } elements.add(null); collection = getSubjectGenerator().create(elements.toArray()); assertEquals( "A Set's hashCode() should be the sum of those of its elements (with " + "a null element counting as having a hash of zero).", expectedHashCode, getSet().hashCode()); } }
Java
/* * Copyright (C) 2007 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.MapFeature.REJECTS_DUPLICATES_AT_CREATION; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import java.util.Arrays; import java.util.List; import java.util.Map.Entry; /** * A generic JUnit test which tests creation (typically through a constructor or * static factory method) of a map. Can't be invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * @author Chris Povirk * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class MapCreationTester<K, V> extends AbstractMapTester<K, V> { @MapFeature.Require(ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullKeySupported() { initMapWithNullKey(); expectContents(createArrayWithNullKey()); } @MapFeature.Require(absent = ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullKeyUnsupported() { try { initMapWithNullKey(); fail("Creating a map containing a null key should fail"); } catch (NullPointerException expected) { } } @MapFeature.Require(ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullValueSupported() { initMapWithNullValue(); expectContents(createArrayWithNullValue()); } @MapFeature.Require(absent = ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullValueUnsupported() { try { initMapWithNullValue(); fail("Creating a map containing a null value should fail"); } catch (NullPointerException expected) { } } @MapFeature.Require({ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullKeyAndValueSupported() { Entry<K, V>[] entries = createSamplesArray(); entries[getNullLocation()] = entry(null, null); resetMap(entries); expectContents(entries); } @MapFeature.Require(value = ALLOWS_NULL_KEYS, absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nullDuplicatesNotRejected() { expectFirstRemoved(getEntriesMultipleNullKeys()); } @MapFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() { expectFirstRemoved(getEntriesMultipleNonNullKeys()); } @MapFeature.Require({ALLOWS_NULL_KEYS, REJECTS_DUPLICATES_AT_CREATION}) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nullDuplicatesRejected() { Entry<K, V>[] entries = getEntriesMultipleNullKeys(); try { resetMap(entries); fail("Should reject duplicate null elements at creation"); } catch (IllegalArgumentException expected) { } } @MapFeature.Require(REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nonNullDuplicatesRejected() { Entry<K, V>[] entries = getEntriesMultipleNonNullKeys(); try { resetMap(entries); fail("Should reject duplicate non-null elements at creation"); } catch (IllegalArgumentException expected) { } } private Entry<K, V>[] getEntriesMultipleNullKeys() { Entry<K, V>[] entries = createArrayWithNullKey(); entries[0] = entry(null, entries[0].getValue()); return entries; } private Entry<K, V>[] getEntriesMultipleNonNullKeys() { Entry<K, V>[] entries = createSamplesArray(); entries[0] = entry(samples.e1.getKey(), samples.e0.getValue()); return entries; } private void expectFirstRemoved(Entry<K, V>[] entries) { resetMap(entries); List<Entry<K, V>> expectedWithDuplicateRemoved = Arrays.asList(entries).subList(1, getNumElements()); expectContents(expectedWithDuplicateRemoved); } }
Java
/* * Copyright (C) 2008 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests creation (typically through a constructor or * static factory method) of a collection. Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * @author Chris Povirk */ @GwtCompatible(emulated = true) public class CollectionCreationTester<E> extends AbstractCollectionTester<E> { @CollectionFeature.Require(ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testCreateWithNull_supported() { E[] array = createArrayWithNullElement(); collection = getSubjectGenerator().create(array); expectContents(array); } @CollectionFeature.Require(absent = ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testCreateWithNull_unsupported() { E[] array = createArrayWithNullElement(); try { getSubjectGenerator().create(array); fail("Creating a collection containing null should fail"); } catch (NullPointerException expected) { } } }
Java
/* * Copyright (C) 2008 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.ListFeature; /** * A generic JUnit test which tests {@code set()} operations on a list. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * @author George van den Driessche */ @GwtCompatible(emulated = true) public class ListSetTester<E> extends AbstractListTester<E> { @ListFeature.Require(SUPPORTS_SET) @CollectionSize.Require(absent = ZERO) public void testSet() { doTestSet(samples.e3); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(ALLOWS_NULL_VALUES) @ListFeature.Require(SUPPORTS_SET) public void testSet_null() { doTestSet(null); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(ALLOWS_NULL_VALUES) @ListFeature.Require(SUPPORTS_SET) public void testSet_replacingNull() { E[] elements = createSamplesArray(); int i = aValidIndex(); elements[i] = null; collection = getSubjectGenerator().create(elements); doTestSet(samples.e3); } private void doTestSet(E newValue) { int index = aValidIndex(); E initialValue = getList().get(index); assertEquals("set(i, x) should return the old element at position i.", initialValue, getList().set(index, newValue)); assertEquals("After set(i, x), get(i) should return x", newValue, getList().get(index)); assertEquals("set() should not change the size of a list.", getNumElements(), getList().size()); } @ListFeature.Require(SUPPORTS_SET) public void testSet_indexTooLow() { try { getList().set(-1, samples.e3); fail("set(-1) should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); } @ListFeature.Require(SUPPORTS_SET) public void testSet_indexTooHigh() { int index = getNumElements(); try { getList().set(index, samples.e3); fail("set(size) should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); } @CollectionSize.Require(absent = ZERO) @ListFeature.Require(absent = SUPPORTS_SET) public void testSet_unsupported() { try { getList().set(aValidIndex(), samples.e3); fail("set() should throw UnsupportedOperationException"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @CollectionSize.Require(ZERO) @ListFeature.Require(absent = SUPPORTS_SET) public void testSet_unsupportedByEmptyList() { try { getList().set(0, samples.e3); fail("set() should throw UnsupportedOperationException " + "or IndexOutOfBoundsException"); } catch (UnsupportedOperationException tolerated) { } catch (IndexOutOfBoundsException tolerated) { } expectUnchanged(); } @CollectionSize.Require(absent = ZERO) @ListFeature.Require(SUPPORTS_SET) @CollectionFeature.Require(absent = ALLOWS_NULL_VALUES) public void testSet_nullUnsupported() { try { getList().set(aValidIndex(), null); fail("set(null) should throw NullPointerException"); } catch (NullPointerException expected) { } expectUnchanged(); } private int aValidIndex() { return getList().size() / 2; } }
Java
/* * Copyright (C) 2008 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.collect.testing.testers; import com.google.common.annotations.GwtCompatible; /** * Tests {@link java.util.List#hashCode}. * * @author George van den Driessche */ @GwtCompatible(emulated = true) public class ListHashCodeTester<E> extends AbstractListTester<E> { public void testHashCode() { int expectedHashCode = 1; for (E element : getOrderedElements()) { expectedHashCode = 31 * expectedHashCode + ((element == null) ? 0 : element.hashCode()); } assertEquals( "A List's hashCode() should be computed from those of its elements.", expectedHashCode, getList().hashCode()); } }
Java
/* * Copyright (C) 2008 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SortedMapInterfaceTest; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.SortedMap; /** * Test cases for {@link TreeBasedTable}. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class TreeBasedTableTest extends AbstractTableTest { public static class TreeRowTest extends SortedMapInterfaceTest<String, String> { public TreeRowTest() { super(false, false, true, true, true); } @Override protected SortedMap<String, String> makeEmptyMap() { TreeBasedTable<String, String, String> table = TreeBasedTable.create(); table.put("a", "b", "c"); table.put("c", "b", "a"); table.put("a", "a", "d"); return table.row("b"); } @Override protected SortedMap<String, String> makePopulatedMap() { TreeBasedTable<String, String, String> table = TreeBasedTable.create(); table.put("a", "b", "c"); table.put("c", "b", "a"); table.put("b", "b", "x"); table.put("b", "c", "y"); table.put("b", "x", "n"); table.put("a", "a", "d"); return table.row("b"); } @Override protected String getKeyNotInPopulatedMap() { return "q"; } @Override protected String getValueNotInPopulatedMap() { return "p"; } public void testClearSubMapOfRowMap() { TreeBasedTable<String, String, String> table = TreeBasedTable.create(); table.put("a", "b", "c"); table.put("c", "b", "a"); table.put("b", "b", "x"); table.put("b", "c", "y"); table.put("b", "x", "n"); table.put("a", "a", "d"); table.row("b").subMap("c", "x").clear(); assertEquals(table.row("b"), ImmutableMap.of("b", "x", "x", "n")); table.row("b").subMap("b", "y").clear(); assertEquals(table.row("b"), ImmutableMap.of()); assertFalse(table.backingMap.containsKey("b")); } } private TreeBasedTable<String, Integer, Character> sortedTable; protected TreeBasedTable<String, Integer, Character> create( Comparator<? super String> rowComparator, Comparator<? super Integer> columnComparator, Object... data) { TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create(rowComparator, columnComparator); table.put("foo", 4, 'a'); table.put("cat", 1, 'b'); table.clear(); populate(table, data); return table; } @Override protected TreeBasedTable<String, Integer, Character> create( Object... data) { TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create(); table.put("foo", 4, 'a'); table.put("cat", 1, 'b'); table.clear(); populate(table, data); return table; } public void testCreateExplicitComparators() { table = TreeBasedTable.create( Collections.reverseOrder(), Ordering.usingToString()); table.put("foo", 3, 'a'); table.put("foo", 12, 'b'); table.put("bar", 5, 'c'); table.put("cat", 8, 'd'); ASSERT.that(table.rowKeySet()).has().exactly("foo", "cat", "bar").inOrder(); ASSERT.that(table.row("foo").keySet()).has().exactly(12, 3).inOrder(); } public void testCreateCopy() { TreeBasedTable<String, Integer, Character> original = TreeBasedTable.create( Collections.reverseOrder(), Ordering.usingToString()); original.put("foo", 3, 'a'); original.put("foo", 12, 'b'); original.put("bar", 5, 'c'); original.put("cat", 8, 'd'); table = TreeBasedTable.create(original); ASSERT.that(table.rowKeySet()).has().exactly("foo", "cat", "bar").inOrder(); ASSERT.that(table.row("foo").keySet()).has().exactly(12, 3).inOrder(); assertEquals(original, table); } public void testToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("{bar={1=b}, foo={1=a, 3=c}}", table.toString()); assertEquals("{bar={1=b}, foo={1=a, 3=c}}", table.rowMap().toString()); } public void testCellSetToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[(bar,1)=b, (foo,1)=a, (foo,3)=c]", table.cellSet().toString()); } public void testRowKeySetToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[bar, foo]", table.rowKeySet().toString()); } public void testValuesToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[b, a, c]", table.values().toString()); } public void testRowComparator() { sortedTable = TreeBasedTable.create(); assertSame(Ordering.natural(), sortedTable.rowComparator()); sortedTable = TreeBasedTable.create( Collections.reverseOrder(), Ordering.usingToString()); assertSame(Collections.reverseOrder(), sortedTable.rowComparator()); } public void testColumnComparator() { sortedTable = TreeBasedTable.create(); assertSame(Ordering.natural(), sortedTable.columnComparator()); sortedTable = TreeBasedTable.create( Collections.reverseOrder(), Ordering.usingToString()); assertSame(Ordering.usingToString(), sortedTable.columnComparator()); } public void testRowKeySetComparator() { sortedTable = TreeBasedTable.create(); assertSame(Ordering.natural(), sortedTable.rowKeySet().comparator()); sortedTable = TreeBasedTable.create( Collections.reverseOrder(), Ordering.usingToString()); assertSame(Collections.reverseOrder(), sortedTable.rowKeySet().comparator()); } public void testRowKeySetFirst() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertSame("bar", sortedTable.rowKeySet().first()); } public void testRowKeySetLast() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertSame("foo", sortedTable.rowKeySet().last()); } public void testRowKeySetHeadSet() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Set<String> set = sortedTable.rowKeySet().headSet("cat"); assertEquals(Collections.singleton("bar"), set); set.clear(); assertTrue(set.isEmpty()); assertEquals(Collections.singleton("foo"), sortedTable.rowKeySet()); } public void testRowKeySetTailSet() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Set<String> set = sortedTable.rowKeySet().tailSet("cat"); assertEquals(Collections.singleton("foo"), set); set.clear(); assertTrue(set.isEmpty()); assertEquals(Collections.singleton("bar"), sortedTable.rowKeySet()); } public void testRowKeySetSubSet() { sortedTable = create( "foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c', "dog", 2, 'd'); Set<String> set = sortedTable.rowKeySet().subSet("cat", "egg"); assertEquals(Collections.singleton("dog"), set); set.clear(); assertTrue(set.isEmpty()); assertEquals(ImmutableSet.of("bar", "foo"), sortedTable.rowKeySet()); } public void testRowMapComparator() { sortedTable = TreeBasedTable.create(); assertSame(Ordering.natural(), sortedTable.rowMap().comparator()); sortedTable = TreeBasedTable.create( Collections.reverseOrder(), Ordering.usingToString()); assertSame(Collections.reverseOrder(), sortedTable.rowMap().comparator()); } public void testRowMapFirstKey() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertSame("bar", sortedTable.rowMap().firstKey()); } public void testRowMapLastKey() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertSame("foo", sortedTable.rowMap().lastKey()); } public void testRowKeyMapHeadMap() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<String, Map<Integer, Character>> map = sortedTable.rowMap().headMap("cat"); assertEquals(1, map.size()); assertEquals(ImmutableMap.of(1, 'b'), map.get("bar")); map.clear(); assertTrue(map.isEmpty()); assertEquals(Collections.singleton("foo"), sortedTable.rowKeySet()); } public void testRowKeyMapTailMap() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<String, Map<Integer, Character>> map = sortedTable.rowMap().tailMap("cat"); assertEquals(1, map.size()); assertEquals(ImmutableMap.of(1, 'a', 3, 'c'), map.get("foo")); map.clear(); assertTrue(map.isEmpty()); assertEquals(Collections.singleton("bar"), sortedTable.rowKeySet()); } public void testRowKeyMapSubMap() { sortedTable = create( "foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c', "dog", 2, 'd'); Map<String, Map<Integer, Character>> map = sortedTable.rowMap().subMap("cat", "egg"); assertEquals(ImmutableMap.of(2, 'd'), map.get("dog")); map.clear(); assertTrue(map.isEmpty()); assertEquals(ImmutableSet.of("bar", "foo"), sortedTable.rowKeySet()); } public void testRowMapValuesAreSorted() { sortedTable = create( "foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c', "dog", 2, 'd'); assertTrue(sortedTable.rowMap().get("foo") instanceof SortedMap); } public void testColumnKeySet_isSorted() { table = create("a", 2, 'X', "a", 2, 'X', "b", 3, 'X', "b", 2, 'X', "c", 10, 'X', "c", 10, 'X', "c", 20, 'X', "d", 15, 'X', "d", 20, 'X', "d", 1, 'X', "e", 5, 'X' ); assertEquals("[1, 2, 3, 5, 10, 15, 20]", table.columnKeySet().toString()); } public void testColumnKeySet_isSortedWithRealComparator() { table = create(String.CASE_INSENSITIVE_ORDER, Ordering.natural().reverse(), "a", 2, 'X', "a", 2, 'X', "b", 3, 'X', "b", 2, 'X', "c", 10, 'X', "c", 10, 'X', "c", 20, 'X', "d", 15, 'X', "d", 20, 'X', "d", 1, 'X', "e", 5, 'X' ); assertEquals("[20, 15, 10, 5, 3, 2, 1]", table.columnKeySet().toString()); } public void testColumnKeySet_empty() { table = create(); assertEquals("[]", table.columnKeySet().toString()); } public void testColumnKeySet_oneRow() { table = create("a", 2, 'X', "a", 1, 'X' ); assertEquals("[1, 2]", table.columnKeySet().toString()); } public void testColumnKeySet_oneColumn() { table = create("a", 1, 'X', "b", 1, 'X' ); assertEquals("[1]", table.columnKeySet().toString()); } public void testColumnKeySet_oneEntry() { table = create("a", 1, 'X'); assertEquals("[1]", table.columnKeySet().toString()); } public void testRowEntrySetContains() { table = sortedTable = create("a", 2, 'X', "a", 2, 'X', "b", 3, 'X', "b", 2, 'X', "c", 10, 'X', "c", 10, 'X', "c", 20, 'X', "d", 15, 'X', "d", 20, 'X', "d", 1, 'X', "e", 5, 'X'); SortedMap<Integer, Character> row = sortedTable.row("c"); Set<Map.Entry<Integer, Character>> entrySet = row.entrySet(); assertTrue(entrySet.contains(Maps.immutableEntry(10, 'X'))); assertTrue(entrySet.contains(Maps.immutableEntry(20, 'X'))); assertFalse(entrySet.contains(Maps.immutableEntry(15, 'X'))); entrySet = row.tailMap(15).entrySet(); assertFalse(entrySet.contains(Maps.immutableEntry(10, 'X'))); assertTrue(entrySet.contains(Maps.immutableEntry(20, 'X'))); assertFalse(entrySet.contains(Maps.immutableEntry(15, 'X'))); } public void testRowEntrySetRemove() { table = sortedTable = create("a", 2, 'X', "a", 2, 'X', "b", 3, 'X', "b", 2, 'X', "c", 10, 'X', "c", 10, 'X', "c", 20, 'X', "d", 15, 'X', "d", 20, 'X', "d", 1, 'X', "e", 5, 'X'); SortedMap<Integer, Character> row = sortedTable.row("c"); Set<Map.Entry<Integer, Character>> entrySet = row.tailMap(15).entrySet(); assertFalse(entrySet.remove(Maps.immutableEntry(10, 'X'))); assertTrue(entrySet.remove(Maps.immutableEntry(20, 'X'))); assertFalse(entrySet.remove(Maps.immutableEntry(15, 'X'))); entrySet = row.entrySet(); assertTrue(entrySet.remove(Maps.immutableEntry(10, 'X'))); assertFalse(entrySet.remove(Maps.immutableEntry(20, 'X'))); assertFalse(entrySet.remove(Maps.immutableEntry(15, 'X'))); } public void testRowSize() { table = sortedTable = create("a", 2, 'X', "a", 2, 'X', "b", 3, 'X', "b", 2, 'X', "c", 10, 'X', "c", 10, 'X', "c", 20, 'X', "d", 15, 'X', "d", 20, 'X', "d", 1, 'X', "e", 5, 'X'); SortedMap<Integer, Character> row = sortedTable.row("c"); assertEquals(row.size(), 2); assertEquals(row.tailMap(15).size(), 1); } public void testSubRowClearAndPut() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); SortedMap<Integer, Character> row = (SortedMap<Integer, Character>) table.row("foo"); SortedMap<Integer, Character> subRow = row.tailMap(2); assertEquals(ImmutableMap.of(1, 'a', 3, 'c'), row); assertEquals(ImmutableMap.of(3, 'c'), subRow); table.remove("foo", 3); assertEquals(ImmutableMap.of(1, 'a'), row); assertEquals(ImmutableMap.of(), subRow); table.remove("foo", 1); assertEquals(ImmutableMap.of(), row); assertEquals(ImmutableMap.of(), subRow); table.put("foo", 2, 'b'); assertEquals(ImmutableMap.of(2, 'b'), row); assertEquals(ImmutableMap.of(2, 'b'), subRow); row.clear(); assertEquals(ImmutableMap.of(), row); assertEquals(ImmutableMap.of(), subRow); table.put("foo", 5, 'x'); assertEquals(ImmutableMap.of(5, 'x'), row); assertEquals(ImmutableMap.of(5, 'x'), subRow); } }
Java
/* * Copyright (C) 2013 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.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.MapConstraintsTest.TestKeyException; import com.google.common.collect.MapConstraintsTest.TestValueException; import com.google.common.collect.testing.TestStringMapGenerator; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Tests for {@link MapConstraints#constrainedMap}. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class ConstrainedMapTest extends TestCase { private static final String TEST_KEY = "42"; private static final String TEST_VALUE = "test"; private static final MapConstraint<String, String> TEST_CONSTRAINT = new TestConstraint(); public void testPutWithForbiddenKeyForbiddenValue() { Map<String, String> map = MapConstraints.constrainedMap( new HashMap<String, String>(), TEST_CONSTRAINT); try { map.put(TEST_KEY, TEST_VALUE); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // success } } public void testPutWithForbiddenKeyAllowedValue() { Map<String, String> map = MapConstraints.constrainedMap( new HashMap<String, String>(), TEST_CONSTRAINT); try { map.put(TEST_KEY, "allowed"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // success } } public void testPutWithAllowedKeyForbiddenValue() { Map<String, String> map = MapConstraints.constrainedMap( new HashMap<String, String>(), TEST_CONSTRAINT); try { map.put("allowed", TEST_VALUE); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // success } } public static final class ConstrainedMapGenerator extends TestStringMapGenerator { @Override protected Map<String, String> create(Entry<String, String>[] entries) { Map<String, String> map = MapConstraints.constrainedMap( new HashMap<String, String>(), TEST_CONSTRAINT); for (Entry<String, String> entry : entries) { map.put(entry.getKey(), entry.getValue()); } return map; } } private static final class TestConstraint implements MapConstraint<String, String> { @Override public void checkKeyValue(String key, String value) { if (TEST_KEY.equals(key)) { throw new TestKeyException(); } if (TEST_VALUE.equals(value)) { throw new TestValueException(); } } private static final long serialVersionUID = 0; } }
Java
/* * Copyright (C) 2007 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.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * Unit tests for {@code LinkedHashMultimap}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class LinkedHashMultimapTest extends TestCase { public void testValueSetHashTableExpansion() { LinkedHashMultimap<String, Integer> multimap = LinkedHashMultimap.create(); for (int z = 1; z <= 100; z++) { multimap.put("a", z); // The Eclipse compiler (and hence GWT) rejects a parameterized cast. @SuppressWarnings("unchecked") LinkedHashMultimap<String, Integer>.ValueSet valueSet = (LinkedHashMultimap.ValueSet) multimap.backingMap().get("a"); assertEquals(z, valueSet.size()); assertFalse(Hashing.needsResizing(valueSet.size(), valueSet.hashTable.length, LinkedHashMultimap.VALUE_SET_LOAD_FACTOR)); } } private Multimap<String, Integer> initializeMultimap5() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 5); multimap.put("bar", 4); multimap.put("foo", 3); multimap.put("cow", 2); multimap.put("bar", 1); return multimap; } public void testToString() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 3); multimap.put("bar", 1); multimap.putAll("foo", Arrays.asList(-1, 2, 4)); multimap.putAll("bar", Arrays.asList(2, 3)); multimap.put("foo", 1); assertEquals("{foo=[3, -1, 2, 4, 1], bar=[1, 2, 3]}", multimap.toString()); } public void testOrderingReadOnly() { Multimap<String, Integer> multimap = initializeMultimap5(); assertOrderingReadOnly(multimap); } public void testOrderingUnmodifiable() { Multimap<String, Integer> multimap = initializeMultimap5(); assertOrderingReadOnly(Multimaps.unmodifiableMultimap(multimap)); } public void testOrderingSynchronized() { Multimap<String, Integer> multimap = initializeMultimap5(); assertOrderingReadOnly(Multimaps.synchronizedMultimap(multimap)); } private void assertOrderingReadOnly(Multimap<String, Integer> multimap) { ASSERT.that(multimap.get("foo")).has().exactly(5, 3).inOrder(); ASSERT.that(multimap.get("bar")).has().exactly(4, 1).inOrder(); ASSERT.that(multimap.get("cow")).has().item(2); ASSERT.that(multimap.keySet()).has().exactly("foo", "bar", "cow").inOrder(); ASSERT.that(multimap.values()).has().exactly(5, 4, 3, 2, 1).inOrder(); Iterator<Map.Entry<String, Integer>> entryIterator = multimap.entries().iterator(); assertEquals(Maps.immutableEntry("foo", 5), entryIterator.next()); assertEquals(Maps.immutableEntry("bar", 4), entryIterator.next()); assertEquals(Maps.immutableEntry("foo", 3), entryIterator.next()); assertEquals(Maps.immutableEntry("cow", 2), entryIterator.next()); assertEquals(Maps.immutableEntry("bar", 1), entryIterator.next()); Iterator<Map.Entry<String, Collection<Integer>>> collectionIterator = multimap.asMap().entrySet().iterator(); Map.Entry<String, Collection<Integer>> entry = collectionIterator.next(); assertEquals("foo", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(5, 3).inOrder(); entry = collectionIterator.next(); assertEquals("bar", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(4, 1).inOrder(); entry = collectionIterator.next(); assertEquals("cow", entry.getKey()); ASSERT.that(entry.getValue()).has().item(2); } public void testOrderingUpdates() { Multimap<String, Integer> multimap = initializeMultimap5(); ASSERT.that(multimap.replaceValues("foo", asList(6, 7))).has().exactly(5, 3).inOrder(); ASSERT.that(multimap.keySet()).has().exactly("foo", "bar", "cow").inOrder(); ASSERT.that(multimap.removeAll("foo")).has().exactly(6, 7).inOrder(); ASSERT.that(multimap.keySet()).has().exactly("bar", "cow").inOrder(); assertTrue(multimap.remove("bar", 4)); ASSERT.that(multimap.keySet()).has().exactly("bar", "cow").inOrder(); assertTrue(multimap.remove("bar", 1)); ASSERT.that(multimap.keySet()).has().item("cow"); multimap.put("bar", 9); ASSERT.that(multimap.keySet()).has().exactly("cow", "bar").inOrder(); } public void testToStringNullExact() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 3); multimap.put("foo", -1); multimap.put(null, null); multimap.put("bar", 1); multimap.put("foo", 2); multimap.put(null, 0); multimap.put("bar", 2); multimap.put("bar", null); multimap.put("foo", null); multimap.put("foo", 4); multimap.put(null, -1); multimap.put("bar", 3); multimap.put("bar", 1); multimap.put("foo", 1); assertEquals( "{foo=[3, -1, 2, null, 4, 1], null=[null, 0, -1], bar=[1, 2, null, 3]}", multimap.toString()); } public void testPutMultimapOrdered() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.putAll(initializeMultimap5()); assertOrderingReadOnly(multimap); } public void testKeysToString_ordering() { Multimap<String, Integer> multimap = initializeMultimap5(); assertEquals("[foo x 2, bar x 2, cow]", multimap.keys().toString()); } public void testCreate() { LinkedHashMultimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("foo", 3); assertEquals(ImmutableSet.of(1, 3), multimap.get("foo")); } public void testCreateFromMultimap() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("a", 1); multimap.put("b", 2); multimap.put("a", 3); multimap.put("c", 4); LinkedHashMultimap<String, Integer> copy = LinkedHashMultimap.create(multimap); new EqualsTester() .addEqualityGroup(multimap, copy) .testEquals(); } public void testCreateFromSizes() { LinkedHashMultimap<String, Integer> multimap = LinkedHashMultimap.create(20, 15); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("foo", 3); assertEquals(ImmutableSet.of(1, 3), multimap.get("foo")); } public void testCreateFromIllegalSizes() { try { LinkedHashMultimap.create(-20, 15); fail(); } catch (IllegalArgumentException expected) {} try { LinkedHashMultimap.create(20, -15); fail(); } catch (IllegalArgumentException expected) {} } }
Java
/* * Copyright (C) 2007 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.collect; import static com.google.common.collect.Iterators.advance; import static com.google.common.collect.Iterators.get; import static com.google.common.collect.Iterators.getLast; import static com.google.common.collect.Lists.newArrayList; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import junit.framework.TestCase; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.RandomAccess; import java.util.Set; import java.util.Vector; /** * Unit test for {@code Iterators}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class IteratorsTest extends TestCase { public void testEmptyIterator() { Iterator<String> iterator = Iterators.emptyIterator(); assertFalse(iterator.hasNext()); try { iterator.next(); fail("no exception thrown"); } catch (NoSuchElementException expected) { } try { iterator.remove(); fail("no exception thrown"); } catch (UnsupportedOperationException expected) { } } public void testEmptyListIterator() { ListIterator<String> iterator = Iterators.emptyListIterator(); assertFalse(iterator.hasNext()); assertFalse(iterator.hasPrevious()); assertEquals(0, iterator.nextIndex()); assertEquals(-1, iterator.previousIndex()); try { iterator.next(); fail("no exception thrown"); } catch (NoSuchElementException expected) { } try { iterator.previous(); fail("no exception thrown"); } catch (NoSuchElementException expected) { } try { iterator.remove(); fail("no exception thrown"); } catch (UnsupportedOperationException expected) { } try { iterator.set("a"); fail("no exception thrown"); } catch (UnsupportedOperationException expected) { } try { iterator.add("a"); fail("no exception thrown"); } catch (UnsupportedOperationException expected) { } } public void testEmptyModifiableIterator() { Iterator<String> iterator = Iterators.emptyModifiableIterator(); assertFalse(iterator.hasNext()); try { iterator.next(); fail("Expected NoSuchElementException"); } catch (NoSuchElementException expected) { } try { iterator.remove(); fail("Expected IllegalStateException"); } catch (IllegalStateException expected) { } } public void testSize0() { Iterator<String> iterator = Iterators.emptyIterator(); assertEquals(0, Iterators.size(iterator)); } public void testSize1() { Iterator<Integer> iterator = Collections.singleton(0).iterator(); assertEquals(1, Iterators.size(iterator)); } public void testSize_partiallyConsumed() { Iterator<Integer> iterator = asList(1, 2, 3, 4, 5).iterator(); iterator.next(); iterator.next(); assertEquals(3, Iterators.size(iterator)); } public void test_contains_nonnull_yes() { Iterator<String> set = asList("a", null, "b").iterator(); assertTrue(Iterators.contains(set, "b")); } public void test_contains_nonnull_no() { Iterator<String> set = asList("a", "b").iterator(); assertFalse(Iterators.contains(set, "c")); } public void test_contains_null_yes() { Iterator<String> set = asList("a", null, "b").iterator(); assertTrue(Iterators.contains(set, null)); } public void test_contains_null_no() { Iterator<String> set = asList("a", "b").iterator(); assertFalse(Iterators.contains(set, null)); } public void testGetOnlyElement_noDefault_valid() { Iterator<String> iterator = Collections.singletonList("foo").iterator(); assertEquals("foo", Iterators.getOnlyElement(iterator)); } public void testGetOnlyElement_noDefault_empty() { Iterator<String> iterator = Iterators.emptyIterator(); try { Iterators.getOnlyElement(iterator); fail(); } catch (NoSuchElementException expected) { } } public void testGetOnlyElement_noDefault_moreThanOneLessThanFiveElements() { Iterator<String> iterator = asList("one", "two").iterator(); try { Iterators.getOnlyElement(iterator); fail(); } catch (IllegalArgumentException expected) { assertEquals("expected one element but was: <one, two>", expected.getMessage()); } } public void testGetOnlyElement_noDefault_fiveElements() { Iterator<String> iterator = asList("one", "two", "three", "four", "five").iterator(); try { Iterators.getOnlyElement(iterator); fail(); } catch (IllegalArgumentException expected) { assertEquals("expected one element but was: " + "<one, two, three, four, five>", expected.getMessage()); } } public void testGetOnlyElement_noDefault_moreThanFiveElements() { Iterator<String> iterator = asList("one", "two", "three", "four", "five", "six").iterator(); try { Iterators.getOnlyElement(iterator); fail(); } catch (IllegalArgumentException expected) { assertEquals("expected one element but was: " + "<one, two, three, four, five, ...>", expected.getMessage()); } } public void testGetOnlyElement_withDefault_singleton() { Iterator<String> iterator = Collections.singletonList("foo").iterator(); assertEquals("foo", Iterators.getOnlyElement(iterator, "bar")); } public void testGetOnlyElement_withDefault_empty() { Iterator<String> iterator = Iterators.emptyIterator(); assertEquals("bar", Iterators.getOnlyElement(iterator, "bar")); } public void testGetOnlyElement_withDefault_empty_null() { Iterator<String> iterator = Iterators.emptyIterator(); assertNull(Iterators.getOnlyElement(iterator, null)); } public void testGetOnlyElement_withDefault_two() { Iterator<String> iterator = asList("foo", "bar").iterator(); try { Iterators.getOnlyElement(iterator, "x"); fail(); } catch (IllegalArgumentException expected) { assertEquals("expected one element but was: <foo, bar>", expected.getMessage()); } } public void testFilterSimple() { Iterator<String> unfiltered = Lists.newArrayList("foo", "bar").iterator(); Iterator<String> filtered = Iterators.filter(unfiltered, Predicates.equalTo("foo")); List<String> expected = Collections.singletonList("foo"); List<String> actual = Lists.newArrayList(filtered); assertEquals(expected, actual); } public void testFilterNoMatch() { Iterator<String> unfiltered = Lists.newArrayList("foo", "bar").iterator(); Iterator<String> filtered = Iterators.filter(unfiltered, Predicates.alwaysFalse()); List<String> expected = Collections.emptyList(); List<String> actual = Lists.newArrayList(filtered); assertEquals(expected, actual); } public void testFilterMatchAll() { Iterator<String> unfiltered = Lists.newArrayList("foo", "bar").iterator(); Iterator<String> filtered = Iterators.filter(unfiltered, Predicates.alwaysTrue()); List<String> expected = Lists.newArrayList("foo", "bar"); List<String> actual = Lists.newArrayList(filtered); assertEquals(expected, actual); } public void testFilterNothing() { Iterator<String> unfiltered = Collections.<String>emptyList().iterator(); Iterator<String> filtered = Iterators.filter(unfiltered, new Predicate<String>() { @Override public boolean apply(String s) { fail("Should never be evaluated"); return false; } }); List<String> expected = Collections.emptyList(); List<String> actual = Lists.newArrayList(filtered); assertEquals(expected, actual); } public void testAny() { List<String> list = Lists.newArrayList(); Predicate<String> predicate = Predicates.equalTo("pants"); assertFalse(Iterators.any(list.iterator(), predicate)); list.add("cool"); assertFalse(Iterators.any(list.iterator(), predicate)); list.add("pants"); assertTrue(Iterators.any(list.iterator(), predicate)); } public void testAll() { List<String> list = Lists.newArrayList(); Predicate<String> predicate = Predicates.equalTo("cool"); assertTrue(Iterators.all(list.iterator(), predicate)); list.add("cool"); assertTrue(Iterators.all(list.iterator(), predicate)); list.add("pants"); assertFalse(Iterators.all(list.iterator(), predicate)); } public void testFind_firstElement() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("cool", Iterators.find(iterator, Predicates.equalTo("cool"))); assertEquals("pants", iterator.next()); } public void testFind_lastElement() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("pants", Iterators.find(iterator, Predicates.equalTo("pants"))); assertFalse(iterator.hasNext()); } public void testFind_notPresent() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); try { Iterators.find(iterator, Predicates.alwaysFalse()); fail(); } catch (NoSuchElementException e) { } assertFalse(iterator.hasNext()); } public void testFind_matchAlways() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("cool", Iterators.find(iterator, Predicates.alwaysTrue())); } public void testFind_withDefault_first() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("cool", Iterators.find(iterator, Predicates.equalTo("cool"), "woot")); assertEquals("pants", iterator.next()); } public void testFind_withDefault_last() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("pants", Iterators.find(iterator, Predicates.equalTo("pants"), "woot")); assertFalse(iterator.hasNext()); } public void testFind_withDefault_notPresent() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("woot", Iterators.find(iterator, Predicates.alwaysFalse(), "woot")); assertFalse(iterator.hasNext()); } public void testFind_withDefault_notPresent_nullReturn() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertNull( Iterators.find(iterator, Predicates.alwaysFalse(), null)); assertFalse(iterator.hasNext()); } public void testFind_withDefault_matchAlways() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("cool", Iterators.find(iterator, Predicates.alwaysTrue(), "woot")); assertEquals("pants", iterator.next()); } public void testTryFind_firstElement() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("cool", Iterators.tryFind(iterator, Predicates.equalTo("cool")).get()); } public void testTryFind_lastElement() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("pants", Iterators.tryFind(iterator, Predicates.equalTo("pants")).get()); } public void testTryFind_alwaysTrue() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("cool", Iterators.tryFind(iterator, Predicates.alwaysTrue()).get()); } public void testTryFind_alwaysFalse_orDefault() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("woot", Iterators.tryFind(iterator, Predicates.alwaysFalse()).or("woot")); assertFalse(iterator.hasNext()); } public void testTryFind_alwaysFalse_isPresent() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertFalse( Iterators.tryFind(iterator, Predicates.alwaysFalse()).isPresent()); assertFalse(iterator.hasNext()); } public void testTransform() { Iterator<String> input = asList("1", "2", "3").iterator(); Iterator<Integer> result = Iterators.transform(input, new Function<String, Integer>() { @Override public Integer apply(String from) { return Integer.valueOf(from); } }); List<Integer> actual = Lists.newArrayList(result); List<Integer> expected = asList(1, 2, 3); assertEquals(expected, actual); } public void testTransformRemove() { List<String> list = Lists.newArrayList("1", "2", "3"); Iterator<String> input = list.iterator(); Iterator<Integer> iterator = Iterators.transform(input, new Function<String, Integer>() { @Override public Integer apply(String from) { return Integer.valueOf(from); } }); assertEquals(Integer.valueOf(1), iterator.next()); assertEquals(Integer.valueOf(2), iterator.next()); iterator.remove(); assertEquals(asList("1", "3"), list); } public void testPoorlyBehavedTransform() { Iterator<String> input = asList("1", null, "3").iterator(); Iterator<Integer> result = Iterators.transform(input, new Function<String, Integer>() { @Override public Integer apply(String from) { return Integer.valueOf(from); } }); result.next(); try { result.next(); fail("Expected NFE"); } catch (NumberFormatException nfe) { // Expected to fail. } } public void testNullFriendlyTransform() { Iterator<Integer> input = asList(1, 2, null, 3).iterator(); Iterator<String> result = Iterators.transform(input, new Function<Integer, String>() { @Override public String apply(Integer from) { return String.valueOf(from); } }); List<String> actual = Lists.newArrayList(result); List<String> expected = asList("1", "2", "null", "3"); assertEquals(expected, actual); } public void testCycleOfEmpty() { // "<String>" for javac 1.5. Iterator<String> cycle = Iterators.<String>cycle(); assertFalse(cycle.hasNext()); } public void testCycleOfOne() { Iterator<String> cycle = Iterators.cycle("a"); for (int i = 0; i < 3; i++) { assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); } } public void testCycleOfOneWithRemove() { Iterable<String> iterable = Lists.newArrayList("a"); Iterator<String> cycle = Iterators.cycle(iterable); assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); cycle.remove(); assertEquals(Collections.emptyList(), iterable); assertFalse(cycle.hasNext()); } public void testCycleOfTwo() { Iterator<String> cycle = Iterators.cycle("a", "b"); for (int i = 0; i < 3; i++) { assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); assertTrue(cycle.hasNext()); assertEquals("b", cycle.next()); } } public void testCycleOfTwoWithRemove() { Iterable<String> iterable = Lists.newArrayList("a", "b"); Iterator<String> cycle = Iterators.cycle(iterable); assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); assertTrue(cycle.hasNext()); assertEquals("b", cycle.next()); assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); cycle.remove(); assertEquals(Collections.singletonList("b"), iterable); assertTrue(cycle.hasNext()); assertEquals("b", cycle.next()); assertTrue(cycle.hasNext()); assertEquals("b", cycle.next()); cycle.remove(); assertEquals(Collections.emptyList(), iterable); assertFalse(cycle.hasNext()); } public void testCycleRemoveWithoutNext() { Iterator<String> cycle = Iterators.cycle("a", "b"); assertTrue(cycle.hasNext()); try { cycle.remove(); fail("no exception thrown"); } catch (IllegalStateException expected) { } } public void testCycleRemoveSameElementTwice() { Iterator<String> cycle = Iterators.cycle("a", "b"); cycle.next(); cycle.remove(); try { cycle.remove(); fail("no exception thrown"); } catch (IllegalStateException expected) { } } public void testCycleWhenRemoveIsNotSupported() { Iterable<String> iterable = asList("a", "b"); Iterator<String> cycle = Iterators.cycle(iterable); cycle.next(); try { cycle.remove(); fail("no exception thrown"); } catch (UnsupportedOperationException expected) { } } public void testCycleRemoveAfterHasNext() { Iterable<String> iterable = Lists.newArrayList("a"); Iterator<String> cycle = Iterators.cycle(iterable); assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); assertTrue(cycle.hasNext()); cycle.remove(); assertEquals(Collections.emptyList(), iterable); assertFalse(cycle.hasNext()); } public void testCycleNoSuchElementException() { Iterable<String> iterable = Lists.newArrayList("a"); Iterator<String> cycle = Iterators.cycle(iterable); assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); cycle.remove(); assertFalse(cycle.hasNext()); try { cycle.next(); fail(); } catch (NoSuchElementException expected) {} } /** * Illustrates the somewhat bizarre behavior when a null is passed in. */ public void testConcatContainingNull() { @SuppressWarnings("unchecked") Iterator<Iterator<Integer>> input = asList(iterateOver(1, 2), null, iterateOver(3)).iterator(); Iterator<Integer> result = Iterators.concat(input); assertEquals(1, (int) result.next()); assertEquals(2, (int) result.next()); try { result.hasNext(); fail("no exception thrown"); } catch (NullPointerException e) { } try { result.next(); fail("no exception thrown"); } catch (NullPointerException e) { } // There is no way to get "through" to the 3. Buh-bye } @SuppressWarnings("unchecked") public void testConcatVarArgsContainingNull() { try { Iterators.concat(iterateOver(1, 2), null, iterateOver(3), iterateOver(4), iterateOver(5)); fail("no exception thrown"); } catch (NullPointerException e) { } } public void testAddAllWithEmptyIterator() { List<String> alreadyThere = Lists.newArrayList("already", "there"); boolean changed = Iterators.addAll(alreadyThere, Iterators.<String>emptyIterator()); ASSERT.that(alreadyThere).has().exactly("already", "there").inOrder(); assertFalse(changed); } public void testAddAllToList() { List<String> alreadyThere = Lists.newArrayList("already", "there"); List<String> freshlyAdded = Lists.newArrayList("freshly", "added"); boolean changed = Iterators.addAll(alreadyThere, freshlyAdded.iterator()); ASSERT.that(alreadyThere).has().exactly("already", "there", "freshly", "added"); assertTrue(changed); } public void testAddAllToSet() { Set<String> alreadyThere = Sets.newLinkedHashSet(asList("already", "there")); List<String> oneMore = Lists.newArrayList("there"); boolean changed = Iterators.addAll(alreadyThere, oneMore.iterator()); ASSERT.that(alreadyThere).has().exactly("already", "there").inOrder(); assertFalse(changed); } private static Iterator<Integer> iterateOver(final Integer... values) { return newArrayList(values).iterator(); } public void testElementsEqual() { Iterable<?> a; Iterable<?> b; // Base case. a = Lists.newArrayList(); b = Collections.emptySet(); assertTrue(Iterators.elementsEqual(a.iterator(), b.iterator())); // A few elements. a = asList(4, 8, 15, 16, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertTrue(Iterators.elementsEqual(a.iterator(), b.iterator())); // The same, but with nulls. a = asList(4, 8, null, 16, 23, 42); b = asList(4, 8, null, 16, 23, 42); assertTrue(Iterators.elementsEqual(a.iterator(), b.iterator())); // Different Iterable types (still equal elements, though). a = ImmutableList.of(4, 8, 15, 16, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertTrue(Iterators.elementsEqual(a.iterator(), b.iterator())); // An element differs. a = asList(4, 8, 15, 12, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterators.elementsEqual(a.iterator(), b.iterator())); // null versus non-null. a = asList(4, 8, 15, null, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterators.elementsEqual(a.iterator(), b.iterator())); assertFalse(Iterators.elementsEqual(b.iterator(), a.iterator())); // Different lengths. a = asList(4, 8, 15, 16, 23); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterators.elementsEqual(a.iterator(), b.iterator())); assertFalse(Iterators.elementsEqual(b.iterator(), a.iterator())); // Different lengths, one is empty. a = Collections.emptySet(); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterators.elementsEqual(a.iterator(), b.iterator())); assertFalse(Iterators.elementsEqual(b.iterator(), a.iterator())); } public void testPartition_badSize() { Iterator<Integer> source = Iterators.singletonIterator(1); try { Iterators.partition(source, 0); fail(); } catch (IllegalArgumentException expected) { } } public void testPartition_empty() { Iterator<Integer> source = Iterators.emptyIterator(); Iterator<List<Integer>> partitions = Iterators.partition(source, 1); assertFalse(partitions.hasNext()); } public void testPartition_singleton1() { Iterator<Integer> source = Iterators.singletonIterator(1); Iterator<List<Integer>> partitions = Iterators.partition(source, 1); assertTrue(partitions.hasNext()); assertTrue(partitions.hasNext()); assertEquals(ImmutableList.of(1), partitions.next()); assertFalse(partitions.hasNext()); } public void testPartition_singleton2() { Iterator<Integer> source = Iterators.singletonIterator(1); Iterator<List<Integer>> partitions = Iterators.partition(source, 2); assertTrue(partitions.hasNext()); assertTrue(partitions.hasNext()); assertEquals(ImmutableList.of(1), partitions.next()); assertFalse(partitions.hasNext()); } public void testPartition_view() { List<Integer> list = asList(1, 2); Iterator<List<Integer>> partitions = Iterators.partition(list.iterator(), 1); // Changes before the partition is retrieved are reflected list.set(0, 3); List<Integer> first = partitions.next(); // Changes after are not list.set(0, 4); assertEquals(ImmutableList.of(3), first); } public void testPaddedPartition_badSize() { Iterator<Integer> source = Iterators.singletonIterator(1); try { Iterators.paddedPartition(source, 0); fail(); } catch (IllegalArgumentException expected) { } } public void testPaddedPartition_empty() { Iterator<Integer> source = Iterators.emptyIterator(); Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 1); assertFalse(partitions.hasNext()); } public void testPaddedPartition_singleton1() { Iterator<Integer> source = Iterators.singletonIterator(1); Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 1); assertTrue(partitions.hasNext()); assertTrue(partitions.hasNext()); assertEquals(ImmutableList.of(1), partitions.next()); assertFalse(partitions.hasNext()); } public void testPaddedPartition_singleton2() { Iterator<Integer> source = Iterators.singletonIterator(1); Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 2); assertTrue(partitions.hasNext()); assertTrue(partitions.hasNext()); assertEquals(asList(1, null), partitions.next()); assertFalse(partitions.hasNext()); } public void testPaddedPartition_view() { List<Integer> list = asList(1, 2); Iterator<List<Integer>> partitions = Iterators.paddedPartition(list.iterator(), 1); // Changes before the PaddedPartition is retrieved are reflected list.set(0, 3); List<Integer> first = partitions.next(); // Changes after are not list.set(0, 4); assertEquals(ImmutableList.of(3), first); } public void testPaddedPartitionRandomAccess() { Iterator<Integer> source = asList(1, 2, 3).iterator(); Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 2); assertTrue(partitions.next() instanceof RandomAccess); assertTrue(partitions.next() instanceof RandomAccess); } public void testForArrayEmpty() { String[] array = new String[0]; Iterator<String> iterator = Iterators.forArray(array); assertFalse(iterator.hasNext()); try { iterator.next(); fail(); } catch (NoSuchElementException expected) {} } public void testForArrayTypical() { String[] array = {"foo", "bar"}; Iterator<String> iterator = Iterators.forArray(array); assertTrue(iterator.hasNext()); assertEquals("foo", iterator.next()); assertTrue(iterator.hasNext()); try { iterator.remove(); fail(); } catch (UnsupportedOperationException expected) {} assertEquals("bar", iterator.next()); assertFalse(iterator.hasNext()); try { iterator.next(); fail(); } catch (NoSuchElementException expected) {} } public void testForArrayOffset() { String[] array = {"foo", "bar", "cat", "dog"}; Iterator<String> iterator = Iterators.forArray(array, 1, 2, 0); assertTrue(iterator.hasNext()); assertEquals("bar", iterator.next()); assertTrue(iterator.hasNext()); assertEquals("cat", iterator.next()); assertFalse(iterator.hasNext()); try { Iterators.forArray(array, 2, 3, 0); fail(); } catch (IndexOutOfBoundsException expected) {} } public void testForArrayLength0() { String[] array = {"foo", "bar"}; assertFalse(Iterators.forArray(array, 0, 0, 0).hasNext()); assertFalse(Iterators.forArray(array, 1, 0, 0).hasNext()); assertFalse(Iterators.forArray(array, 2, 0, 0).hasNext()); try { Iterators.forArray(array, -1, 0, 0); fail(); } catch (IndexOutOfBoundsException expected) {} try { Iterators.forArray(array, 3, 0, 0); fail(); } catch (IndexOutOfBoundsException expected) {} } public void testForEnumerationEmpty() { Enumeration<Integer> enumer = enumerate(); Iterator<Integer> iter = Iterators.forEnumeration(enumer); assertFalse(iter.hasNext()); try { iter.next(); fail(); } catch (NoSuchElementException expected) { } } public void testForEnumerationSingleton() { Enumeration<Integer> enumer = enumerate(1); Iterator<Integer> iter = Iterators.forEnumeration(enumer); assertTrue(iter.hasNext()); assertTrue(iter.hasNext()); assertEquals(1, (int) iter.next()); try { iter.remove(); fail(); } catch (UnsupportedOperationException expected) { } assertFalse(iter.hasNext()); try { iter.next(); fail(); } catch (NoSuchElementException expected) { } } public void testForEnumerationTypical() { Enumeration<Integer> enumer = enumerate(1, 2, 3); Iterator<Integer> iter = Iterators.forEnumeration(enumer); assertTrue(iter.hasNext()); assertEquals(1, (int) iter.next()); assertTrue(iter.hasNext()); assertEquals(2, (int) iter.next()); assertTrue(iter.hasNext()); assertEquals(3, (int) iter.next()); assertFalse(iter.hasNext()); } public void testAsEnumerationEmpty() { Iterator<Integer> iter = Iterators.emptyIterator(); Enumeration<Integer> enumer = Iterators.asEnumeration(iter); assertFalse(enumer.hasMoreElements()); try { enumer.nextElement(); fail(); } catch (NoSuchElementException expected) { } } public void testAsEnumerationSingleton() { Iterator<Integer> iter = ImmutableList.of(1).iterator(); Enumeration<Integer> enumer = Iterators.asEnumeration(iter); assertTrue(enumer.hasMoreElements()); assertTrue(enumer.hasMoreElements()); assertEquals(1, (int) enumer.nextElement()); assertFalse(enumer.hasMoreElements()); try { enumer.nextElement(); fail(); } catch (NoSuchElementException expected) { } } public void testAsEnumerationTypical() { Iterator<Integer> iter = ImmutableList.of(1, 2, 3).iterator(); Enumeration<Integer> enumer = Iterators.asEnumeration(iter); assertTrue(enumer.hasMoreElements()); assertEquals(1, (int) enumer.nextElement()); assertTrue(enumer.hasMoreElements()); assertEquals(2, (int) enumer.nextElement()); assertTrue(enumer.hasMoreElements()); assertEquals(3, (int) enumer.nextElement()); assertFalse(enumer.hasMoreElements()); } private static Enumeration<Integer> enumerate(Integer... ints) { Vector<Integer> vector = new Vector<Integer>(); vector.addAll(asList(ints)); return vector.elements(); } public void testToString() { Iterator<String> iterator = Lists.newArrayList("yam", "bam", "jam", "ham").iterator(); assertEquals("[yam, bam, jam, ham]", Iterators.toString(iterator)); } public void testToStringWithNull() { Iterator<String> iterator = Lists.newArrayList("hello", null, "world").iterator(); assertEquals("[hello, null, world]", Iterators.toString(iterator)); } public void testToStringEmptyIterator() { Iterator<String> iterator = Collections.<String>emptyList().iterator(); assertEquals("[]", Iterators.toString(iterator)); } public void testLimit() { List<String> list = newArrayList(); try { Iterators.limit(list.iterator(), -1); fail("expected exception"); } catch (IllegalArgumentException expected) { // expected } assertFalse(Iterators.limit(list.iterator(), 0).hasNext()); assertFalse(Iterators.limit(list.iterator(), 1).hasNext()); list.add("cool"); assertFalse(Iterators.limit(list.iterator(), 0).hasNext()); assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 1))); assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 2))); list.add("pants"); assertFalse(Iterators.limit(list.iterator(), 0).hasNext()); assertEquals(ImmutableList.of("cool"), newArrayList(Iterators.limit(list.iterator(), 1))); assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 2))); assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 3))); } public void testLimitRemove() { List<String> list = newArrayList(); list.add("cool"); list.add("pants"); Iterator<String> iterator = Iterators.limit(list.iterator(), 1); iterator.next(); iterator.remove(); assertFalse(iterator.hasNext()); assertEquals(1, list.size()); assertEquals("pants", list.get(0)); } public void testGetNext_withDefault_singleton() { Iterator<String> iterator = Collections.singletonList("foo").iterator(); assertEquals("foo", Iterators.getNext(iterator, "bar")); } public void testGetNext_withDefault_empty() { Iterator<String> iterator = Iterators.emptyIterator(); assertEquals("bar", Iterators.getNext(iterator, "bar")); } public void testGetNext_withDefault_empty_null() { Iterator<String> iterator = Iterators.emptyIterator(); assertNull(Iterators.getNext(iterator, null)); } public void testGetNext_withDefault_two() { Iterator<String> iterator = asList("foo", "bar").iterator(); assertEquals("foo", Iterators.getNext(iterator, "x")); } public void testGetLast_basic() { List<String> list = newArrayList(); list.add("a"); list.add("b"); assertEquals("b", getLast(list.iterator())); } public void testGetLast_exception() { List<String> list = newArrayList(); try { getLast(list.iterator()); fail(); } catch (NoSuchElementException expected) { } } public void testGetLast_withDefault_singleton() { Iterator<String> iterator = Collections.singletonList("foo").iterator(); assertEquals("foo", Iterators.getLast(iterator, "bar")); } public void testGetLast_withDefault_empty() { Iterator<String> iterator = Iterators.emptyIterator(); assertEquals("bar", Iterators.getLast(iterator, "bar")); } public void testGetLast_withDefault_empty_null() { Iterator<String> iterator = Iterators.emptyIterator(); assertNull(Iterators.getLast(iterator, null)); } public void testGetLast_withDefault_two() { Iterator<String> iterator = asList("foo", "bar").iterator(); assertEquals("bar", Iterators.getLast(iterator, "x")); } public void testGet_basic() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); assertEquals("b", get(iterator, 1)); assertFalse(iterator.hasNext()); } public void testGet_atSize() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); try { get(iterator, 2); fail(); } catch (IndexOutOfBoundsException expected) {} assertFalse(iterator.hasNext()); } public void testGet_pastEnd() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); try { get(iterator, 5); fail(); } catch (IndexOutOfBoundsException expected) {} assertFalse(iterator.hasNext()); } public void testGet_empty() { List<String> list = newArrayList(); Iterator<String> iterator = list.iterator(); try { get(iterator, 0); fail(); } catch (IndexOutOfBoundsException expected) {} assertFalse(iterator.hasNext()); } public void testGet_negativeIndex() { List<String> list = newArrayList("a", "b", "c"); Iterator<String> iterator = list.iterator(); try { get(iterator, -1); fail(); } catch (IndexOutOfBoundsException expected) {} } public void testGet_withDefault_basic() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); assertEquals("a", get(iterator, 0, "c")); assertTrue(iterator.hasNext()); } public void testGet_withDefault_atSize() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); assertEquals("c", get(iterator, 2, "c")); assertFalse(iterator.hasNext()); } public void testGet_withDefault_pastEnd() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); assertEquals("c", get(iterator, 3, "c")); assertFalse(iterator.hasNext()); } public void testGet_withDefault_negativeIndex() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); try { get(iterator, -1, "c"); fail(); } catch (IndexOutOfBoundsException expected) { // pass } assertTrue(iterator.hasNext()); } public void testAdvance_basic() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); advance(iterator, 1); assertEquals("b", iterator.next()); } public void testAdvance_pastEnd() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); advance(iterator, 5); assertFalse(iterator.hasNext()); } public void testAdvance_illegalArgument() { List<String> list = newArrayList("a", "b", "c"); Iterator<String> iterator = list.iterator(); try { advance(iterator, -1); fail(); } catch (IllegalArgumentException expected) {} } public void testFrequency() { List<String> list = newArrayList("a", null, "b", null, "a", null); assertEquals(2, Iterators.frequency(list.iterator(), "a")); assertEquals(1, Iterators.frequency(list.iterator(), "b")); assertEquals(0, Iterators.frequency(list.iterator(), "c")); assertEquals(0, Iterators.frequency(list.iterator(), 4.2)); assertEquals(3, Iterators.frequency(list.iterator(), null)); } public void testRemoveAll() { List<String> list = newArrayList("a", "b", "c", "d", "e"); assertTrue(Iterators.removeAll( list.iterator(), newArrayList("b", "d", "f"))); assertEquals(newArrayList("a", "c", "e"), list); assertFalse(Iterators.removeAll( list.iterator(), newArrayList("x", "y", "z"))); assertEquals(newArrayList("a", "c", "e"), list); } public void testRemoveIf() { List<String> list = newArrayList("a", "b", "c", "d", "e"); assertTrue(Iterators.removeIf( list.iterator(), new Predicate<String>() { @Override public boolean apply(String s) { return s.equals("b") || s.equals("d") || s.equals("f"); } })); assertEquals(newArrayList("a", "c", "e"), list); assertFalse(Iterators.removeIf( list.iterator(), new Predicate<String>() { @Override public boolean apply(String s) { return s.equals("x") || s.equals("y") || s.equals("z"); } })); assertEquals(newArrayList("a", "c", "e"), list); } public void testRetainAll() { List<String> list = newArrayList("a", "b", "c", "d", "e"); assertTrue(Iterators.retainAll( list.iterator(), newArrayList("b", "d", "f"))); assertEquals(newArrayList("b", "d"), list); assertFalse(Iterators.retainAll( list.iterator(), newArrayList("b", "e", "d"))); assertEquals(newArrayList("b", "d"), list); } public void testConsumingIterator() { // Test data List<String> list = Lists.newArrayList("a", "b"); // Test & Verify Iterator<String> consumingIterator = Iterators.consumingIterator(list.iterator()); ASSERT.that(list).has().exactly("a", "b").inOrder(); assertTrue(consumingIterator.hasNext()); ASSERT.that(list).has().exactly("a", "b").inOrder(); assertEquals("a", consumingIterator.next()); ASSERT.that(list).has().item("b"); assertTrue(consumingIterator.hasNext()); assertEquals("b", consumingIterator.next()); ASSERT.that(list).isEmpty(); assertFalse(consumingIterator.hasNext()); } public void testIndexOf_consumedData() { Iterator<String> iterator = Lists.newArrayList("manny", "mo", "jack").iterator(); assertEquals(1, Iterators.indexOf(iterator, Predicates.equalTo("mo"))); assertEquals("jack", iterator.next()); assertFalse(iterator.hasNext()); } public void testIndexOf_consumedDataWithDuplicates() { Iterator<String> iterator = Lists.newArrayList("manny", "mo", "mo", "jack").iterator(); assertEquals(1, Iterators.indexOf(iterator, Predicates.equalTo("mo"))); assertEquals("mo", iterator.next()); assertEquals("jack", iterator.next()); assertFalse(iterator.hasNext()); } public void testIndexOf_consumedDataNoMatch() { Iterator<String> iterator = Lists.newArrayList("manny", "mo", "mo", "jack").iterator(); assertEquals(-1, Iterators.indexOf(iterator, Predicates.equalTo("bob"))); assertFalse(iterator.hasNext()); } @SuppressWarnings("deprecation") public void testUnmodifiableIteratorShortCircuit() { Iterator<String> mod = Lists.newArrayList("a", "b", "c").iterator(); UnmodifiableIterator<String> unmod = Iterators.unmodifiableIterator(mod); assertNotSame(mod, unmod); assertSame(unmod, Iterators.unmodifiableIterator(unmod)); assertSame(unmod, Iterators.unmodifiableIterator((Iterator<String>) unmod)); } @SuppressWarnings("deprecation") public void testPeekingIteratorShortCircuit() { Iterator<String> nonpeek = Lists.newArrayList("a", "b", "c").iterator(); PeekingIterator<String> peek = Iterators.peekingIterator(nonpeek); assertNotSame(peek, nonpeek); assertSame(peek, Iterators.peekingIterator(peek)); assertSame(peek, Iterators.peekingIterator((Iterator<String>) peek)); } }
Java
/* * Copyright (C) 2008 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.collect; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.MapConstraintsTest.TestKeyException; import com.google.common.collect.MapConstraintsTest.TestValueException; import com.google.common.collect.testing.google.TestStringBiMapGenerator; import junit.framework.TestCase; import java.util.Map.Entry; /** * Tests for {@link MapConstraints#constrainedBiMap}. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class ConstrainedBiMapTest extends TestCase { private static final String TEST_KEY = "42"; private static final String TEST_VALUE = "test"; private static final MapConstraint<String, String> TEST_CONSTRAINT = new TestConstraint(); public void testPutWithForbiddenKeyForbiddenValue() { BiMap<String, String> map = MapConstraints.constrainedBiMap( HashBiMap.<String, String> create(), TEST_CONSTRAINT); try { map.put(TEST_KEY, TEST_VALUE); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // success } } public void testPutWithForbiddenKeyAllowedValue() { BiMap<String, String> map = MapConstraints.constrainedBiMap( HashBiMap.<String, String> create(), TEST_CONSTRAINT); try { map.put(TEST_KEY, "allowed"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // success } } public void testPutWithAllowedKeyForbiddenValue() { BiMap<String, String> map = MapConstraints.constrainedBiMap( HashBiMap.<String, String> create(), TEST_CONSTRAINT); try { map.put("allowed", TEST_VALUE); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // success } } public static final class ConstrainedBiMapGenerator extends TestStringBiMapGenerator { @Override protected BiMap<String, String> create(Entry<String, String>[] entries) { BiMap<String, String> bimap = MapConstraints.constrainedBiMap( HashBiMap.<String, String> create(), TEST_CONSTRAINT); for (Entry<String, String> entry : entries) { checkArgument(!bimap.containsKey(entry.getKey())); bimap.put(entry.getKey(), entry.getValue()); } return bimap; } } private static final class TestConstraint implements MapConstraint<String, String> { @Override public void checkKeyValue(String key, String value) { if (TEST_KEY.equals(key)) { throw new TestKeyException(); } if (TEST_VALUE.equals(value)) { throw new TestValueException(); } } private static final long serialVersionUID = 0; } }
Java
/* * Copyright (C) 2009 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.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.testing.EqualsTester; /** * Tests {@link EmptyImmutableTable} * * @author Gregory Kick */ @GwtCompatible(emulated = true) public class EmptyImmutableTableTest extends AbstractImmutableTableTest { private static final ImmutableTable<Character, Integer, String> INSTANCE = ImmutableTable.of(); @Override Iterable<ImmutableTable<Character, Integer, String>> getTestInstances() { return ImmutableSet.of(INSTANCE); } public void testHashCode() { assertEquals(0, INSTANCE.hashCode()); } public void testEqualsObject() { Table<Character, Integer, String> nonEmptyTable = HashBasedTable.create(); nonEmptyTable.put('A', 1, "blah"); new EqualsTester() .addEqualityGroup(INSTANCE, HashBasedTable.create(), TreeBasedTable.create()) .addEqualityGroup(nonEmptyTable) .testEquals(); } public void testToString() { assertEquals("{}", INSTANCE.toString()); } public void testSize() { assertEquals(0, INSTANCE.size()); } public void testGet() { assertNull(INSTANCE.get('a', 1)); } public void testIsEmpty() { assertTrue(INSTANCE.isEmpty()); } public void testCellSet() { assertEquals(ImmutableSet.of(), INSTANCE.cellSet()); } public void testColumn() { assertEquals(ImmutableMap.of(), INSTANCE.column(1)); } public void testColumnKeySet() { assertEquals(ImmutableSet.of(), INSTANCE.columnKeySet()); } public void testColumnMap() { assertEquals(ImmutableMap.of(), INSTANCE.columnMap()); } public void testContains() { assertFalse(INSTANCE.contains('a', 1)); } public void testContainsColumn() { assertFalse(INSTANCE.containsColumn(1)); } public void testContainsRow() { assertFalse(INSTANCE.containsRow('a')); } public void testContainsValue() { assertFalse(INSTANCE.containsValue("blah")); } public void testRow() { assertEquals(ImmutableMap.of(), INSTANCE.row('a')); } public void testRowKeySet() { assertEquals(ImmutableSet.of(), INSTANCE.rowKeySet()); } public void testRowMap() { assertEquals(ImmutableMap.of(), INSTANCE.rowMap()); } public void testValues() { assertTrue(INSTANCE.values().isEmpty()); } }
Java
/* * Copyright (C) 2008 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.collect; import com.google.common.annotations.GwtCompatible; /** * Test cases for {@link HashBasedTable}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class HashBasedTableTest extends AbstractTableTest { @Override protected Table<String, Integer, Character> create( Object... data) { Table<String, Integer, Character> table = HashBasedTable.create(); table.put("foo", 4, 'a'); table.put("cat", 1, 'b'); table.clear(); populate(table, data); return table; } public void testCreateWithValidSizes() { Table<String, Integer, Character> table1 = HashBasedTable.create(100, 20); table1.put("foo", 1, 'a'); assertEquals((Character) 'a', table1.get("foo", 1)); Table<String, Integer, Character> table2 = HashBasedTable.create(100, 0); table2.put("foo", 1, 'a'); assertEquals((Character) 'a', table2.get("foo", 1)); Table<String, Integer, Character> table3 = HashBasedTable.create(0, 20); table3.put("foo", 1, 'a'); assertEquals((Character) 'a', table3.get("foo", 1)); Table<String, Integer, Character> table4 = HashBasedTable.create(0, 0); table4.put("foo", 1, 'a'); assertEquals((Character) 'a', table4.get("foo", 1)); } public void testCreateWithInvalidSizes() { try { HashBasedTable.create(100, -5); fail(); } catch (IllegalArgumentException expected) {} try { HashBasedTable.create(-5, 20); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateCopy() { Table<String, Integer, Character> original = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Table<String, Integer, Character> copy = HashBasedTable.create(original); assertEquals(original, copy); assertEquals((Character) 'a', copy.get("foo", 1)); } }
Java
/* * Copyright (C) 2009 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.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.collect.Table.Cell; import com.google.common.testing.EqualsTester; import com.google.common.testing.SerializableTester; import java.util.Arrays; import java.util.Map; /** * Test cases for {@link ArrayTable}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class ArrayTableTest extends AbstractTableTest { @Override protected ArrayTable<String, Integer, Character> create( Object... data) { // TODO: Specify different numbers of rows and columns, to detect problems // that arise when the wrong size is used. ArrayTable<String, Integer, Character> table = ArrayTable.create(asList("foo", "bar", "cat"), asList(1, 2, 3)); populate(table, data); return table; } @Override protected void assertSize(int expectedSize) { assertEquals(9, table.size()); } @Override protected boolean supportsRemove() { return false; } @Override protected boolean supportsNullValues() { return true; } // Overriding tests of behavior that differs for ArrayTable. @Override public void testContains() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.contains("foo", 1)); assertTrue(table.contains("bar", 1)); assertTrue(table.contains("foo", 3)); assertTrue(table.contains("foo", 2)); assertTrue(table.contains("bar", 3)); assertTrue(table.contains("cat", 1)); assertFalse(table.contains("foo", -1)); assertFalse(table.contains("bad", 1)); assertFalse(table.contains("bad", -1)); assertFalse(table.contains("foo", null)); assertFalse(table.contains(null, 1)); assertFalse(table.contains(null, null)); } @Override public void testContainsRow() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.containsRow("foo")); assertTrue(table.containsRow("bar")); assertTrue(table.containsRow("cat")); assertFalse(table.containsRow("bad")); assertFalse(table.containsRow(null)); } @Override public void testContainsColumn() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.containsColumn(1)); assertTrue(table.containsColumn(3)); assertTrue(table.containsColumn(2)); assertFalse(table.containsColumn(-1)); assertFalse(table.containsColumn(null)); } @Override public void testContainsValue() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.containsValue('a')); assertTrue(table.containsValue('b')); assertTrue(table.containsValue('c')); assertFalse(table.containsValue('x')); assertTrue(table.containsValue(null)); } @Override public void testIsEmpty() { assertFalse(table.isEmpty()); table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertFalse(table.isEmpty()); } @Override public void testEquals() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Table<String, Integer, Character> hashCopy = HashBasedTable.create(); hashCopy.put("foo", 1, 'a'); hashCopy.put("bar", 1, 'b'); hashCopy.put("foo", 3, 'c'); Table<String, Integer, Character> reordered = create("foo", 3, 'c', "foo", 1, 'a', "bar", 1, 'b'); Table<String, Integer, Character> smaller = create("foo", 1, 'a', "bar", 1, 'b'); Table<String, Integer, Character> swapOuter = create("bar", 1, 'a', "foo", 1, 'b', "bar", 3, 'c'); Table<String, Integer, Character> swapValues = create("foo", 1, 'c', "bar", 1, 'b', "foo", 3, 'a'); new EqualsTester() .addEqualityGroup(table, reordered) .addEqualityGroup(hashCopy) .addEqualityGroup(smaller) .addEqualityGroup(swapOuter) .addEqualityGroup(swapValues) .testEquals(); } @Override public void testHashCode() { table = ArrayTable.create(asList("foo", "bar"), asList(1, 3)); table.put("foo", 1, 'a'); table.put("bar", 1, 'b'); table.put("foo", 3, 'c'); int expected = Objects.hashCode("foo", 1, 'a') + Objects.hashCode("bar", 1, 'b') + Objects.hashCode("foo", 3, 'c') + Objects.hashCode("bar", 3, 0); assertEquals(expected, table.hashCode()); } @Override public void testRow() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<Integer, Character> expected = Maps.newHashMap(); expected.put(1, 'a'); expected.put(3, 'c'); expected.put(2, null); assertEquals(expected, table.row("foo")); } @Override public void testColumn() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<String, Character> expected = Maps.newHashMap(); expected.put("foo", 'a'); expected.put("bar", 'b'); expected.put("cat", null); assertEquals(expected, table.column(1)); } @Override public void testToStringSize1() { table = ArrayTable.create(ImmutableList.of("foo"), ImmutableList.of(1)); table.put("foo", 1, 'a'); assertEquals("{foo={1=a}}", table.toString()); } public void testCreateDuplicateRows() { try { ArrayTable.create(asList("foo", "bar", "foo"), asList(1, 2, 3)); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateDuplicateColumns() { try { ArrayTable.create(asList("foo", "bar"), asList(1, 2, 3, 2)); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateEmptyRows() { try { ArrayTable.create(Arrays.<String>asList(), asList(1, 2, 3)); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateEmptyColumns() { try { ArrayTable.create(asList("foo", "bar"), Arrays.<Integer>asList()); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateCopyArrayTable() { Table<String, Integer, Character> original = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Table<String, Integer, Character> copy = ArrayTable.create(original); assertEquals(original, copy); original.put("foo", 1, 'd'); assertEquals((Character) 'd', original.get("foo", 1)); assertEquals((Character) 'a', copy.get("foo", 1)); assertEquals(copy.rowKeySet(), original.rowKeySet()); assertEquals(copy.columnKeySet(), original.columnKeySet()); } public void testCreateCopyHashBasedTable() { Table<String, Integer, Character> original = HashBasedTable.create(); original.put("foo", 1, 'a'); original.put("bar", 1, 'b'); original.put("foo", 3, 'c'); Table<String, Integer, Character> copy = ArrayTable.create(original); assertEquals(4, copy.size()); assertEquals((Character) 'a', copy.get("foo", 1)); assertEquals((Character) 'b', copy.get("bar", 1)); assertEquals((Character) 'c', copy.get("foo", 3)); assertNull(copy.get("bar", 3)); original.put("foo", 1, 'd'); assertEquals((Character) 'd', original.get("foo", 1)); assertEquals((Character) 'a', copy.get("foo", 1)); assertEquals(copy.rowKeySet(), ImmutableSet.of("foo", "bar")); assertEquals(copy.columnKeySet(), ImmutableSet.of(1, 3)); } public void testCreateCopyEmptyTable() { Table<String, Integer, Character> original = HashBasedTable.create(); try { ArrayTable.create(original); fail(); } catch (IllegalArgumentException expected) {} } public void testSerialization() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); SerializableTester.reserializeAndAssert(table); } public void testToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("{foo={1=a, 2=null, 3=c}, " + "bar={1=b, 2=null, 3=null}, " + "cat={1=null, 2=null, 3=null}}", table.toString()); assertEquals("{foo={1=a, 2=null, 3=c}, " + "bar={1=b, 2=null, 3=null}, " + "cat={1=null, 2=null, 3=null}}", table.rowMap().toString()); } public void testCellSetToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[(foo,1)=a, (foo,2)=null, (foo,3)=c, " + "(bar,1)=b, (bar,2)=null, (bar,3)=null, " + "(cat,1)=null, (cat,2)=null, (cat,3)=null]", table.cellSet().toString()); } public void testRowKeySetToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[foo, bar, cat]", table.rowKeySet().toString()); } public void testColumnKeySetToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[1, 2, 3]", table.columnKeySet().toString()); } public void testValuesToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[a, null, c, b, null, null, null, null, null]", table.values().toString()); } public void testRowKeyList() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); ASSERT.that(table.rowKeyList()).has().exactly("foo", "bar", "cat").inOrder(); } public void testColumnKeyList() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); ASSERT.that(table.columnKeyList()).has().exactly(1, 2, 3).inOrder(); } public void testGetMissingKeys() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertNull(table.get("dog", 1)); assertNull(table.get("foo", 4)); } public void testAt() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals((Character) 'b', table.at(1, 0)); assertEquals((Character) 'c', table.at(0, 2)); assertNull(table.at(1, 2)); try { table.at(1, 3); fail(); } catch (IndexOutOfBoundsException expected) {} try { table.at(1, -1); fail(); } catch (IndexOutOfBoundsException expected) {} try { table.at(3, 2); fail(); } catch (IndexOutOfBoundsException expected) {} try { table.at(-1, 2); fail(); } catch (IndexOutOfBoundsException expected) {} } public void testSet() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals((Character) 'b', table.set(1, 0, 'd')); assertEquals((Character) 'd', table.get("bar", 1)); assertNull(table.set(2, 0, 'e')); assertEquals((Character) 'e', table.get("cat", 1)); assertEquals((Character) 'a', table.set(0, 0, null)); assertNull(table.get("foo", 1)); try { table.set(1, 3, 'z'); fail(); } catch (IndexOutOfBoundsException expected) {} try { table.set(1, -1, 'z'); fail(); } catch (IndexOutOfBoundsException expected) {} try { table.set(3, 2, 'z'); fail(); } catch (IndexOutOfBoundsException expected) {} try { table.set(-1, 2, 'z'); fail(); } catch (IndexOutOfBoundsException expected) {} assertFalse(table.containsValue('z')); } public void testEraseAll() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); table.eraseAll(); assertEquals(9, table.size()); assertNull(table.get("bar", 1)); assertTrue(table.containsRow("foo")); assertFalse(table.containsValue('a')); } public void testPutIllegal() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); try { table.put("dog", 1, 'd'); fail(); } catch (IllegalArgumentException expected) { assertEquals("Row dog not in [foo, bar, cat]", expected.getMessage()); } try { table.put("foo", 4, 'd'); fail(); } catch (IllegalArgumentException expected) { assertEquals("Column 4 not in [1, 2, 3]", expected.getMessage()); } assertFalse(table.containsValue('d')); } public void testErase() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals((Character) 'b', table.erase("bar", 1)); assertNull(table.get("bar", 1)); assertEquals(9, table.size()); assertNull(table.erase("bar", 1)); assertNull(table.erase("foo", 2)); assertNull(table.erase("dog", 1)); assertNull(table.erase("bar", 5)); assertNull(table.erase(null, 1)); assertNull(table.erase("bar", null)); } public void testCellReflectsChanges() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Cell<String, Integer, Character> cell = table.cellSet().iterator().next(); assertEquals(Tables.immutableCell("foo", 1, 'a'), cell); assertEquals((Character) 'a', table.put("foo", 1, 'd')); assertEquals(Tables.immutableCell("foo", 1, 'd'), cell); } public void testRowMissing() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<Integer, Character> row = table.row("dog"); assertTrue(row.isEmpty()); try { row.put(1, 'd'); fail(); } catch (UnsupportedOperationException expected) {} } public void testColumnMissing() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<String, Character> column = table.column(4); assertTrue(column.isEmpty()); try { column.put("foo", 'd'); fail(); } catch (UnsupportedOperationException expected) {} } public void testRowPutIllegal() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<Integer, Character> map = table.row("foo"); try { map.put(4, 'd'); fail(); } catch (IllegalArgumentException expected) { assertEquals("Column 4 not in [1, 2, 3]", expected.getMessage()); } } public void testColumnPutIllegal() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<String, Character> map = table.column(3); try { map.put("dog", 'd'); fail(); } catch (IllegalArgumentException expected) { assertEquals("Row dog not in [foo, bar, cat]", expected.getMessage()); } } }
Java
/* * Copyright (C) 2010 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import java.util.Iterator; import java.util.NoSuchElementException; /** Tests for {@link AbstractSequentialIterator}. */ @GwtCompatible(emulated = true) public class AbstractSequentialIteratorTest extends TestCase { public void testDoubler() { Iterable<Integer> doubled = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return newDoubler(2, 32); } }; ASSERT.that(doubled).iteratesOverSequence(2, 4, 8, 16, 32); } public void testSampleCode() { Iterable<Integer> actual = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { Iterator<Integer> powersOfTwo = new AbstractSequentialIterator<Integer>(1) { protected Integer computeNext(Integer previous) { return (previous == 1 << 30) ? null : previous * 2; } }; return powersOfTwo; } }; ASSERT.that(actual).iteratesOverSequence(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824); } public void testEmpty() { Iterator<Object> empty = newEmpty(); assertFalse(empty.hasNext()); try { empty.next(); fail(); } catch (NoSuchElementException expected) { } try { empty.remove(); fail(); } catch (UnsupportedOperationException expected) { } } public void testBroken() { Iterator<Object> broken = newBroken(); assertTrue(broken.hasNext()); // We can't retrieve even the known first element: try { broken.next(); fail(); } catch (MyException expected) { } try { broken.next(); fail(); } catch (MyException expected) { } } private static Iterator<Integer> newDoubler(int first, final int last) { return new AbstractSequentialIterator<Integer>(first) { @Override protected Integer computeNext(Integer previous) { return (previous == last) ? null : previous * 2; } }; } private static <T> Iterator<T> newEmpty() { return new AbstractSequentialIterator<T>(null) { @Override protected T computeNext(T previous) { throw new AssertionFailedError(); } }; } private static Iterator<Object> newBroken() { return new AbstractSequentialIterator<Object>("UNUSED") { @Override protected Object computeNext(Object previous) { throw new MyException(); } }; } private static class MyException extends RuntimeException {} }
Java
/* * Copyright (C) 2007 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.collect; import static com.google.common.collect.Iterables.skip; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.testing.IteratorTester; import junit.framework.TestCase; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * Unit test for {@code Iterables}. * * @author Kevin Bourrillion * @author Jared Levy */ @GwtCompatible(emulated = true) public class IterablesTest extends TestCase { public void testSize0() { Iterable<String> iterable = Collections.emptySet(); assertEquals(0, Iterables.size(iterable)); } public void testSize1Collection() { Iterable<String> iterable = Collections.singleton("a"); assertEquals(1, Iterables.size(iterable)); } public void testSize2NonCollection() { Iterable<Integer> iterable = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return asList(0, 1).iterator(); } }; assertEquals(2, Iterables.size(iterable)); } @SuppressWarnings("serial") public void testSize_collection_doesntIterate() { List<Integer> nums = asList(1, 2, 3, 4, 5); List<Integer> collection = new ArrayList<Integer>(nums) { @Override public Iterator<Integer> iterator() { fail("Don't iterate me!"); return null; } }; assertEquals(5, Iterables.size(collection)); } private static Iterable<String> iterable(String... elements) { final List<String> list = asList(elements); return new Iterable<String>() { @Override public Iterator<String> iterator() { return list.iterator(); } }; } public void test_contains_null_set_yes() { Iterable<String> set = Sets.newHashSet("a", null, "b"); assertTrue(Iterables.contains(set, null)); } public void test_contains_null_set_no() { Iterable<String> set = Sets.newHashSet("a", "b"); assertFalse(Iterables.contains(set, null)); } public void test_contains_null_iterable_yes() { Iterable<String> set = iterable("a", null, "b"); assertTrue(Iterables.contains(set, null)); } public void test_contains_null_iterable_no() { Iterable<String> set = iterable("a", "b"); assertFalse(Iterables.contains(set, null)); } public void test_contains_nonnull_set_yes() { Iterable<String> set = Sets.newHashSet("a", null, "b"); assertTrue(Iterables.contains(set, "b")); } public void test_contains_nonnull_set_no() { Iterable<String> set = Sets.newHashSet("a", "b"); assertFalse(Iterables.contains(set, "c")); } public void test_contains_nonnull_iterable_yes() { Iterable<String> set = iterable("a", null, "b"); assertTrue(Iterables.contains(set, "b")); } public void test_contains_nonnull_iterable_no() { Iterable<String> set = iterable("a", "b"); assertFalse(Iterables.contains(set, "c")); } public void testGetOnlyElement_noDefault_valid() { Iterable<String> iterable = Collections.singletonList("foo"); assertEquals("foo", Iterables.getOnlyElement(iterable)); } public void testGetOnlyElement_noDefault_empty() { Iterable<String> iterable = Collections.emptyList(); try { Iterables.getOnlyElement(iterable); fail(); } catch (NoSuchElementException expected) { } } public void testGetOnlyElement_noDefault_multiple() { Iterable<String> iterable = asList("foo", "bar"); try { Iterables.getOnlyElement(iterable); fail(); } catch (IllegalArgumentException expected) { } } public void testGetOnlyElement_withDefault_singleton() { Iterable<String> iterable = Collections.singletonList("foo"); assertEquals("foo", Iterables.getOnlyElement(iterable, "bar")); } public void testGetOnlyElement_withDefault_empty() { Iterable<String> iterable = Collections.emptyList(); assertEquals("bar", Iterables.getOnlyElement(iterable, "bar")); } public void testGetOnlyElement_withDefault_empty_null() { Iterable<String> iterable = Collections.emptyList(); assertNull(Iterables.getOnlyElement(iterable, null)); } public void testGetOnlyElement_withDefault_multiple() { Iterable<String> iterable = asList("foo", "bar"); try { Iterables.getOnlyElement(iterable, "x"); fail(); } catch (IllegalArgumentException expected) { } } public void testAny() { List<String> list = newArrayList(); Predicate<String> predicate = Predicates.equalTo("pants"); assertFalse(Iterables.any(list, predicate)); list.add("cool"); assertFalse(Iterables.any(list, predicate)); list.add("pants"); assertTrue(Iterables.any(list, predicate)); } public void testAll() { List<String> list = newArrayList(); Predicate<String> predicate = Predicates.equalTo("cool"); assertTrue(Iterables.all(list, predicate)); list.add("cool"); assertTrue(Iterables.all(list, predicate)); list.add("pants"); assertFalse(Iterables.all(list, predicate)); } public void testFind() { Iterable<String> list = newArrayList("cool", "pants"); assertEquals("cool", Iterables.find(list, Predicates.equalTo("cool"))); assertEquals("pants", Iterables.find(list, Predicates.equalTo("pants"))); try { Iterables.find(list, Predicates.alwaysFalse()); fail(); } catch (NoSuchElementException e) { } assertEquals("cool", Iterables.find(list, Predicates.alwaysTrue())); assertCanIterateAgain(list); } public void testFind_withDefault() { Iterable<String> list = Lists.newArrayList("cool", "pants"); assertEquals("cool", Iterables.find(list, Predicates.equalTo("cool"), "woot")); assertEquals("pants", Iterables.find(list, Predicates.equalTo("pants"), "woot")); assertEquals("woot", Iterables.find(list, Predicates.alwaysFalse(), "woot")); assertNull(Iterables.find(list, Predicates.alwaysFalse(), null)); assertEquals("cool", Iterables.find(list, Predicates.alwaysTrue(), "woot")); assertCanIterateAgain(list); } public void testTryFind() { Iterable<String> list = newArrayList("cool", "pants"); assertEquals(Optional.of("cool"), Iterables.tryFind(list, Predicates.equalTo("cool"))); assertEquals(Optional.of("pants"), Iterables.tryFind(list, Predicates.equalTo("pants"))); assertEquals(Optional.of("cool"), Iterables.tryFind(list, Predicates.alwaysTrue())); assertEquals(Optional.absent(), Iterables.tryFind(list, Predicates.alwaysFalse())); assertCanIterateAgain(list); } private static class TypeA {} private interface TypeB {} private static class HasBoth extends TypeA implements TypeB {} public void testTransform() { List<String> input = asList("1", "2", "3"); Iterable<Integer> result = Iterables.transform(input, new Function<String, Integer>() { @Override public Integer apply(String from) { return Integer.valueOf(from); } }); List<Integer> actual = newArrayList(result); List<Integer> expected = asList(1, 2, 3); assertEquals(expected, actual); assertCanIterateAgain(result); assertEquals("[1, 2, 3]", result.toString()); } public void testPoorlyBehavedTransform() { List<String> input = asList("1", null, "3"); Iterable<Integer> result = Iterables.transform(input, new Function<String, Integer>() { @Override public Integer apply(String from) { return Integer.valueOf(from); } }); Iterator<Integer> resultIterator = result.iterator(); resultIterator.next(); try { resultIterator.next(); fail("Expected NFE"); } catch (NumberFormatException nfe) { // Expected to fail. } } public void testNullFriendlyTransform() { List<Integer> input = asList(1, 2, null, 3); Iterable<String> result = Iterables.transform(input, new Function<Integer, String>() { @Override public String apply(Integer from) { return String.valueOf(from); } }); List<String> actual = newArrayList(result); List<String> expected = asList("1", "2", "null", "3"); assertEquals(expected, actual); } // Far less exhaustive than the tests in IteratorsTest public void testCycle() { Iterable<String> cycle = Iterables.cycle("a", "b"); int howManyChecked = 0; for (String string : cycle) { String expected = (howManyChecked % 2 == 0) ? "a" : "b"; assertEquals(expected, string); if (howManyChecked++ == 5) { break; } } // We left the last iterator pointing to "b". But a new iterator should // always point to "a". for (String string : cycle) { assertEquals("a", string); break; } assertEquals("[a, b] (cycled)", cycle.toString()); } // Again, the exhaustive tests are in IteratorsTest public void testConcatIterable() { List<Integer> list1 = newArrayList(1); List<Integer> list2 = newArrayList(4); @SuppressWarnings("unchecked") List<List<Integer>> input = newArrayList(list1, list2); Iterable<Integer> result = Iterables.concat(input); assertEquals(asList(1, 4), newArrayList(result)); // Now change the inputs and see result dynamically change as well list1.add(2); List<Integer> list3 = newArrayList(3); input.add(1, list3); assertEquals(asList(1, 2, 3, 4), newArrayList(result)); assertEquals("[1, 2, 3, 4]", result.toString()); } public void testConcatVarargs() { List<Integer> list1 = newArrayList(1); List<Integer> list2 = newArrayList(4); List<Integer> list3 = newArrayList(7, 8); List<Integer> list4 = newArrayList(9); List<Integer> list5 = newArrayList(10); @SuppressWarnings("unchecked") Iterable<Integer> result = Iterables.concat(list1, list2, list3, list4, list5); assertEquals(asList(1, 4, 7, 8, 9, 10), newArrayList(result)); assertEquals("[1, 4, 7, 8, 9, 10]", result.toString()); } public void testConcatNullPointerException() { List<Integer> list1 = newArrayList(1); List<Integer> list2 = newArrayList(4); try { Iterables.concat(list1, null, list2); fail(); } catch (NullPointerException expected) {} } public void testConcatPeformingFiniteCycle() { Iterable<Integer> iterable = asList(1, 2, 3); int n = 4; Iterable<Integer> repeated = Iterables.concat(Collections.nCopies(n, iterable)); ASSERT.that(repeated).iteratesOverSequence( 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3); } public void testPartition_badSize() { Iterable<Integer> source = Collections.singleton(1); try { Iterables.partition(source, 0); fail(); } catch (IllegalArgumentException expected) { } } public void testPartition_empty() { Iterable<Integer> source = Collections.emptySet(); Iterable<List<Integer>> partitions = Iterables.partition(source, 1); assertTrue(Iterables.isEmpty(partitions)); } public void testPartition_singleton1() { Iterable<Integer> source = Collections.singleton(1); Iterable<List<Integer>> partitions = Iterables.partition(source, 1); assertEquals(1, Iterables.size(partitions)); assertEquals(Collections.singletonList(1), partitions.iterator().next()); } public void testPartition_view() { List<Integer> list = asList(1, 2); Iterable<List<Integer>> partitions = Iterables.partition(list, 2); // Changes before the partition is retrieved are reflected list.set(0, 3); Iterator<List<Integer>> iterator = partitions.iterator(); // Changes before the partition is retrieved are reflected list.set(1, 4); List<Integer> first = iterator.next(); // Changes after are not list.set(0, 5); assertEquals(ImmutableList.of(3, 4), first); } public void testPaddedPartition_basic() { List<Integer> list = asList(1, 2, 3, 4, 5); Iterable<List<Integer>> partitions = Iterables.paddedPartition(list, 2); assertEquals(3, Iterables.size(partitions)); assertEquals(asList(5, null), Iterables.getLast(partitions)); } public void testPaddedPartitionRandomAccessInput() { Iterable<Integer> source = asList(1, 2, 3); Iterable<List<Integer>> partitions = Iterables.paddedPartition(source, 2); Iterator<List<Integer>> iterator = partitions.iterator(); assertTrue(iterator.next() instanceof RandomAccess); assertTrue(iterator.next() instanceof RandomAccess); } public void testPaddedPartitionNonRandomAccessInput() { Iterable<Integer> source = Lists.newLinkedList(asList(1, 2, 3)); Iterable<List<Integer>> partitions = Iterables.paddedPartition(source, 2); Iterator<List<Integer>> iterator = partitions.iterator(); // Even though the input list doesn't implement RandomAccess, the output // lists do. assertTrue(iterator.next() instanceof RandomAccess); assertTrue(iterator.next() instanceof RandomAccess); } // More tests in IteratorsTest public void testAddAllToList() { List<String> alreadyThere = newArrayList("already", "there"); List<String> freshlyAdded = newArrayList("freshly", "added"); boolean changed = Iterables.addAll(alreadyThere, freshlyAdded); ASSERT.that(alreadyThere).has().exactly( "already", "there", "freshly", "added").inOrder(); assertTrue(changed); } private static void assertCanIterateAgain(Iterable<?> iterable) { for (@SuppressWarnings("unused") Object obj : iterable) { } } // More exhaustive tests are in IteratorsTest. public void testElementsEqual() throws Exception { Iterable<?> a; Iterable<?> b; // A few elements. a = asList(4, 8, 15, 16, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertTrue(Iterables.elementsEqual(a, b)); // An element differs. a = asList(4, 8, 15, 12, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterables.elementsEqual(a, b)); // null versus non-null. a = asList(4, 8, 15, null, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterables.elementsEqual(a, b)); assertFalse(Iterables.elementsEqual(b, a)); // Different lengths. a = asList(4, 8, 15, 16, 23); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterables.elementsEqual(a, b)); assertFalse(Iterables.elementsEqual(b, a)); } public void testToString() { List<String> list = Collections.emptyList(); assertEquals("[]", Iterables.toString(list)); list = newArrayList("yam", "bam", "jam", "ham"); assertEquals("[yam, bam, jam, ham]", Iterables.toString(list)); } public void testLimit() { Iterable<String> iterable = newArrayList("foo", "bar", "baz"); Iterable<String> limited = Iterables.limit(iterable, 2); List<String> expected = ImmutableList.of("foo", "bar"); List<String> actual = newArrayList(limited); assertEquals(expected, actual); assertCanIterateAgain(limited); assertEquals("[foo, bar]", limited.toString()); } public void testLimit_illegalArgument() { List<String> list = newArrayList("a", "b", "c"); try { Iterables.limit(list, -1); fail(); } catch (IllegalArgumentException expected) {} } public void testIsEmpty() { Iterable<String> emptyList = Collections.emptyList(); assertTrue(Iterables.isEmpty(emptyList)); Iterable<String> singletonList = Collections.singletonList("foo"); assertFalse(Iterables.isEmpty(singletonList)); } public void testSkip_simple() { Collection<String> set = ImmutableSet.of("a", "b", "c", "d", "e"); assertEquals(newArrayList("c", "d", "e"), newArrayList(skip(set, 2))); assertEquals("[c, d, e]", skip(set, 2).toString()); } public void testSkip_simpleList() { Collection<String> list = newArrayList("a", "b", "c", "d", "e"); assertEquals(newArrayList("c", "d", "e"), newArrayList(skip(list, 2))); assertEquals("[c, d, e]", skip(list, 2).toString()); } public void testSkip_pastEnd() { Collection<String> set = ImmutableSet.of("a", "b"); assertEquals(emptyList(), newArrayList(skip(set, 20))); } public void testSkip_pastEndList() { Collection<String> list = newArrayList("a", "b"); assertEquals(emptyList(), newArrayList(skip(list, 20))); } public void testSkip_skipNone() { Collection<String> set = ImmutableSet.of("a", "b"); assertEquals(newArrayList("a", "b"), newArrayList(skip(set, 0))); } public void testSkip_skipNoneList() { Collection<String> list = newArrayList("a", "b"); assertEquals(newArrayList("a", "b"), newArrayList(skip(list, 0))); } public void testSkip_removal() { Collection<String> set = Sets.newHashSet("a", "b"); Iterator<String> iterator = skip(set, 2).iterator(); try { iterator.next(); } catch (NoSuchElementException suppressed) { // We want remove() to fail even after a failed call to next(). } try { iterator.remove(); fail("Expected IllegalStateException"); } catch (IllegalStateException expected) {} } public void testSkip_allOfMutableList_modifiable() { List<String> list = newArrayList("a", "b"); Iterator<String> iterator = skip(list, 2).iterator(); try { iterator.remove(); fail("Expected IllegalStateException"); } catch (IllegalStateException expected) {} } public void testSkip_allOfImmutableList_modifiable() { List<String> list = ImmutableList.of("a", "b"); Iterator<String> iterator = skip(list, 2).iterator(); try { iterator.remove(); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException expected) {} } public void testSkip_nonStructurallyModifiedList() throws Exception { List<String> list = newArrayList("a", "b", "c"); Iterable<String> tail = skip(list, 1); Iterator<String> tailIterator = tail.iterator(); list.set(2, "C"); assertEquals("b", tailIterator.next()); assertEquals("C", tailIterator.next()); assertFalse(tailIterator.hasNext()); } public void testSkip_structurallyModifiedSkipSome() throws Exception { Collection<String> set = newLinkedHashSet(asList("a", "b", "c")); Iterable<String> tail = skip(set, 1); set.remove("b"); set.addAll(newArrayList("A", "B", "C")); ASSERT.that(tail).iteratesOverSequence("c", "A", "B", "C"); } public void testSkip_structurallyModifiedSkipSomeList() throws Exception { List<String> list = newArrayList("a", "b", "c"); Iterable<String> tail = skip(list, 1); list.subList(1, 3).clear(); list.addAll(0, newArrayList("A", "B", "C")); ASSERT.that(tail).iteratesOverSequence("B", "C", "a"); } public void testSkip_structurallyModifiedSkipAll() throws Exception { Collection<String> set = newLinkedHashSet(asList("a", "b", "c")); Iterable<String> tail = skip(set, 2); set.remove("a"); set.remove("b"); assertFalse(tail.iterator().hasNext()); } public void testSkip_structurallyModifiedSkipAllList() throws Exception { List<String> list = newArrayList("a", "b", "c"); Iterable<String> tail = skip(list, 2); list.subList(0, 2).clear(); assertTrue(Iterables.isEmpty(tail)); } public void testSkip_illegalArgument() { List<String> list = newArrayList("a", "b", "c"); try { skip(list, -1); fail(); } catch (IllegalArgumentException expected) {} } private void testGetOnAbc(Iterable<String> iterable) { try { Iterables.get(iterable, -1); fail(); } catch (IndexOutOfBoundsException expected) {} assertEquals("a", Iterables.get(iterable, 0)); assertEquals("b", Iterables.get(iterable, 1)); assertEquals("c", Iterables.get(iterable, 2)); try { Iterables.get(iterable, 3); fail(); } catch (IndexOutOfBoundsException nsee) {} try { Iterables.get(iterable, 4); fail(); } catch (IndexOutOfBoundsException nsee) {} } private void testGetOnEmpty(Iterable<String> iterable) { try { Iterables.get(iterable, 0); fail(); } catch (IndexOutOfBoundsException expected) {} } public void testGet_list() { testGetOnAbc(newArrayList("a", "b", "c")); } public void testGet_emptyList() { testGetOnEmpty(Collections.<String>emptyList()); } public void testGet_sortedSet() { testGetOnAbc(ImmutableSortedSet.of("b", "c", "a")); } public void testGet_emptySortedSet() { testGetOnEmpty(ImmutableSortedSet.<String>of()); } public void testGet_iterable() { testGetOnAbc(ImmutableSet.of("a", "b", "c")); } public void testGet_emptyIterable() { testGetOnEmpty(Sets.<String>newHashSet()); } public void testGet_withDefault_negativePosition() { try { Iterables.get(newArrayList("a", "b", "c"), -1, "d"); fail(); } catch (IndexOutOfBoundsException expected) { // pass } } public void testGet_withDefault_simple() { ArrayList<String> list = newArrayList("a", "b", "c"); assertEquals("b", Iterables.get(list, 1, "d")); } public void testGet_withDefault_iterable() { Set<String> set = ImmutableSet.of("a", "b", "c"); assertEquals("b", Iterables.get(set, 1, "d")); } public void testGet_withDefault_last() { ArrayList<String> list = newArrayList("a", "b", "c"); assertEquals("c", Iterables.get(list, 2, "d")); } public void testGet_withDefault_lastPlusOne() { ArrayList<String> list = newArrayList("a", "b", "c"); assertEquals("d", Iterables.get(list, 3, "d")); } public void testGet_withDefault_doesntIterate() { List<String> list = new DiesOnIteratorArrayList(); list.add("a"); assertEquals("a", Iterables.get(list, 0, "b")); } public void testGetFirst_withDefault_singleton() { Iterable<String> iterable = Collections.singletonList("foo"); assertEquals("foo", Iterables.getFirst(iterable, "bar")); } public void testGetFirst_withDefault_empty() { Iterable<String> iterable = Collections.emptyList(); assertEquals("bar", Iterables.getFirst(iterable, "bar")); } public void testGetFirst_withDefault_empty_null() { Iterable<String> iterable = Collections.emptyList(); assertNull(Iterables.getFirst(iterable, null)); } public void testGetFirst_withDefault_multiple() { Iterable<String> iterable = asList("foo", "bar"); assertEquals("foo", Iterables.getFirst(iterable, "qux")); } public void testGetLast_list() { List<String> list = newArrayList("a", "b", "c"); assertEquals("c", Iterables.getLast(list)); } public void testGetLast_emptyList() { List<String> list = Collections.emptyList(); try { Iterables.getLast(list); fail(); } catch (NoSuchElementException e) {} } public void testGetLast_sortedSet() { SortedSet<String> sortedSet = ImmutableSortedSet.of("b", "c", "a"); assertEquals("c", Iterables.getLast(sortedSet)); } public void testGetLast_withDefault_singleton() { Iterable<String> iterable = Collections.singletonList("foo"); assertEquals("foo", Iterables.getLast(iterable, "bar")); } public void testGetLast_withDefault_empty() { Iterable<String> iterable = Collections.emptyList(); assertEquals("bar", Iterables.getLast(iterable, "bar")); } public void testGetLast_withDefault_empty_null() { Iterable<String> iterable = Collections.emptyList(); assertNull(Iterables.getLast(iterable, null)); } public void testGetLast_withDefault_multiple() { Iterable<String> iterable = asList("foo", "bar"); assertEquals("bar", Iterables.getLast(iterable, "qux")); } /** * {@link ArrayList} extension that forbids the use of * {@link Collection#iterator} for tests that need to prove that it isn't * called. */ private static class DiesOnIteratorArrayList extends ArrayList<String> { /** * @throws UnsupportedOperationException all the time */ @Override public Iterator<String> iterator() { throw new UnsupportedOperationException(); } } public void testGetLast_withDefault_not_empty_list() { // TODO: verify that this is the best testing strategy. List<String> diesOnIteratorList = new DiesOnIteratorArrayList(); diesOnIteratorList.add("bar"); assertEquals("bar", Iterables.getLast(diesOnIteratorList, "qux")); } /** * {@link TreeSet} extension that forbids the use of * {@link Collection#iterator} for tests that need to prove that it isn't * called. */ private static final class DiesOnIteratorTreeSet extends TreeSet<String> { /** * @throws UnsupportedOperationException all the time */ @Override public Iterator<String> iterator() { throw new UnsupportedOperationException(); } } public void testGetLast_emptySortedSet() { SortedSet<String> sortedSet = ImmutableSortedSet.of(); try { Iterables.getLast(sortedSet); fail(); } catch (NoSuchElementException e) {} } public void testGetLast_iterable() { Set<String> set = ImmutableSet.of("a", "b", "c"); assertEquals("c", Iterables.getLast(set)); } public void testGetLast_emptyIterable() { Set<String> set = Sets.newHashSet(); try { Iterables.getLast(set); fail(); } catch (NoSuchElementException e) {} } public void testUnmodifiableIterable() { List<String> list = newArrayList("a", "b", "c"); Iterable<String> iterable = Iterables.unmodifiableIterable(list); Iterator<String> iterator = iterable.iterator(); iterator.next(); try { iterator.remove(); fail(); } catch (UnsupportedOperationException expected) {} assertEquals("[a, b, c]", iterable.toString()); } @SuppressWarnings("deprecation") // test of deprecated method public void testUnmodifiableIterableShortCircuit() { List<String> list = newArrayList("a", "b", "c"); Iterable<String> iterable = Iterables.unmodifiableIterable(list); Iterable<String> iterable2 = Iterables.unmodifiableIterable(iterable); assertSame(iterable, iterable2); ImmutableList<String> immutableList = ImmutableList.of("a", "b", "c"); assertSame(immutableList, Iterables.unmodifiableIterable(immutableList)); assertSame(immutableList, Iterables.unmodifiableIterable((List<String>) immutableList)); } public void testFrequency_multiset() { Multiset<String> multiset = ImmutableMultiset.of("a", "b", "a", "c", "b", "a"); assertEquals(3, Iterables.frequency(multiset, "a")); assertEquals(2, Iterables.frequency(multiset, "b")); assertEquals(1, Iterables.frequency(multiset, "c")); assertEquals(0, Iterables.frequency(multiset, "d")); assertEquals(0, Iterables.frequency(multiset, 4.2)); assertEquals(0, Iterables.frequency(multiset, null)); } public void testFrequency_set() { Set<String> set = Sets.newHashSet("a", "b", "c"); assertEquals(1, Iterables.frequency(set, "a")); assertEquals(1, Iterables.frequency(set, "b")); assertEquals(1, Iterables.frequency(set, "c")); assertEquals(0, Iterables.frequency(set, "d")); assertEquals(0, Iterables.frequency(set, 4.2)); assertEquals(0, Iterables.frequency(set, null)); } public void testFrequency_list() { List<String> list = newArrayList("a", "b", "a", "c", "b", "a"); assertEquals(3, Iterables.frequency(list, "a")); assertEquals(2, Iterables.frequency(list, "b")); assertEquals(1, Iterables.frequency(list, "c")); assertEquals(0, Iterables.frequency(list, "d")); assertEquals(0, Iterables.frequency(list, 4.2)); assertEquals(0, Iterables.frequency(list, null)); } public void testRemoveAll_collection() { List<String> list = newArrayList("a", "b", "c", "d", "e"); assertTrue(Iterables.removeAll(list, newArrayList("b", "d", "f"))); assertEquals(newArrayList("a", "c", "e"), list); assertFalse(Iterables.removeAll(list, newArrayList("x", "y", "z"))); assertEquals(newArrayList("a", "c", "e"), list); } public void testRemoveAll_iterable() { final List<String> list = newArrayList("a", "b", "c", "d", "e"); Iterable<String> iterable = new Iterable<String>() { @Override public Iterator<String> iterator() { return list.iterator(); } }; assertTrue(Iterables.removeAll(iterable, newArrayList("b", "d", "f"))); assertEquals(newArrayList("a", "c", "e"), list); assertFalse(Iterables.removeAll(iterable, newArrayList("x", "y", "z"))); assertEquals(newArrayList("a", "c", "e"), list); } public void testRetainAll_collection() { List<String> list = newArrayList("a", "b", "c", "d", "e"); assertTrue(Iterables.retainAll(list, newArrayList("b", "d", "f"))); assertEquals(newArrayList("b", "d"), list); assertFalse(Iterables.retainAll(list, newArrayList("b", "e", "d"))); assertEquals(newArrayList("b", "d"), list); } public void testRetainAll_iterable() { final List<String> list = newArrayList("a", "b", "c", "d", "e"); Iterable<String> iterable = new Iterable<String>() { @Override public Iterator<String> iterator() { return list.iterator(); } }; assertTrue(Iterables.retainAll(iterable, newArrayList("b", "d", "f"))); assertEquals(newArrayList("b", "d"), list); assertFalse(Iterables.retainAll(iterable, newArrayList("b", "e", "d"))); assertEquals(newArrayList("b", "d"), list); } public void testRemoveIf_randomAccess() { List<String> list = newArrayList("a", "b", "c", "d", "e"); assertTrue(Iterables.removeIf(list, new Predicate<String>() { @Override public boolean apply(String s) { return s.equals("b") || s.equals("d") || s.equals("f"); } })); assertEquals(newArrayList("a", "c", "e"), list); assertFalse(Iterables.removeIf(list, new Predicate<String>() { @Override public boolean apply(String s) { return s.equals("x") || s.equals("y") || s.equals("z"); } })); assertEquals(newArrayList("a", "c", "e"), list); } public void testRemoveIf_transformedList() { List<String> list = newArrayList("1", "2", "3", "4", "5"); List<Integer> transformed = Lists.transform(list, new Function<String, Integer>() { @Override public Integer apply(String s) { return Integer.valueOf(s); } }); assertTrue(Iterables.removeIf(transformed, new Predicate<Integer>() { @Override public boolean apply(Integer n) { return (n & 1) == 0; // isEven() } })); assertEquals(newArrayList("1", "3", "5"), list); assertFalse(Iterables.removeIf(transformed, new Predicate<Integer>() { @Override public boolean apply(Integer n) { return (n & 1) == 0; // isEven() } })); assertEquals(newArrayList("1", "3", "5"), list); } public void testRemoveIf_noRandomAccess() { List<String> list = Lists.newLinkedList(asList("a", "b", "c", "d", "e")); assertTrue(Iterables.removeIf(list, new Predicate<String>() { @Override public boolean apply(String s) { return s.equals("b") || s.equals("d") || s.equals("f"); } })); assertEquals(newArrayList("a", "c", "e"), list); assertFalse(Iterables.removeIf(list, new Predicate<String>() { @Override public boolean apply(String s) { return s.equals("x") || s.equals("y") || s.equals("z"); } })); assertEquals(newArrayList("a", "c", "e"), list); } // The Maps returned by Maps.filterEntries(), Maps.filterKeys(), and // Maps.filterValues() are not tested with removeIf() since Maps are not // Iterable. Those returned by Iterators.filter() and Iterables.filter() // are not tested because they are unmodifiable. public void testIterableWithToString() { assertEquals("[]", create().toString()); assertEquals("[a]", create("a").toString()); assertEquals("[a, b, c]", create("a", "b", "c").toString()); assertEquals("[c, a, a]", create("c", "a", "a").toString()); } public void testIterableWithToStringNull() { assertEquals("[null]", create((String) null).toString()); assertEquals("[null, null]", create(null, null).toString()); assertEquals("[, null, a]", create("", null, "a").toString()); } /** Returns a new iterable over the specified strings. */ private static Iterable<String> create(String... strings) { final List<String> list = asList(strings); return new FluentIterable<String>() { @Override public Iterator<String> iterator() { return list.iterator(); } }; } public void testConsumingIterable() { // Test data List<String> list = Lists.newArrayList(asList("a", "b")); // Test & Verify Iterable<String> consumingIterable = Iterables.consumingIterable(list); Iterator<String> consumingIterator = consumingIterable.iterator(); ASSERT.that(list).has().exactly("a", "b").inOrder(); assertTrue(consumingIterator.hasNext()); ASSERT.that(list).has().exactly("a", "b").inOrder(); assertEquals("a", consumingIterator.next()); ASSERT.that(list).has().item("b"); assertTrue(consumingIterator.hasNext()); assertEquals("b", consumingIterator.next()); ASSERT.that(list).isEmpty(); assertFalse(consumingIterator.hasNext()); } public void testConsumingIterable_queue_iterator() { final List<Integer> items = ImmutableList.of(4, 8, 15, 16, 23, 42); new IteratorTester<Integer>( 3, UNMODIFIABLE, items, IteratorTester.KnownOrder.KNOWN_ORDER) { @Override protected Iterator<Integer> newTargetIterator() { return Iterables.consumingIterable(Lists.newLinkedList(items)) .iterator(); } }.test(); } public void testConsumingIterable_queue_removesFromQueue() { Queue<Integer> queue = Lists.newLinkedList(asList(5, 14)); Iterator<Integer> consumingIterator = Iterables.consumingIterable(queue).iterator(); assertEquals(5, queue.peek().intValue()); assertEquals(5, consumingIterator.next().intValue()); assertEquals(14, queue.peek().intValue()); assertTrue(consumingIterator.hasNext()); assertTrue(queue.isEmpty()); } public void testConsumingIterable_noIteratorCall() { Queue<Integer> queue = new UnIterableQueue<Integer>(Lists.newLinkedList(asList(5, 14))); Iterator<Integer> consumingIterator = Iterables.consumingIterable(queue).iterator(); /* * Make sure that we can get an element off without calling * UnIterableQueue.iterator(). */ assertEquals(5, consumingIterator.next().intValue()); } private static class UnIterableQueue<T> extends ForwardingQueue<T> { private Queue<T> queue; UnIterableQueue(Queue<T> queue) { this.queue = queue; } @Override public Iterator<T> iterator() { throw new UnsupportedOperationException(); } @Override protected Queue<T> delegate() { return queue; } } public void testIndexOf_empty() { List<String> list = new ArrayList<String>(); assertEquals(-1, Iterables.indexOf(list, Predicates.equalTo(""))); } public void testIndexOf_oneElement() { List<String> list = Lists.newArrayList("bob"); assertEquals(0, Iterables.indexOf(list, Predicates.equalTo("bob"))); assertEquals(-1, Iterables.indexOf(list, Predicates.equalTo("jack"))); } public void testIndexOf_twoElements() { List<String> list = Lists.newArrayList("mary", "bob"); assertEquals(0, Iterables.indexOf(list, Predicates.equalTo("mary"))); assertEquals(1, Iterables.indexOf(list, Predicates.equalTo("bob"))); assertEquals(-1, Iterables.indexOf(list, Predicates.equalTo("jack"))); } public void testIndexOf_withDuplicates() { List<String> list = Lists.newArrayList("mary", "bob", "bob", "bob", "sam"); assertEquals(0, Iterables.indexOf(list, Predicates.equalTo("mary"))); assertEquals(1, Iterables.indexOf(list, Predicates.equalTo("bob"))); assertEquals(4, Iterables.indexOf(list, Predicates.equalTo("sam"))); assertEquals(-1, Iterables.indexOf(list, Predicates.equalTo("jack"))); } private static final Predicate<CharSequence> STARTSWITH_A = new Predicate<CharSequence>() { @Override public boolean apply(CharSequence input) { return (input.length() > 0) && (input.charAt(0) == 'a'); } }; public void testIndexOf_genericPredicate() { List<CharSequence> sequences = Lists.newArrayList(); sequences.add("bob"); sequences.add(new StringBuilder("charlie")); sequences.add(new StringBuffer("henry")); sequences.add(new StringBuilder("apple")); sequences.add("lemon"); assertEquals(3, Iterables.indexOf(sequences, STARTSWITH_A)); } public void testIndexOf_genericPredicate2() { List<String> sequences = Lists.newArrayList("bob", "charlie", "henry", "apple", "lemon"); assertEquals(3, Iterables.indexOf(sequences, STARTSWITH_A)); } public void testMergeSorted_empty() { // Setup Iterable<Iterable<Integer>> elements = ImmutableList.of(); // Test Iterable<Integer> iterable = Iterables.mergeSorted(elements, Ordering.natural()); // Verify Iterator<Integer> iterator = iterable.iterator(); assertFalse(iterator.hasNext()); try { iterator.next(); fail("next() on empty iterator should throw NoSuchElementException"); } catch (NoSuchElementException e) { // Huzzah! } } public void testMergeSorted_single_empty() { // Setup Iterable<Integer> iterable0 = ImmutableList.of(); Iterable<Iterable<Integer>> iterables = ImmutableList.of(iterable0); // Test & Verify verifyMergeSorted(iterables, ImmutableList.<Integer>of()); } public void testMergeSorted_single() { // Setup Iterable<Integer> iterable0 = ImmutableList.of(1, 2, 3); Iterable<Iterable<Integer>> iterables = ImmutableList.of(iterable0); // Test & Verify verifyMergeSorted(iterables, iterable0); } public void testMergeSorted_pyramid() { List<Iterable<Integer>> iterables = Lists.newLinkedList(); List<Integer> allIntegers = Lists.newArrayList(); // Creates iterators like: {{}, {0}, {0, 1}, {0, 1, 2}, ...} for (int i = 0; i < 10; i++) { List<Integer> list = Lists.newLinkedList(); for (int j = 0; j < i; j++) { list.add(j); allIntegers.add(j); } iterables.add(Ordering.natural().sortedCopy(list)); } verifyMergeSorted(iterables, allIntegers); } // Like the pyramid, but creates more unique values, along with repeated ones. public void testMergeSorted_skipping_pyramid() { List<Iterable<Integer>> iterables = Lists.newLinkedList(); List<Integer> allIntegers = Lists.newArrayList(); for (int i = 0; i < 20; i++) { List<Integer> list = Lists.newLinkedList(); for (int j = 0; j < i; j++) { list.add(j * i); allIntegers.add(j * i); } iterables.add(Ordering.natural().sortedCopy(list)); } verifyMergeSorted(iterables, allIntegers); } private static void verifyMergeSorted(Iterable<Iterable<Integer>> iterables, Iterable<Integer> unsortedExpected) { Iterable<Integer> expected = Ordering.natural().sortedCopy(unsortedExpected); Iterable<Integer> mergedIterator = Iterables.mergeSorted(iterables, Ordering.natural()); assertEquals(Lists.newLinkedList(expected), Lists.newLinkedList(mergedIterator)); } }
Java
/* * Copyright (C) 2008 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; /** * Test cases for {@link Table} read operations. * * @author Jared Levy */ @GwtCompatible(emulated = true) public abstract class AbstractTableReadTest extends TestCase { protected Table<String, Integer, Character> table; /** * Creates a table with the specified data. * * @param data the table data, repeating the sequence row key, column key, * value once per mapping * @throws IllegalArgumentException if the size of {@code data} isn't a * multiple of 3 * @throws ClassCastException if a data element has the wrong type */ protected abstract Table<String, Integer, Character> create(Object... data); protected void assertSize(int expectedSize) { assertEquals(expectedSize, table.size()); } @Override public void setUp() throws Exception { super.setUp(); table = create(); } public void testContains() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.contains("foo", 1)); assertTrue(table.contains("bar", 1)); assertTrue(table.contains("foo", 3)); assertFalse(table.contains("foo", 2)); assertFalse(table.contains("bar", 3)); assertFalse(table.contains("cat", 1)); assertFalse(table.contains("foo", null)); assertFalse(table.contains(null, 1)); assertFalse(table.contains(null, null)); } public void testContainsRow() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.containsRow("foo")); assertTrue(table.containsRow("bar")); assertFalse(table.containsRow("cat")); assertFalse(table.containsRow(null)); } public void testContainsColumn() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.containsColumn(1)); assertTrue(table.containsColumn(3)); assertFalse(table.containsColumn(2)); assertFalse(table.containsColumn(null)); } public void testContainsValue() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.containsValue('a')); assertTrue(table.containsValue('b')); assertTrue(table.containsValue('c')); assertFalse(table.containsValue('x')); assertFalse(table.containsValue(null)); } public void testGet() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals((Character) 'a', table.get("foo", 1)); assertEquals((Character) 'b', table.get("bar", 1)); assertEquals((Character) 'c', table.get("foo", 3)); assertNull(table.get("foo", 2)); assertNull(table.get("bar", 3)); assertNull(table.get("cat", 1)); assertNull(table.get("foo", null)); assertNull(table.get(null, 1)); assertNull(table.get(null, null)); } public void testIsEmpty() { assertTrue(table.isEmpty()); table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertFalse(table.isEmpty()); } public void testSize() { assertSize(0); table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertSize(3); } public void testEquals() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Table<String, Integer, Character> hashCopy = HashBasedTable.create(table); Table<String, Integer, Character> reordered = create("foo", 3, 'c', "foo", 1, 'a', "bar", 1, 'b'); Table<String, Integer, Character> smaller = create("foo", 1, 'a', "bar", 1, 'b'); Table<String, Integer, Character> swapOuter = create("bar", 1, 'a', "foo", 1, 'b', "bar", 3, 'c'); Table<String, Integer, Character> swapValues = create("foo", 1, 'c', "bar", 1, 'b', "foo", 3, 'a'); new EqualsTester() .addEqualityGroup(table, hashCopy, reordered) .addEqualityGroup(smaller) .addEqualityGroup(swapOuter) .addEqualityGroup(swapValues) .testEquals(); } public void testHashCode() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); int expected = Objects.hashCode("foo", 1, 'a') + Objects.hashCode("bar", 1, 'b') + Objects.hashCode("foo", 3, 'c'); assertEquals(expected, table.hashCode()); } public void testToStringSize1() { table = create("foo", 1, 'a'); assertEquals("{foo={1=a}}", table.toString()); } public void testRow() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals(ImmutableMap.of(1, 'a', 3, 'c'), table.row("foo")); } // This test assumes that the implementation does not support null keys. public void testRowNull() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); try { table.row(null); fail(); } catch (NullPointerException expected) {} } public void testColumn() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals(ImmutableMap.of("foo", 'a', "bar", 'b'), table.column(1)); } // This test assumes that the implementation does not support null keys. public void testColumnNull() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); try { table.column(null); fail(); } catch (NullPointerException expected) {} } public void testColumnSetPartialOverlap() { table = create( "foo", 1, 'a', "bar", 1, 'b', "foo", 2, 'c', "bar", 3, 'd'); ASSERT.that(table.columnKeySet()).has().exactly(1, 2, 3); } }
Java
/* * Copyright (C) 2008 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.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.Table.Cell; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; /** * Tests for {@link Tables}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class TablesTest extends TestCase { public void testImmutableEntryToString() { Cell<String, Integer, Character> entry = Tables.immutableCell("foo", 1, 'a'); assertEquals("(foo,1)=a", entry.toString()); Cell<String, Integer, Character> nullEntry = Tables.immutableCell(null, null, null); assertEquals("(null,null)=null", nullEntry.toString()); } public void testEntryEquals() { Cell<String, Integer, Character> entry = Tables.immutableCell("foo", 1, 'a'); new EqualsTester() .addEqualityGroup(entry, Tables.immutableCell("foo", 1, 'a')) .addEqualityGroup(Tables.immutableCell("bar", 1, 'a')) .addEqualityGroup(Tables.immutableCell("foo", 2, 'a')) .addEqualityGroup(Tables.immutableCell("foo", 1, 'b')) .addEqualityGroup(Tables.immutableCell(null, null, null)) .testEquals(); } public void testEntryEqualsNull() { Cell<String, Integer, Character> entry = Tables.immutableCell(null, null, null); new EqualsTester() .addEqualityGroup(entry, Tables.immutableCell(null, null, null)) .addEqualityGroup(Tables.immutableCell("bar", null, null)) .addEqualityGroup(Tables.immutableCell(null, 2, null)) .addEqualityGroup(Tables.immutableCell(null, null, 'b')) .addEqualityGroup(Tables.immutableCell("foo", 1, 'a')) .testEquals(); } }
Java
/* * Copyright (C) 2007 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.collect; import static com.google.common.collect.Maps.transformEntries; import static com.google.common.collect.Maps.transformValues; import static com.google.common.collect.testing.Helpers.mapEntry; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Equivalence; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Maps.EntryTransformer; import com.google.common.collect.Maps.ValueDifferenceImpl; import com.google.common.collect.SetsTest.Derived; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.concurrent.ConcurrentMap; /** * Unit test for {@code Maps}. * * @author Kevin Bourrillion * @author Mike Bostock * @author Jared Levy */ @GwtCompatible(emulated = true) public class MapsTest extends TestCase { private static final Comparator<Integer> SOME_COMPARATOR = Collections.reverseOrder(); public void testHashMap() { HashMap<Integer, Integer> map = Maps.newHashMap(); assertEquals(Collections.emptyMap(), map); } public void testHashMapWithInitialMap() { Map<String, Integer> original = new TreeMap<String, Integer>(); original.put("a", 1); original.put("b", 2); original.put("c", 3); HashMap<String, Integer> map = Maps.newHashMap(original); assertEquals(original, map); } public void testHashMapGeneralizesTypes() { Map<String, Integer> original = new TreeMap<String, Integer>(); original.put("a", 1); original.put("b", 2); original.put("c", 3); HashMap<Object, Object> map = Maps.newHashMap((Map<? extends Object, ? extends Object>) original); assertEquals(original, map); } public void testCapacityForNegativeSizeFails() { try { Maps.capacity(-1); fail("Negative expected size must result in IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } public void testCapacityForLargeSizes() { int[] largeExpectedSizes = new int[] { Integer.MAX_VALUE / 2 - 1, Integer.MAX_VALUE / 2, Integer.MAX_VALUE / 2 + 1, Integer.MAX_VALUE - 1, Integer.MAX_VALUE}; for (int expectedSize : largeExpectedSizes) { int capacity = Maps.capacity(expectedSize); assertTrue( "capacity (" + capacity + ") must be >= expectedSize (" + expectedSize + ")", capacity >= expectedSize); } } public void testLinkedHashMap() { LinkedHashMap<Integer, Integer> map = Maps.newLinkedHashMap(); assertEquals(Collections.emptyMap(), map); } @SuppressWarnings("serial") public void testLinkedHashMapWithInitialMap() { Map<String, String> map = new LinkedHashMap<String, String>() {{ put("Hello", "World"); put("first", "second"); put("polygene", "lubricants"); put("alpha", "betical"); }}; LinkedHashMap<String, String> copy = Maps.newLinkedHashMap(map); Iterator<Entry<String, String>> iter = copy.entrySet().iterator(); assertTrue(iter.hasNext()); Entry<String, String> entry = iter.next(); assertEquals("Hello", entry.getKey()); assertEquals("World", entry.getValue()); assertTrue(iter.hasNext()); entry = iter.next(); assertEquals("first", entry.getKey()); assertEquals("second", entry.getValue()); assertTrue(iter.hasNext()); entry = iter.next(); assertEquals("polygene", entry.getKey()); assertEquals("lubricants", entry.getValue()); assertTrue(iter.hasNext()); entry = iter.next(); assertEquals("alpha", entry.getKey()); assertEquals("betical", entry.getValue()); assertFalse(iter.hasNext()); } public void testLinkedHashMapGeneralizesTypes() { Map<String, Integer> original = new LinkedHashMap<String, Integer>(); original.put("a", 1); original.put("b", 2); original.put("c", 3); HashMap<Object, Object> map = Maps.<Object, Object>newLinkedHashMap(original); assertEquals(original, map); } public void testIdentityHashMap() { IdentityHashMap<Integer, Integer> map = Maps.newIdentityHashMap(); assertEquals(Collections.emptyMap(), map); } public void testConcurrentMap() { ConcurrentMap<Integer, Integer> map = Maps.newConcurrentMap(); assertEquals(Collections.emptyMap(), map); } public void testTreeMap() { TreeMap<Integer, Integer> map = Maps.newTreeMap(); assertEquals(Collections.emptyMap(), map); assertNull(map.comparator()); } public void testTreeMapDerived() { TreeMap<Derived, Integer> map = Maps.newTreeMap(); assertEquals(Collections.emptyMap(), map); map.put(new Derived("foo"), 1); map.put(new Derived("bar"), 2); ASSERT.that(map.keySet()).has().exactly( new Derived("bar"), new Derived("foo")).inOrder(); ASSERT.that(map.values()).has().exactly(2, 1).inOrder(); assertNull(map.comparator()); } public void testTreeMapNonGeneric() { TreeMap<LegacyComparable, Integer> map = Maps.newTreeMap(); assertEquals(Collections.emptyMap(), map); map.put(new LegacyComparable("foo"), 1); map.put(new LegacyComparable("bar"), 2); ASSERT.that(map.keySet()).has().exactly( new LegacyComparable("bar"), new LegacyComparable("foo")).inOrder(); ASSERT.that(map.values()).has().exactly(2, 1).inOrder(); assertNull(map.comparator()); } public void testTreeMapWithComparator() { TreeMap<Integer, Integer> map = Maps.newTreeMap(SOME_COMPARATOR); assertEquals(Collections.emptyMap(), map); assertSame(SOME_COMPARATOR, map.comparator()); } public void testTreeMapWithInitialMap() { SortedMap<Integer, Integer> map = Maps.newTreeMap(); map.put(5, 10); map.put(3, 20); map.put(1, 30); TreeMap<Integer, Integer> copy = Maps.newTreeMap(map); assertEquals(copy, map); assertSame(copy.comparator(), map.comparator()); } public enum SomeEnum { SOME_INSTANCE } public void testEnumMap() { EnumMap<SomeEnum, Integer> map = Maps.newEnumMap(SomeEnum.class); assertEquals(Collections.emptyMap(), map); map.put(SomeEnum.SOME_INSTANCE, 0); assertEquals(Collections.singletonMap(SomeEnum.SOME_INSTANCE, 0), map); } public void testEnumMapNullClass() { try { Maps.<SomeEnum, Long>newEnumMap((Class<MapsTest.SomeEnum>) null); fail("no exception thrown"); } catch (NullPointerException expected) { } } public void testEnumMapWithInitialEnumMap() { EnumMap<SomeEnum, Integer> original = Maps.newEnumMap(SomeEnum.class); original.put(SomeEnum.SOME_INSTANCE, 0); EnumMap<SomeEnum, Integer> copy = Maps.newEnumMap(original); assertEquals(original, copy); } public void testEnumMapWithInitialEmptyEnumMap() { EnumMap<SomeEnum, Integer> original = Maps.newEnumMap(SomeEnum.class); EnumMap<SomeEnum, Integer> copy = Maps.newEnumMap(original); assertEquals(original, copy); assertNotSame(original, copy); } public void testEnumMapWithInitialMap() { HashMap<SomeEnum, Integer> original = Maps.newHashMap(); original.put(SomeEnum.SOME_INSTANCE, 0); EnumMap<SomeEnum, Integer> copy = Maps.newEnumMap(original); assertEquals(original, copy); } public void testEnumMapWithInitialEmptyMap() { Map<SomeEnum, Integer> original = Maps.newHashMap(); try { Maps.newEnumMap(original); fail("Empty map must result in an IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } public void testToStringImplWithNullKeys() throws Exception { Map<String, String> hashmap = Maps.newHashMap(); hashmap.put("foo", "bar"); hashmap.put(null, "baz"); assertEquals(hashmap.toString(), Maps.toStringImpl(hashmap)); } public void testToStringImplWithNullValues() throws Exception { Map<String, String> hashmap = Maps.newHashMap(); hashmap.put("foo", "bar"); hashmap.put("baz", null); assertEquals(hashmap.toString(), Maps.toStringImpl(hashmap)); } private static final Map<Integer, Integer> EMPTY = Collections.emptyMap(); private static final Map<Integer, Integer> SINGLETON = Collections.singletonMap(1, 2); public void testMapDifferenceEmptyEmpty() { MapDifference<Integer, Integer> diff = Maps.difference(EMPTY, EMPTY); assertTrue(diff.areEqual()); assertEquals(EMPTY, diff.entriesOnlyOnLeft()); assertEquals(EMPTY, diff.entriesOnlyOnRight()); assertEquals(EMPTY, diff.entriesInCommon()); assertEquals(EMPTY, diff.entriesDiffering()); assertEquals("equal", diff.toString()); } public void testMapDifferenceEmptySingleton() { MapDifference<Integer, Integer> diff = Maps.difference(EMPTY, SINGLETON); assertFalse(diff.areEqual()); assertEquals(EMPTY, diff.entriesOnlyOnLeft()); assertEquals(SINGLETON, diff.entriesOnlyOnRight()); assertEquals(EMPTY, diff.entriesInCommon()); assertEquals(EMPTY, diff.entriesDiffering()); assertEquals("not equal: only on right={1=2}", diff.toString()); } public void testMapDifferenceSingletonEmpty() { MapDifference<Integer, Integer> diff = Maps.difference(SINGLETON, EMPTY); assertFalse(diff.areEqual()); assertEquals(SINGLETON, diff.entriesOnlyOnLeft()); assertEquals(EMPTY, diff.entriesOnlyOnRight()); assertEquals(EMPTY, diff.entriesInCommon()); assertEquals(EMPTY, diff.entriesDiffering()); assertEquals("not equal: only on left={1=2}", diff.toString()); } public void testMapDifferenceTypical() { Map<Integer, String> left = ImmutableMap.of( 1, "a", 2, "b", 3, "c", 4, "d", 5, "e"); Map<Integer, String> right = ImmutableMap.of( 1, "a", 3, "f", 5, "g", 6, "z"); MapDifference<Integer, String> diff1 = Maps.difference(left, right); assertFalse(diff1.areEqual()); assertEquals(ImmutableMap.of(2, "b", 4, "d"), diff1.entriesOnlyOnLeft()); assertEquals(ImmutableMap.of(6, "z"), diff1.entriesOnlyOnRight()); assertEquals(ImmutableMap.of(1, "a"), diff1.entriesInCommon()); assertEquals(ImmutableMap.of(3, ValueDifferenceImpl.create("c", "f"), 5, ValueDifferenceImpl.create("e", "g")), diff1.entriesDiffering()); assertEquals("not equal: only on left={2=b, 4=d}: only on right={6=z}: " + "value differences={3=(c, f), 5=(e, g)}", diff1.toString()); MapDifference<Integer, String> diff2 = Maps.difference(right, left); assertFalse(diff2.areEqual()); assertEquals(ImmutableMap.of(6, "z"), diff2.entriesOnlyOnLeft()); assertEquals(ImmutableMap.of(2, "b", 4, "d"), diff2.entriesOnlyOnRight()); assertEquals(ImmutableMap.of(1, "a"), diff2.entriesInCommon()); assertEquals(ImmutableMap.of(3, ValueDifferenceImpl.create("f", "c"), 5, ValueDifferenceImpl.create("g", "e")), diff2.entriesDiffering()); assertEquals("not equal: only on left={6=z}: only on right={2=b, 4=d}: " + "value differences={3=(f, c), 5=(g, e)}", diff2.toString()); } public void testMapDifferenceEquals() { Map<Integer, String> left = ImmutableMap.of( 1, "a", 2, "b", 3, "c", 4, "d", 5, "e"); Map<Integer, String> right = ImmutableMap.of( 1, "a", 3, "f", 5, "g", 6, "z"); Map<Integer, String> right2 = ImmutableMap.of( 1, "a", 3, "h", 5, "g", 6, "z"); MapDifference<Integer, String> original = Maps.difference(left, right); MapDifference<Integer, String> same = Maps.difference(left, right); MapDifference<Integer, String> reverse = Maps.difference(right, left); MapDifference<Integer, String> diff2 = Maps.difference(left, right2); new EqualsTester() .addEqualityGroup(original, same) .addEqualityGroup(reverse) .addEqualityGroup(diff2) .testEquals(); } public void testMapDifferencePredicateTypical() { Map<Integer, String> left = ImmutableMap.of( 1, "a", 2, "b", 3, "c", 4, "d", 5, "e"); Map<Integer, String> right = ImmutableMap.of( 1, "A", 3, "F", 5, "G", 6, "Z"); // TODO(kevinb): replace with Ascii.caseInsensitiveEquivalence() when it // exists Equivalence<String> caseInsensitiveEquivalence = Equivalence.equals().onResultOf( new Function<String, String>() { @Override public String apply(String input) { return input.toLowerCase(); } }); MapDifference<Integer, String> diff1 = Maps.difference(left, right, caseInsensitiveEquivalence); assertFalse(diff1.areEqual()); assertEquals(ImmutableMap.of(2, "b", 4, "d"), diff1.entriesOnlyOnLeft()); assertEquals(ImmutableMap.of(6, "Z"), diff1.entriesOnlyOnRight()); assertEquals(ImmutableMap.of(1, "a"), diff1.entriesInCommon()); assertEquals(ImmutableMap.of(3, ValueDifferenceImpl.create("c", "F"), 5, ValueDifferenceImpl.create("e", "G")), diff1.entriesDiffering()); assertEquals("not equal: only on left={2=b, 4=d}: only on right={6=Z}: " + "value differences={3=(c, F), 5=(e, G)}", diff1.toString()); MapDifference<Integer, String> diff2 = Maps.difference(right, left, caseInsensitiveEquivalence); assertFalse(diff2.areEqual()); assertEquals(ImmutableMap.of(6, "Z"), diff2.entriesOnlyOnLeft()); assertEquals(ImmutableMap.of(2, "b", 4, "d"), diff2.entriesOnlyOnRight()); assertEquals(ImmutableMap.of(1, "A"), diff2.entriesInCommon()); assertEquals(ImmutableMap.of(3, ValueDifferenceImpl.create("F", "c"), 5, ValueDifferenceImpl.create("G", "e")), diff2.entriesDiffering()); assertEquals("not equal: only on left={6=Z}: only on right={2=b, 4=d}: " + "value differences={3=(F, c), 5=(G, e)}", diff2.toString()); } private static final SortedMap<Integer, Integer> SORTED_EMPTY = Maps.newTreeMap(); private static final SortedMap<Integer, Integer> SORTED_SINGLETON = ImmutableSortedMap.of(1, 2); public void testMapDifferenceOfSortedMapIsSorted() { Map<Integer, Integer> map = SORTED_SINGLETON; MapDifference<Integer, Integer> difference = Maps.difference(map, EMPTY); assertTrue(difference instanceof SortedMapDifference); } public void testSortedMapDifferenceEmptyEmpty() { SortedMapDifference<Integer, Integer> diff = Maps.difference(SORTED_EMPTY, SORTED_EMPTY); assertTrue(diff.areEqual()); assertEquals(SORTED_EMPTY, diff.entriesOnlyOnLeft()); assertEquals(SORTED_EMPTY, diff.entriesOnlyOnRight()); assertEquals(SORTED_EMPTY, diff.entriesInCommon()); assertEquals(SORTED_EMPTY, diff.entriesDiffering()); assertEquals("equal", diff.toString()); } public void testSortedMapDifferenceEmptySingleton() { SortedMapDifference<Integer, Integer> diff = Maps.difference(SORTED_EMPTY, SORTED_SINGLETON); assertFalse(diff.areEqual()); assertEquals(SORTED_EMPTY, diff.entriesOnlyOnLeft()); assertEquals(SORTED_SINGLETON, diff.entriesOnlyOnRight()); assertEquals(SORTED_EMPTY, diff.entriesInCommon()); assertEquals(SORTED_EMPTY, diff.entriesDiffering()); assertEquals("not equal: only on right={1=2}", diff.toString()); } public void testSortedMapDifferenceSingletonEmpty() { SortedMapDifference<Integer, Integer> diff = Maps.difference(SORTED_SINGLETON, SORTED_EMPTY); assertFalse(diff.areEqual()); assertEquals(SORTED_SINGLETON, diff.entriesOnlyOnLeft()); assertEquals(SORTED_EMPTY, diff.entriesOnlyOnRight()); assertEquals(SORTED_EMPTY, diff.entriesInCommon()); assertEquals(SORTED_EMPTY, diff.entriesDiffering()); assertEquals("not equal: only on left={1=2}", diff.toString()); } public void testSortedMapDifferenceTypical() { SortedMap<Integer, String> left = ImmutableSortedMap.<Integer, String>reverseOrder() .put(1, "a").put(2, "b").put(3, "c").put(4, "d").put(5, "e") .build(); SortedMap<Integer, String> right = ImmutableSortedMap.of(1, "a", 3, "f", 5, "g", 6, "z"); SortedMapDifference<Integer, String> diff1 = Maps.difference(left, right); assertFalse(diff1.areEqual()); ASSERT.that(diff1.entriesOnlyOnLeft().entrySet()).has().exactly( Maps.immutableEntry(4, "d"), Maps.immutableEntry(2, "b")).inOrder(); ASSERT.that(diff1.entriesOnlyOnRight().entrySet()).has().item( Maps.immutableEntry(6, "z")); ASSERT.that(diff1.entriesInCommon().entrySet()).has().item( Maps.immutableEntry(1, "a")); ASSERT.that(diff1.entriesDiffering().entrySet()).has().exactly( Maps.immutableEntry(5, ValueDifferenceImpl.create("e", "g")), Maps.immutableEntry(3, ValueDifferenceImpl.create("c", "f"))).inOrder(); assertEquals("not equal: only on left={4=d, 2=b}: only on right={6=z}: " + "value differences={5=(e, g), 3=(c, f)}", diff1.toString()); SortedMapDifference<Integer, String> diff2 = Maps.difference(right, left); assertFalse(diff2.areEqual()); ASSERT.that(diff2.entriesOnlyOnLeft().entrySet()).has().item( Maps.immutableEntry(6, "z")); ASSERT.that(diff2.entriesOnlyOnRight().entrySet()).has().exactly( Maps.immutableEntry(2, "b"), Maps.immutableEntry(4, "d")).inOrder(); ASSERT.that(diff1.entriesInCommon().entrySet()).has().item( Maps.immutableEntry(1, "a")); assertEquals(ImmutableMap.of( 3, ValueDifferenceImpl.create("f", "c"), 5, ValueDifferenceImpl.create("g", "e")), diff2.entriesDiffering()); assertEquals("not equal: only on left={6=z}: only on right={2=b, 4=d}: " + "value differences={3=(f, c), 5=(g, e)}", diff2.toString()); } public void testSortedMapDifferenceImmutable() { SortedMap<Integer, String> left = Maps.newTreeMap( ImmutableSortedMap.of(1, "a", 2, "b", 3, "c", 4, "d", 5, "e")); SortedMap<Integer, String> right = Maps.newTreeMap(ImmutableSortedMap.of(1, "a", 3, "f", 5, "g", 6, "z")); SortedMapDifference<Integer, String> diff1 = Maps.difference(left, right); left.put(6, "z"); assertFalse(diff1.areEqual()); ASSERT.that(diff1.entriesOnlyOnLeft().entrySet()).has().exactly( Maps.immutableEntry(2, "b"), Maps.immutableEntry(4, "d")).inOrder(); ASSERT.that(diff1.entriesOnlyOnRight().entrySet()).has().item( Maps.immutableEntry(6, "z")); ASSERT.that(diff1.entriesInCommon().entrySet()).has().item( Maps.immutableEntry(1, "a")); ASSERT.that(diff1.entriesDiffering().entrySet()).has().exactly( Maps.immutableEntry(3, ValueDifferenceImpl.create("c", "f")), Maps.immutableEntry(5, ValueDifferenceImpl.create("e", "g"))).inOrder(); try { diff1.entriesInCommon().put(7, "x"); fail(); } catch (UnsupportedOperationException expected) { } try { diff1.entriesOnlyOnLeft().put(7, "x"); fail(); } catch (UnsupportedOperationException expected) { } try { diff1.entriesOnlyOnRight().put(7, "x"); fail(); } catch (UnsupportedOperationException expected) { } } public void testSortedMapDifferenceEquals() { SortedMap<Integer, String> left = ImmutableSortedMap.of(1, "a", 2, "b", 3, "c", 4, "d", 5, "e"); SortedMap<Integer, String> right = ImmutableSortedMap.of(1, "a", 3, "f", 5, "g", 6, "z"); SortedMap<Integer, String> right2 = ImmutableSortedMap.of(1, "a", 3, "h", 5, "g", 6, "z"); SortedMapDifference<Integer, String> original = Maps.difference(left, right); SortedMapDifference<Integer, String> same = Maps.difference(left, right); SortedMapDifference<Integer, String> reverse = Maps.difference(right, left); SortedMapDifference<Integer, String> diff2 = Maps.difference(left, right2); new EqualsTester() .addEqualityGroup(original, same) .addEqualityGroup(reverse) .addEqualityGroup(diff2) .testEquals(); } private static final Function<String, Integer> LENGTH_FUNCTION = new Function<String, Integer>() { @Override public Integer apply(String input) { return input.length(); } }; public void testAsMap() { Set<String> strings = ImmutableSet.of("one", "two", "three"); Map<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertEquals(Integer.valueOf(5), map.get("three")); assertNull(map.get("five")); ASSERT.that(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("two", 3), mapEntry("three", 5)).inOrder(); } public void testAsMapReadsThrough() { Set<String> strings = Sets.newLinkedHashSet(); Collections.addAll(strings, "one", "two", "three"); Map<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertNull(map.get("four")); strings.add("four"); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5, "four", 4), map); assertEquals(Integer.valueOf(4), map.get("four")); } public void testAsMapWritesThrough() { Set<String> strings = Sets.newLinkedHashSet(); Collections.addAll(strings, "one", "two", "three"); Map<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertEquals(Integer.valueOf(3), map.remove("two")); ASSERT.that(strings).has().exactly("one", "three").inOrder(); } public void testAsMapEmpty() { Set<String> strings = ImmutableSet.of(); Map<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); ASSERT.that(map.entrySet()).isEmpty(); assertTrue(map.isEmpty()); assertNull(map.get("five")); } private static class NonNavigableSortedSet extends ForwardingSortedSet<String> { private final SortedSet<String> delegate = Sets.newTreeSet(); @Override protected SortedSet<String> delegate() { return delegate; } } public void testAsMapReturnsSortedMapForSortedSetInput() { Set<String> set = new NonNavigableSortedSet(); assertTrue(Maps.asMap(set, Functions.identity()) instanceof SortedMap); } public void testAsMapSorted() { SortedSet<String> strings = new NonNavigableSortedSet(); Collections.addAll(strings, "one", "two", "three"); SortedMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertEquals(Integer.valueOf(5), map.get("three")); assertNull(map.get("five")); ASSERT.that(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("three", 5), mapEntry("two", 3)).inOrder(); ASSERT.that(map.tailMap("onea").entrySet()).has().exactly( mapEntry("three", 5), mapEntry("two", 3)).inOrder(); ASSERT.that(map.subMap("one", "two").entrySet()).has().exactly( mapEntry("one", 3), mapEntry("three", 5)).inOrder(); } public void testAsMapSortedReadsThrough() { SortedSet<String> strings = new NonNavigableSortedSet(); Collections.addAll(strings, "one", "two", "three"); SortedMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertNull(map.comparator()); assertEquals(ImmutableSortedMap.of("one", 3, "two", 3, "three", 5), map); assertNull(map.get("four")); strings.add("four"); assertEquals( ImmutableSortedMap.of("one", 3, "two", 3, "three", 5, "four", 4), map); assertEquals(Integer.valueOf(4), map.get("four")); SortedMap<String, Integer> headMap = map.headMap("two"); assertEquals( ImmutableSortedMap.of("four", 4, "one", 3, "three", 5), headMap); strings.add("five"); strings.remove("one"); assertEquals( ImmutableSortedMap.of("five", 4, "four", 4, "three", 5), headMap); ASSERT.that(map.entrySet()).has().exactly( mapEntry("five", 4), mapEntry("four", 4), mapEntry("three", 5), mapEntry("two", 3)).inOrder(); } public void testAsMapSortedWritesThrough() { SortedSet<String> strings = new NonNavigableSortedSet(); Collections.addAll(strings, "one", "two", "three"); SortedMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertEquals(Integer.valueOf(3), map.remove("two")); ASSERT.that(strings).has().exactly("one", "three").inOrder(); } public void testAsMapSortedSubViewKeySetsDoNotSupportAdd() { SortedMap<String, Integer> map = Maps.asMap( new NonNavigableSortedSet(), LENGTH_FUNCTION); try { map.subMap("a", "z").keySet().add("a"); fail(); } catch (UnsupportedOperationException expected) { } try { map.tailMap("a").keySet().add("a"); fail(); } catch (UnsupportedOperationException expected) { } try { map.headMap("r").keySet().add("a"); fail(); } catch (UnsupportedOperationException expected) { } try { map.headMap("r").tailMap("m").keySet().add("a"); fail(); } catch (UnsupportedOperationException expected) { } } public void testAsMapSortedEmpty() { SortedSet<String> strings = new NonNavigableSortedSet(); SortedMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); ASSERT.that(map.entrySet()).isEmpty(); assertTrue(map.isEmpty()); assertNull(map.get("five")); } public void testToMap() { Iterable<String> strings = ImmutableList.of("one", "two", "three"); ImmutableMap<String, Integer> map = Maps.toMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); ASSERT.that(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("two", 3), mapEntry("three", 5)).inOrder(); } public void testToMapIterator() { Iterator<String> strings = ImmutableList.of("one", "two", "three").iterator(); ImmutableMap<String, Integer> map = Maps.toMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); ASSERT.that(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("two", 3), mapEntry("three", 5)).inOrder(); } public void testToMapWithDuplicateKeys() { Iterable<String> strings = ImmutableList.of("one", "two", "three", "two", "one"); ImmutableMap<String, Integer> map = Maps.toMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); ASSERT.that(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("two", 3), mapEntry("three", 5)).inOrder(); } public void testToMapWithNullKeys() { Iterable<String> strings = Arrays.asList("one", null, "three"); try { Maps.toMap(strings, Functions.constant("foo")); fail(); } catch (NullPointerException expected) { } } public void testToMapWithNullValues() { Iterable<String> strings = ImmutableList.of("one", "two", "three"); try { Maps.toMap(strings, Functions.constant(null)); fail(); } catch (NullPointerException expected) { } } private static final BiMap<Integer, String> INT_TO_STRING_MAP = new ImmutableBiMap.Builder<Integer, String>() .put(1, "one") .put(2, "two") .put(3, "three") .build(); public void testUniqueIndexCollection() { ImmutableMap<Integer, String> outputMap = Maps.uniqueIndex(INT_TO_STRING_MAP.values(), Functions.forMap(INT_TO_STRING_MAP.inverse())); assertEquals(INT_TO_STRING_MAP, outputMap); } public void testUniqueIndexIterable() { ImmutableMap<Integer, String> outputMap = Maps.uniqueIndex(new Iterable<String>() { @Override public Iterator<String> iterator() { return INT_TO_STRING_MAP.values().iterator(); } }, Functions.forMap(INT_TO_STRING_MAP.inverse())); assertEquals(INT_TO_STRING_MAP, outputMap); } public void testUniqueIndexIterator() { ImmutableMap<Integer, String> outputMap = Maps.uniqueIndex(INT_TO_STRING_MAP.values().iterator(), Functions.forMap(INT_TO_STRING_MAP.inverse())); assertEquals(INT_TO_STRING_MAP, outputMap); } /** Can't create the map if more than one value maps to the same key. */ public void testUniqueIndexDuplicates() { try { Maps.uniqueIndex(ImmutableSet.of("one", "uno"), Functions.constant(1)); fail(); } catch (IllegalArgumentException expected) { } } /** Null values are not allowed. */ public void testUniqueIndexNullValue() { List<String> listWithNull = Lists.newArrayList((String) null); try { Maps.uniqueIndex(listWithNull, Functions.constant(1)); fail(); } catch (NullPointerException expected) { } } /** Null keys aren't allowed either. */ public void testUniqueIndexNullKey() { List<String> oneStringList = Lists.newArrayList("foo"); try { Maps.uniqueIndex(oneStringList, Functions.constant(null)); fail(); } catch (NullPointerException expected) { } } /** * Constructs a "nefarious" map entry with the specified key and value, * meaning an entry that is suitable for testing that map entries cannot be * modified via a nefarious implementation of equals. This is used for testing * unmodifiable collections of map entries; for example, it should not be * possible to access the raw (modifiable) map entry via a nefarious equals * method. */ public static <K, V> Map.Entry<K, V> nefariousEntry( final K key, final V value) { return new AbstractMapEntry<K, V>() { @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(V value) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (o instanceof Map.Entry) { Map.Entry<K, V> e = (Map.Entry<K, V>) o; e.setValue(value); // muhahaha! } return super.equals(o); } }; } public void testUnmodifiableBiMap() { BiMap<Integer, String> mod = HashBiMap.create(); mod.put(1, "one"); mod.put(2, "two"); mod.put(3, "three"); BiMap<Number, String> unmod = Maps.<Number, String>unmodifiableBiMap(mod); /* No aliasing on inverse operations. */ assertSame(unmod.inverse(), unmod.inverse()); assertSame(unmod, unmod.inverse().inverse()); /* Unmodifiable is a view. */ mod.put(4, "four"); assertEquals(true, unmod.get(4).equals("four")); assertEquals(true, unmod.inverse().get("four").equals(4)); /* UnsupportedOperationException on direct modifications. */ try { unmod.put(4, "four"); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { unmod.forcePut(4, "four"); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { unmod.putAll(Collections.singletonMap(4, "four")); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} /* UnsupportedOperationException on indirect modifications. */ BiMap<String, Number> inverse = unmod.inverse(); try { inverse.put("four", 4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { inverse.forcePut("four", 4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { inverse.putAll(Collections.singletonMap("four", 4)); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} Set<String> values = unmod.values(); try { values.remove("four"); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} Set<Map.Entry<Number, String>> entries = unmod.entrySet(); Map.Entry<Number, String> entry = entries.iterator().next(); try { entry.setValue("four"); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} @SuppressWarnings("unchecked") Map.Entry<Integer, String> entry2 = (Map.Entry<Integer, String>) entries.toArray()[0]; try { entry2.setValue("four"); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} } public void testImmutableEntry() { Map.Entry<String, Integer> e = Maps.immutableEntry("foo", 1); assertEquals("foo", e.getKey()); assertEquals(1, (int) e.getValue()); try { e.setValue(2); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} assertEquals("foo=1", e.toString()); assertEquals(101575, e.hashCode()); } public void testImmutableEntryNull() { Map.Entry<String, Integer> e = Maps.immutableEntry((String) null, (Integer) null); assertNull(e.getKey()); assertNull(e.getValue()); try { e.setValue(null); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} assertEquals("null=null", e.toString()); assertEquals(0, e.hashCode()); } /** See {@link SynchronizedBiMapTest} for more tests. */ public void testSynchronizedBiMap() { BiMap<String, Integer> bimap = HashBiMap.create(); bimap.put("one", 1); BiMap<String, Integer> sync = Maps.synchronizedBiMap(bimap); bimap.put("two", 2); sync.put("three", 3); assertEquals(ImmutableSet.of(1, 2, 3), bimap.inverse().keySet()); assertEquals(ImmutableSet.of(1, 2, 3), sync.inverse().keySet()); } private static final Predicate<String> NOT_LENGTH_3 = new Predicate<String>() { @Override public boolean apply(String input) { return input == null || input.length() != 3; } }; private static final Predicate<Integer> EVEN = new Predicate<Integer>() { @Override public boolean apply(Integer input) { return input == null || input % 2 == 0; } }; private static final Predicate<Entry<String, Integer>> CORRECT_LENGTH = new Predicate<Entry<String, Integer>>() { @Override public boolean apply(Entry<String, Integer> input) { return input.getKey().length() == input.getValue(); } }; private static final Function<Integer, Double> SQRT_FUNCTION = new Function<Integer, Double>() { @Override public Double apply(Integer in) { return Math.sqrt(in); } }; public static class FilteredMapTest extends TestCase { Map<String, Integer> createUnfiltered() { return Maps.newHashMap(); } public void testFilteredKeysIllegalPut() { Map<String, Integer> unfiltered = createUnfiltered(); Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3); filtered.put("a", 1); filtered.put("b", 2); assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered); try { filtered.put("yyy", 3); fail(); } catch (IllegalArgumentException expected) {} } public void testFilteredKeysIllegalPutAll() { Map<String, Integer> unfiltered = createUnfiltered(); Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3); filtered.put("a", 1); filtered.put("b", 2); assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered); try { filtered.putAll(ImmutableMap.of("c", 3, "zzz", 4, "b", 5)); fail(); } catch (IllegalArgumentException expected) {} assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered); } public void testFilteredKeysFilteredReflectsBackingChanges() { Map<String, Integer> unfiltered = createUnfiltered(); Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3); unfiltered.put("two", 2); unfiltered.put("three", 3); unfiltered.put("four", 4); assertEquals(ImmutableMap.of("two", 2, "three", 3, "four", 4), unfiltered); assertEquals(ImmutableMap.of("three", 3, "four", 4), filtered); unfiltered.remove("three"); assertEquals(ImmutableMap.of("two", 2, "four", 4), unfiltered); assertEquals(ImmutableMap.of("four", 4), filtered); unfiltered.clear(); assertEquals(ImmutableMap.of(), unfiltered); assertEquals(ImmutableMap.of(), filtered); } public void testFilteredValuesIllegalPut() { Map<String, Integer> unfiltered = createUnfiltered(); Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN); filtered.put("a", 2); unfiltered.put("b", 4); unfiltered.put("c", 5); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); try { filtered.put("yyy", 3); fail(); } catch (IllegalArgumentException expected) {} assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); } public void testFilteredValuesIllegalPutAll() { Map<String, Integer> unfiltered = createUnfiltered(); Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN); filtered.put("a", 2); unfiltered.put("b", 4); unfiltered.put("c", 5); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); try { filtered.putAll(ImmutableMap.of("c", 4, "zzz", 5, "b", 6)); fail(); } catch (IllegalArgumentException expected) {} assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); } public void testFilteredValuesIllegalSetValue() { Map<String, Integer> unfiltered = createUnfiltered(); Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN); filtered.put("a", 2); filtered.put("b", 4); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); Entry<String, Integer> entry = filtered.entrySet().iterator().next(); try { entry.setValue(5); fail(); } catch (IllegalArgumentException expected) {} assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); } public void testFilteredValuesClear() { Map<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("one", 1); unfiltered.put("two", 2); unfiltered.put("three", 3); unfiltered.put("four", 4); Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN); assertEquals(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4), unfiltered); assertEquals(ImmutableMap.of("two", 2, "four", 4), filtered); filtered.clear(); assertEquals(ImmutableMap.of("one", 1, "three", 3), unfiltered); assertTrue(filtered.isEmpty()); } public void testFilteredEntriesIllegalPut() { Map<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("cat", 3); unfiltered.put("dog", 2); unfiltered.put("horse", 5); Map<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH); assertEquals(ImmutableMap.of("cat", 3, "horse", 5), filtered); filtered.put("chicken", 7); assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); try { filtered.put("cow", 7); fail(); } catch (IllegalArgumentException expected) {} assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); } public void testFilteredEntriesIllegalPutAll() { Map<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("cat", 3); unfiltered.put("dog", 2); unfiltered.put("horse", 5); Map<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH); assertEquals(ImmutableMap.of("cat", 3, "horse", 5), filtered); filtered.put("chicken", 7); assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); try { filtered.putAll(ImmutableMap.of("sheep", 5, "cow", 7)); fail(); } catch (IllegalArgumentException expected) {} assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); } public void testFilteredEntriesObjectPredicate() { Map<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("cat", 3); unfiltered.put("dog", 2); unfiltered.put("horse", 5); Predicate<Object> predicate = Predicates.alwaysFalse(); Map<String, Integer> filtered = Maps.filterEntries(unfiltered, predicate); assertTrue(filtered.isEmpty()); } public void testFilteredEntriesWildCardEntryPredicate() { Map<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("cat", 3); unfiltered.put("dog", 2); unfiltered.put("horse", 5); Predicate<Entry<?, ?>> predicate = new Predicate<Entry<?, ?>>() { @Override public boolean apply(Entry<?, ?> input) { return "cat".equals(input.getKey()) || Integer.valueOf(2) == input.getValue(); } }; Map<String, Integer> filtered = Maps.filterEntries(unfiltered, predicate); assertEquals(ImmutableMap.of("cat", 3, "dog", 2), filtered); } } public static class FilteredSortedMapTest extends FilteredMapTest { @Override SortedMap<String, Integer> createUnfiltered() { return Maps.newTreeMap(); } public void testFilterKeysIdentifiesSortedMap() { SortedMap<String, Integer> map = createUnfiltered(); assertTrue(Maps.filterKeys((Map<String, Integer>) map, NOT_LENGTH_3) instanceof SortedMap); } public void testFilterValuesIdentifiesSortedMap() { SortedMap<String, Integer> map = createUnfiltered(); assertTrue(Maps.filterValues((Map<String, Integer>) map, EVEN) instanceof SortedMap); } public void testFilterEntriesIdentifiesSortedMap() { SortedMap<String, Integer> map = createUnfiltered(); assertTrue(Maps.filterEntries((Map<String, Integer>) map, CORRECT_LENGTH) instanceof SortedMap); } public void testFirstAndLastKeyFilteredMap() { SortedMap<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("apple", 2); unfiltered.put("banana", 6); unfiltered.put("cat", 3); unfiltered.put("dog", 5); SortedMap<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH); assertEquals("banana", filtered.firstKey()); assertEquals("cat", filtered.lastKey()); } public void testHeadSubTailMap_FilteredMap() { SortedMap<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("apple", 2); unfiltered.put("banana", 6); unfiltered.put("cat", 4); unfiltered.put("dog", 3); SortedMap<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH); assertEquals(ImmutableMap.of("banana", 6), filtered.headMap("dog")); assertEquals(ImmutableMap.of(), filtered.headMap("banana")); assertEquals(ImmutableMap.of("banana", 6, "dog", 3), filtered.headMap("emu")); assertEquals(ImmutableMap.of("banana", 6), filtered.subMap("banana", "dog")); assertEquals(ImmutableMap.of("dog", 3), filtered.subMap("cat", "emu")); assertEquals(ImmutableMap.of("dog", 3), filtered.tailMap("cat")); assertEquals(ImmutableMap.of("banana", 6, "dog", 3), filtered.tailMap("banana")); } } public static class FilteredBiMapTest extends FilteredMapTest { @Override BiMap<String, Integer> createUnfiltered() { return HashBiMap.create(); } public void testFilterKeysIdentifiesBiMap() { BiMap<String, Integer> map = createUnfiltered(); assertTrue(Maps.filterKeys((Map<String, Integer>) map, NOT_LENGTH_3) instanceof BiMap); } public void testFilterValuesIdentifiesBiMap() { BiMap<String, Integer> map = createUnfiltered(); assertTrue(Maps.filterValues((Map<String, Integer>) map, EVEN) instanceof BiMap); } public void testFilterEntriesIdentifiesBiMap() { BiMap<String, Integer> map = createUnfiltered(); assertTrue(Maps.filterEntries((Map<String, Integer>) map, CORRECT_LENGTH) instanceof BiMap); } } public void testTransformValues() { Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9); Map<String, Double> transformed = transformValues(map, SQRT_FUNCTION); assertEquals(ImmutableMap.of("a", 2.0, "b", 3.0), transformed); } public void testTransformValuesSecretlySorted() { Map<String, Integer> map = sortedNotNavigable(ImmutableSortedMap.of("a", 4, "b", 9)); Map<String, Double> transformed = transformValues(map, SQRT_FUNCTION); assertEquals(ImmutableMap.of("a", 2.0, "b", 3.0), transformed); assertTrue(transformed instanceof SortedMap); } public void testTransformEntries() { Map<String, String> map = ImmutableMap.of("a", "4", "b", "9"); EntryTransformer<String, String, String> concat = new EntryTransformer<String, String, String>() { @Override public String transformEntry(String key, String value) { return key + value; } }; Map<String, String> transformed = transformEntries(map, concat); assertEquals(ImmutableMap.of("a", "a4", "b", "b9"), transformed); } public void testTransformEntriesSecretlySorted() { Map<String, String> map = ImmutableSortedMap.of("a", "4", "b", "9"); EntryTransformer<String, String, String> concat = new EntryTransformer<String, String, String>() { @Override public String transformEntry(String key, String value) { return key + value; } }; Map<String, String> transformed = transformEntries(map, concat); assertEquals(ImmutableMap.of("a", "a4", "b", "b9"), transformed); assertTrue(transformed instanceof SortedMap); } public void testTransformEntriesGenerics() { Map<Object, Object> map1 = ImmutableMap.<Object, Object>of(1, 2); Map<Object, Number> map2 = ImmutableMap.<Object, Number>of(1, 2); Map<Object, Integer> map3 = ImmutableMap.<Object, Integer>of(1, 2); Map<Number, Object> map4 = ImmutableMap.<Number, Object>of(1, 2); Map<Number, Number> map5 = ImmutableMap.<Number, Number>of(1, 2); Map<Number, Integer> map6 = ImmutableMap.<Number, Integer>of(1, 2); Map<Integer, Object> map7 = ImmutableMap.<Integer, Object>of(1, 2); Map<Integer, Number> map8 = ImmutableMap.<Integer, Number>of(1, 2); Map<Integer, Integer> map9 = ImmutableMap.<Integer, Integer>of(1, 2); Map<? extends Number, ? extends Number> map0 = ImmutableMap.of(1, 2); EntryTransformer<Number, Number, Double> transformer = new EntryTransformer<Number, Number, Double>() { @Override public Double transformEntry(Number key, Number value) { return key.doubleValue() + value.doubleValue(); } }; Map<Object, Double> objectKeyed; Map<Number, Double> numberKeyed; Map<Integer, Double> integerKeyed; numberKeyed = transformEntries(map5, transformer); numberKeyed = transformEntries(map6, transformer); integerKeyed = transformEntries(map8, transformer); integerKeyed = transformEntries(map9, transformer); Map<? extends Number, Double> wildcarded = transformEntries(map0, transformer); // Can't loosen the key type: // objectKeyed = transformEntries(map5, transformer); // objectKeyed = transformEntries(map6, transformer); // objectKeyed = transformEntries(map8, transformer); // objectKeyed = transformEntries(map9, transformer); // numberKeyed = transformEntries(map8, transformer); // numberKeyed = transformEntries(map9, transformer); // Can't loosen the value type: // Map<Number, Number> looseValued1 = transformEntries(map5, transformer); // Map<Number, Number> looseValued2 = transformEntries(map6, transformer); // Map<Integer, Number> looseValued3 = transformEntries(map8, transformer); // Map<Integer, Number> looseValued4 = transformEntries(map9, transformer); // Can't call with too loose a key: // transformEntries(map1, transformer); // transformEntries(map2, transformer); // transformEntries(map3, transformer); // Can't call with too loose a value: // transformEntries(map1, transformer); // transformEntries(map4, transformer); // transformEntries(map7, transformer); } public void testTransformEntriesExample() { Map<String, Boolean> options = ImmutableMap.of("verbose", true, "sort", false); EntryTransformer<String, Boolean, String> flagPrefixer = new EntryTransformer<String, Boolean, String>() { @Override public String transformEntry(String key, Boolean value) { return value ? key : "no" + key; } }; Map<String, String> transformed = transformEntries(options, flagPrefixer); assertEquals("{verbose=verbose, sort=nosort}", transformed.toString()); } // Logically this would accept a NavigableMap, but that won't work under GWT. private static <K, V> SortedMap<K, V> sortedNotNavigable( final SortedMap<K, V> map) { return new ForwardingSortedMap<K, V>() { @Override protected SortedMap<K, V> delegate() { return map; } }; } public void testSortedMapTransformValues() { SortedMap<String, Integer> map = sortedNotNavigable(ImmutableSortedMap.of("a", 4, "b", 9)); SortedMap<String, Double> transformed = transformValues(map, SQRT_FUNCTION); /* * We'd like to sanity check that we didn't get a NavigableMap out, but we * can't easily do so while maintaining GWT compatibility. */ assertEquals(ImmutableSortedMap.of("a", 2.0, "b", 3.0), transformed); } public void testSortedMapTransformEntries() { SortedMap<String, String> map = sortedNotNavigable(ImmutableSortedMap.of("a", "4", "b", "9")); EntryTransformer<String, String, String> concat = new EntryTransformer<String, String, String>() { @Override public String transformEntry(String key, String value) { return key + value; } }; SortedMap<String, String> transformed = transformEntries(map, concat); /* * We'd like to sanity check that we didn't get a NavigableMap out, but we * can't easily do so while maintaining GWT compatibility. */ assertEquals(ImmutableSortedMap.of("a", "a4", "b", "b9"), transformed); } }
Java
/* * Copyright (C) 2011 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.collect; import static java.util.concurrent.TimeUnit.HOURS; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import junit.framework.TestCase; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * @author Charles Fry */ @GwtCompatible(emulated = true) public class MapMakerTest extends TestCase { // "Basher tests", where we throw a bunch of stuff at a Cache and check basic invariants. /* * TODO(cpovirk): eliminate duplication between these tests and those in LegacyMapMakerTests and * anywhere else */ /** Tests for the builder. */ public static class MakerTest extends TestCase { public void testInitialCapacity_negative() { MapMaker maker = new MapMaker(); try { maker.initialCapacity(-1); fail(); } catch (IllegalArgumentException expected) { } } // TODO(cpovirk): enable when ready public void xtestInitialCapacity_setTwice() { MapMaker maker = new MapMaker().initialCapacity(16); try { // even to the same value is not allowed maker.initialCapacity(16); fail(); } catch (IllegalArgumentException expected) { } } @SuppressWarnings("deprecation") // test of deprecated method public void testExpiration_setTwice() { MapMaker maker = new MapMaker().expireAfterWrite(1, HOURS); try { // even to the same value is not allowed maker.expireAfterWrite(1, HOURS); fail(); } catch (IllegalStateException expected) { } } public void testMaximumSize_setTwice() { MapMaker maker = new MapMaker().maximumSize(16); try { // even to the same value is not allowed maker.maximumSize(16); fail(); } catch (IllegalStateException expected) { } } public void testReturnsPlainConcurrentHashMapWhenPossible() { Map<?, ?> map = new MapMaker() .initialCapacity(5) .makeMap(); assertTrue(map instanceof ConcurrentHashMap); } } /** Tests of the built map with maximumSize. */ public static class MaximumSizeTest extends TestCase { public void testPut_sizeIsZero() { ConcurrentMap<Object, Object> map = new MapMaker().maximumSize(0).makeMap(); assertEquals(0, map.size()); map.put(new Object(), new Object()); assertEquals(0, map.size()); } public void testSizeBasedEviction() { int numKeys = 10; int mapSize = 5; ConcurrentMap<Object, Object> map = new MapMaker().maximumSize(mapSize).makeMap(); for (int i = 0; i < numKeys; i++) { map.put(i, i); } assertEquals(mapSize, map.size()); for (int i = numKeys - mapSize; i < mapSize; i++) { assertTrue(map.containsKey(i)); } } } /** Tests for recursive computation. */ public static class RecursiveComputationTest extends TestCase { Function<Integer, String> recursiveComputer = new Function<Integer, String>() { @Override public String apply(Integer key) { if (key > 0) { return key + ", " + recursiveMap.get(key - 1); } else { return "0"; } } }; ConcurrentMap<Integer, String> recursiveMap = new MapMaker() .makeComputingMap(recursiveComputer); public void testRecursiveComputation() { assertEquals("3, 2, 1, 0", recursiveMap.get(3)); } } /** * Tests for computing functionality. */ public static class ComputingTest extends TestCase { public void testComputerThatReturnsNull() { ConcurrentMap<Integer, String> map = new MapMaker() .makeComputingMap(new Function<Integer, String>() { @Override public String apply(Integer key) { return null; } }); try { map.get(1); fail(); } catch (NullPointerException e) { /* expected */ } } public void testRuntimeException() { final RuntimeException e = new RuntimeException(); ConcurrentMap<Object, Object> map = new MapMaker().makeComputingMap( new Function<Object, Object>() { @Override public Object apply(Object from) { throw e; } }); try { map.get(new Object()); fail(); } catch (ComputationException ce) { assertSame(e, ce.getCause()); } } } }
Java
/* * Copyright (C) 2007 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.collect; import static com.google.common.collect.BoundType.CLOSED; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.SortedSet; /** * Unit test for {@link TreeMultiset}. * * @author Neal Kanodia */ @GwtCompatible(emulated = true) public class TreeMultisetTest extends TestCase { public void testCreate() { TreeMultiset<String> multiset = TreeMultiset.create(); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); assertEquals(Ordering.natural(), multiset.comparator()); assertEquals("[bar, foo x 2]", multiset.toString()); } public void testCreateWithComparator() { Multiset<String> multiset = TreeMultiset.create(Collections.reverseOrder()); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); assertEquals("[foo x 2, bar]", multiset.toString()); } public void testCreateFromIterable() { Multiset<String> multiset = TreeMultiset.create(Arrays.asList("foo", "bar", "foo")); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); assertEquals("[bar, foo x 2]", multiset.toString()); } public void testToString() { Multiset<String> ms = TreeMultiset.create(); ms.add("a", 3); ms.add("c", 1); ms.add("b", 2); assertEquals("[a x 3, b x 2, c]", ms.toString()); } public void testElementSetSortedSetMethods() { TreeMultiset<String> ms = TreeMultiset.create(); ms.add("c", 1); ms.add("a", 3); ms.add("b", 2); SortedSet<String> elementSet = ms.elementSet(); assertEquals("a", elementSet.first()); assertEquals("c", elementSet.last()); assertEquals(Ordering.natural(), elementSet.comparator()); ASSERT.that(elementSet.headSet("b")).has().exactly("a").inOrder(); ASSERT.that(elementSet.tailSet("b")).has().exactly("b", "c").inOrder(); ASSERT.that(elementSet.subSet("a", "c")).has().exactly("a", "b").inOrder(); } public void testElementSetSubsetRemove() { TreeMultiset<String> ms = TreeMultiset.create(); ms.add("a", 1); ms.add("b", 3); ms.add("c", 2); ms.add("d", 1); ms.add("e", 3); ms.add("f", 2); SortedSet<String> elementSet = ms.elementSet(); ASSERT.that(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); SortedSet<String> subset = elementSet.subSet("b", "f"); ASSERT.that(subset).has().exactly("b", "c", "d", "e").inOrder(); assertTrue(subset.remove("c")); ASSERT.that(elementSet).has().exactly("a", "b", "d", "e", "f").inOrder(); ASSERT.that(subset).has().exactly("b", "d", "e").inOrder(); assertEquals(10, ms.size()); assertFalse(subset.remove("a")); ASSERT.that(elementSet).has().exactly("a", "b", "d", "e", "f").inOrder(); ASSERT.that(subset).has().exactly("b", "d", "e").inOrder(); assertEquals(10, ms.size()); } public void testElementSetSubsetRemoveAll() { TreeMultiset<String> ms = TreeMultiset.create(); ms.add("a", 1); ms.add("b", 3); ms.add("c", 2); ms.add("d", 1); ms.add("e", 3); ms.add("f", 2); SortedSet<String> elementSet = ms.elementSet(); ASSERT.that(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); SortedSet<String> subset = elementSet.subSet("b", "f"); ASSERT.that(subset).has().exactly("b", "c", "d", "e").inOrder(); assertTrue(subset.removeAll(Arrays.asList("a", "c"))); ASSERT.that(elementSet).has().exactly("a", "b", "d", "e", "f").inOrder(); ASSERT.that(subset).has().exactly("b", "d", "e").inOrder(); assertEquals(10, ms.size()); } public void testElementSetSubsetRetainAll() { TreeMultiset<String> ms = TreeMultiset.create(); ms.add("a", 1); ms.add("b", 3); ms.add("c", 2); ms.add("d", 1); ms.add("e", 3); ms.add("f", 2); SortedSet<String> elementSet = ms.elementSet(); ASSERT.that(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); SortedSet<String> subset = elementSet.subSet("b", "f"); ASSERT.that(subset).has().exactly("b", "c", "d", "e").inOrder(); assertTrue(subset.retainAll(Arrays.asList("a", "c"))); ASSERT.that(elementSet).has().exactly("a", "c", "f").inOrder(); ASSERT.that(subset).has().exactly("c").inOrder(); assertEquals(5, ms.size()); } public void testElementSetSubsetClear() { TreeMultiset<String> ms = TreeMultiset.create(); ms.add("a", 1); ms.add("b", 3); ms.add("c", 2); ms.add("d", 1); ms.add("e", 3); ms.add("f", 2); SortedSet<String> elementSet = ms.elementSet(); ASSERT.that(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); SortedSet<String> subset = elementSet.subSet("b", "f"); ASSERT.that(subset).has().exactly("b", "c", "d", "e").inOrder(); subset.clear(); ASSERT.that(elementSet).has().exactly("a", "f").inOrder(); ASSERT.that(subset).isEmpty(); assertEquals(3, ms.size()); } public void testCustomComparator() throws Exception { Comparator<String> comparator = new Comparator<String>() { @Override public int compare(String o1, String o2) { return o2.compareTo(o1); } }; TreeMultiset<String> ms = TreeMultiset.create(comparator); ms.add("b"); ms.add("c"); ms.add("a"); ms.add("b"); ms.add("d"); ASSERT.that(ms).has().exactly("d", "c", "b", "b", "a").inOrder(); SortedSet<String> elementSet = ms.elementSet(); assertEquals("d", elementSet.first()); assertEquals("a", elementSet.last()); assertEquals(comparator, elementSet.comparator()); } public void testNullAcceptingComparator() throws Exception { Comparator<String> comparator = Ordering.<String>natural().nullsFirst(); TreeMultiset<String> ms = TreeMultiset.create(comparator); ms.add("b"); ms.add(null); ms.add("a"); ms.add("b"); ms.add(null, 2); ASSERT.that(ms).has().exactly(null, null, null, "a", "b", "b").inOrder(); assertEquals(3, ms.count(null)); SortedSet<String> elementSet = ms.elementSet(); assertEquals(null, elementSet.first()); assertEquals("b", elementSet.last()); assertEquals(comparator, elementSet.comparator()); } private static final Comparator<String> DEGENERATE_COMPARATOR = new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.length() - o2.length(); } }; /** * Test a TreeMultiset with a comparator that can return 0 when comparing * unequal values. */ public void testDegenerateComparator() throws Exception { TreeMultiset<String> ms = TreeMultiset.create(DEGENERATE_COMPARATOR); ms.add("foo"); ms.add("a"); ms.add("bar"); ms.add("b"); ms.add("c"); assertEquals(2, ms.count("bar")); assertEquals(3, ms.count("b")); Multiset<String> ms2 = TreeMultiset.create(DEGENERATE_COMPARATOR); ms2.add("cat", 2); ms2.add("x", 3); assertEquals(ms, ms2); assertEquals(ms2, ms); SortedSet<String> elementSet = ms.elementSet(); assertEquals("a", elementSet.first()); assertEquals("foo", elementSet.last()); assertEquals(DEGENERATE_COMPARATOR, elementSet.comparator()); } public void testSubMultisetSize() { TreeMultiset<String> ms = TreeMultiset.create(); ms.add("a", Integer.MAX_VALUE); ms.add("b", Integer.MAX_VALUE); ms.add("c", 3); assertEquals(Integer.MAX_VALUE, ms.count("a")); assertEquals(Integer.MAX_VALUE, ms.count("b")); assertEquals(3, ms.count("c")); assertEquals(Integer.MAX_VALUE, ms.headMultiset("c", CLOSED).size()); assertEquals(Integer.MAX_VALUE, ms.headMultiset("b", CLOSED).size()); assertEquals(Integer.MAX_VALUE, ms.headMultiset("a", CLOSED).size()); assertEquals(3, ms.tailMultiset("c", CLOSED).size()); assertEquals(Integer.MAX_VALUE, ms.tailMultiset("b", CLOSED).size()); assertEquals(Integer.MAX_VALUE, ms.tailMultiset("a", CLOSED).size()); } }
Java
/* * Copyright (C) 2009 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.testing.EqualsTester; /** * Tests {@link SingletonImmutableTable}. * * @author Gregory Kick */ @GwtCompatible(emulated = true) public class SingletonImmutableTableTest extends AbstractImmutableTableTest { private final ImmutableTable<Character, Integer, String> testTable = new SingletonImmutableTable<Character, Integer, String>('a', 1, "blah"); public void testHashCode() { assertEquals(Objects.hashCode('a', 1, "blah"), testTable.hashCode()); } public void testCellSet() { assertEquals(ImmutableSet.of(Tables.immutableCell('a', 1, "blah")), testTable.cellSet()); } public void testColumn() { assertEquals(ImmutableMap.of(), testTable.column(0)); assertEquals(ImmutableMap.of('a', "blah"), testTable.column(1)); } public void testColumnKeySet() { assertEquals(ImmutableSet.of(1), testTable.columnKeySet()); } public void testColumnMap() { assertEquals(ImmutableMap.of(1, ImmutableMap.of('a', "blah")), testTable.columnMap()); } public void testRow() { assertEquals(ImmutableMap.of(), testTable.row('A')); assertEquals(ImmutableMap.of(1, "blah"), testTable.row('a')); } public void testRowKeySet() { assertEquals(ImmutableSet.of('a'), testTable.rowKeySet()); } public void testRowMap() { assertEquals(ImmutableMap.of('a', ImmutableMap.of(1, "blah")), testTable.rowMap()); } public void testEqualsObject() { new EqualsTester() .addEqualityGroup(testTable, HashBasedTable.create(testTable)) .addEqualityGroup(ImmutableTable.of(), HashBasedTable.create()) .addEqualityGroup(HashBasedTable.create(ImmutableTable.of('A', 2, ""))) .testEquals(); } public void testToString() { assertEquals("{a={1=blah}}", testTable.toString()); } public void testContains() { assertTrue(testTable.contains('a', 1)); assertFalse(testTable.contains('a', 2)); assertFalse(testTable.contains('A', 1)); assertFalse(testTable.contains('A', 2)); } public void testContainsColumn() { assertTrue(testTable.containsColumn(1)); assertFalse(testTable.containsColumn(2)); } public void testContainsRow() { assertTrue(testTable.containsRow('a')); assertFalse(testTable.containsRow('A')); } public void testContainsValue() { assertTrue(testTable.containsValue("blah")); assertFalse(testTable.containsValue("")); } public void testGet() { assertEquals("blah", testTable.get('a', 1)); assertNull(testTable.get('a', 2)); assertNull(testTable.get('A', 1)); assertNull(testTable.get('A', 2)); } public void testIsEmpty() { assertFalse(testTable.isEmpty()); } public void testSize() { assertEquals(1, testTable.size()); } public void testValues() { ASSERT.that(testTable.values()).has().item("blah"); } @Override Iterable<ImmutableTable<Character, Integer, String>> getTestInstances() { return ImmutableSet.of(testTable); } }
Java
/* * Copyright (C) 2007 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.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.ConcurrentModificationException; import java.util.List; import java.util.RandomAccess; /** * Unit tests for {@code ArrayListMultimap}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class ArrayListMultimapTest extends TestCase { protected ListMultimap<String, Integer> create() { return ArrayListMultimap.create(); } /** * Confirm that get() returns a List implementing RandomAccess. */ public void testGetRandomAccess() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); assertTrue(multimap.get("foo") instanceof RandomAccess); assertTrue(multimap.get("bar") instanceof RandomAccess); } /** * Confirm that removeAll() returns a List implementing RandomAccess. */ public void testRemoveAllRandomAccess() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); assertTrue(multimap.removeAll("foo") instanceof RandomAccess); assertTrue(multimap.removeAll("bar") instanceof RandomAccess); } /** * Confirm that replaceValues() returns a List implementing RandomAccess. */ public void testReplaceValuesRandomAccess() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); assertTrue(multimap.replaceValues("foo", asList(2, 4)) instanceof RandomAccess); assertTrue(multimap.replaceValues("bar", asList(2, 4)) instanceof RandomAccess); } /** * Test throwing ConcurrentModificationException when a sublist's ancestor's * delegate changes. */ public void testSublistConcurrentModificationException() { ListMultimap<String, Integer> multimap = create(); multimap.putAll("foo", asList(1, 2, 3, 4, 5)); List<Integer> list = multimap.get("foo"); ASSERT.that(multimap.get("foo")).has().exactly(1, 2, 3, 4, 5).inOrder(); List<Integer> sublist = list.subList(0, 5); ASSERT.that(sublist).has().exactly(1, 2, 3, 4, 5).inOrder(); sublist.clear(); assertTrue(sublist.isEmpty()); multimap.put("foo", 6); try { sublist.isEmpty(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) {} } public void testCreateFromMultimap() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); multimap.put("bar", 2); ArrayListMultimap<String, Integer> copy = ArrayListMultimap.create(multimap); assertEquals(multimap, copy); } public void testCreate() { ArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create(); assertEquals(3, multimap.expectedValuesPerKey); } public void testCreateFromSizes() { ArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create(15, 20); assertEquals(20, multimap.expectedValuesPerKey); } public void testCreateFromIllegalSizes() { try { ArrayListMultimap.create(15, -2); fail(); } catch (IllegalArgumentException expected) {} try { ArrayListMultimap.create(-15, 2); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateFromHashMultimap() { Multimap<String, Integer> original = HashMultimap.create(); ArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create(original); assertEquals(3, multimap.expectedValuesPerKey); } public void testCreateFromArrayListMultimap() { ArrayListMultimap<String, Integer> original = ArrayListMultimap.create(15, 20); ArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create(original); assertEquals(20, multimap.expectedValuesPerKey); } public void testTrimToSize() { ArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create(); multimap.put("foo", 1); multimap.put("foo", 2); multimap.put("bar", 3); multimap.trimToSize(); assertEquals(3, multimap.size()); ASSERT.that(multimap.get("foo")).has().exactly(1, 2).inOrder(); ASSERT.that(multimap.get("bar")).has().item(3); } }
Java
/* * Copyright (C) 2008 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.collect; import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Lists.newArrayList; import static java.util.Arrays.asList; import static java.util.Collections.nCopies; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Predicate; import junit.framework.TestCase; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * Tests for {@link Collections2}. * * @author Chris Povirk * @author Jared Levy */ @GwtCompatible(emulated = true) public class Collections2Test extends TestCase { static final Predicate<String> NOT_YYY_ZZZ = new Predicate<String>() { @Override public boolean apply(String input) { return !"yyy".equals(input) && !"zzz".equals(input); } }; static final Predicate<String> LENGTH_1 = new Predicate<String>() { @Override public boolean apply(String input) { return input.length() == 1; } }; static final Predicate<String> STARTS_WITH_VOWEL = new Predicate<String>() { @Override public boolean apply(String input) { return asList('a', 'e', 'i', 'o', 'u').contains(input.charAt(0)); } }; private static final Function<String, String> REMOVE_FIRST_CHAR = new Function<String, String>() { @Override public String apply(String from) { return ((from == null) || "".equals(from)) ? null : from.substring(1); } }; public void testOrderedPermutationSetEmpty() { List<Integer> list = newArrayList(); Collection<List<Integer>> permutationSet = Collections2.orderedPermutations(list); assertEquals(1, permutationSet.size()); ASSERT.that(permutationSet).has().item(list); Iterator<List<Integer>> permutations = permutationSet.iterator(); assertNextPermutation(Lists.<Integer>newArrayList(), permutations); assertNoMorePermutations(permutations); } public void testOrderedPermutationSetOneElement() { List<Integer> list = newArrayList(1); Iterator<List<Integer>> permutations = Collections2.orderedPermutations(list).iterator(); assertNextPermutation(newArrayList(1), permutations); assertNoMorePermutations(permutations); } public void testOrderedPermutationSetThreeElements() { List<String> list = newArrayList("b", "a", "c"); Iterator<List<String>> permutations = Collections2.orderedPermutations(list).iterator(); assertNextPermutation(newArrayList("a", "b", "c"), permutations); assertNextPermutation(newArrayList("a", "c", "b"), permutations); assertNextPermutation(newArrayList("b", "a", "c"), permutations); assertNextPermutation(newArrayList("b", "c", "a"), permutations); assertNextPermutation(newArrayList("c", "a", "b"), permutations); assertNextPermutation(newArrayList("c", "b", "a"), permutations); assertNoMorePermutations(permutations); } public void testOrderedPermutationSetRepeatedElements() { List<Integer> list = newArrayList(1, 1, 2, 2); Iterator<List<Integer>> permutations = Collections2.orderedPermutations(list, Ordering.natural()).iterator(); assertNextPermutation(newArrayList(1, 1, 2, 2), permutations); assertNextPermutation(newArrayList(1, 2, 1, 2), permutations); assertNextPermutation(newArrayList(1, 2, 2, 1), permutations); assertNextPermutation(newArrayList(2, 1, 1, 2), permutations); assertNextPermutation(newArrayList(2, 1, 2, 1), permutations); assertNextPermutation(newArrayList(2, 2, 1, 1), permutations); assertNoMorePermutations(permutations); } public void testOrderedPermutationSetRepeatedElementsSize() { List<Integer> list = newArrayList(1, 1, 1, 1, 2, 2, 3); Collection<List<Integer>> permutations = Collections2.orderedPermutations(list, Ordering.natural()); assertPermutationsCount(105, permutations); } public void testOrderedPermutationSetSizeOverflow() { // 12 elements won't overflow assertEquals(479001600 /*12!*/, Collections2.orderedPermutations( newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)).size()); // 13 elements overflow an int assertEquals(Integer.MAX_VALUE, Collections2.orderedPermutations( newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)).size()); // 21 elements overflow a long assertEquals(Integer.MAX_VALUE, Collections2.orderedPermutations( newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21)).size()); // Almost force an overflow in the binomial coefficient calculation assertEquals(1391975640 /*C(34,14)*/, Collections2.orderedPermutations( concat(nCopies(20, 1), nCopies(14, 2))).size()); // Do force an overflow in the binomial coefficient calculation assertEquals(Integer.MAX_VALUE, Collections2.orderedPermutations( concat(nCopies(21, 1), nCopies(14, 2))).size()); } public void testOrderedPermutationSetContains() { List<Integer> list = newArrayList(3, 2, 1); Collection<List<Integer>> permutationSet = Collections2.orderedPermutations(list); assertTrue(permutationSet.contains(newArrayList(1, 2, 3))); assertTrue(permutationSet.contains(newArrayList(2, 3, 1))); assertFalse(permutationSet.contains(newArrayList(1, 2))); assertFalse(permutationSet.contains(newArrayList(1, 1, 2, 3))); assertFalse(permutationSet.contains(newArrayList(1, 2, 3, 4))); assertFalse(permutationSet.contains(null)); } public void testPermutationSetEmpty() { Collection<List<Integer>> permutationSet = Collections2.permutations(Collections.<Integer>emptyList()); assertEquals(1, permutationSet.size()); assertTrue(permutationSet.contains(Collections.<Integer> emptyList())); Iterator<List<Integer>> permutations = permutationSet.iterator(); assertNextPermutation(Collections.<Integer> emptyList(), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetOneElement() { Iterator<List<Integer>> permutations = Collections2.permutations(Collections.<Integer> singletonList(1)) .iterator(); assertNextPermutation(newArrayList(1), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetTwoElements() { Iterator<List<Integer>> permutations = Collections2.permutations( newArrayList(1, 2)).iterator(); assertNextPermutation(newArrayList(1, 2), permutations); assertNextPermutation(newArrayList(2, 1), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetThreeElements() { Iterator<List<Integer>> permutations = Collections2.permutations( newArrayList(1, 2, 3)).iterator(); assertNextPermutation(newArrayList(1, 2, 3), permutations); assertNextPermutation(newArrayList(1, 3, 2), permutations); assertNextPermutation(newArrayList(3, 1, 2), permutations); assertNextPermutation(newArrayList(3, 2, 1), permutations); assertNextPermutation(newArrayList(2, 3, 1), permutations); assertNextPermutation(newArrayList(2, 1, 3), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetThreeElementsOutOfOrder() { Iterator<List<Integer>> permutations = Collections2.permutations( newArrayList(3, 2, 1)).iterator(); assertNextPermutation(newArrayList(3, 2, 1), permutations); assertNextPermutation(newArrayList(3, 1, 2), permutations); assertNextPermutation(newArrayList(1, 3, 2), permutations); assertNextPermutation(newArrayList(1, 2, 3), permutations); assertNextPermutation(newArrayList(2, 1, 3), permutations); assertNextPermutation(newArrayList(2, 3, 1), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetThreeRepeatedElements() { Iterator<List<Integer>> permutations = Collections2.permutations( newArrayList(1, 1, 2)).iterator(); assertNextPermutation(newArrayList(1, 1, 2), permutations); assertNextPermutation(newArrayList(1, 2, 1), permutations); assertNextPermutation(newArrayList(2, 1, 1), permutations); assertNextPermutation(newArrayList(2, 1, 1), permutations); assertNextPermutation(newArrayList(1, 2, 1), permutations); assertNextPermutation(newArrayList(1, 1, 2), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetFourElements() { Iterator<List<Integer>> permutations = Collections2.permutations( newArrayList(1, 2, 3, 4)).iterator(); assertNextPermutation(newArrayList(1, 2, 3, 4), permutations); assertNextPermutation(newArrayList(1, 2, 4, 3), permutations); assertNextPermutation(newArrayList(1, 4, 2, 3), permutations); assertNextPermutation(newArrayList(4, 1, 2, 3), permutations); assertNextPermutation(newArrayList(4, 1, 3, 2), permutations); assertNextPermutation(newArrayList(1, 4, 3, 2), permutations); assertNextPermutation(newArrayList(1, 3, 4, 2), permutations); assertNextPermutation(newArrayList(1, 3, 2, 4), permutations); assertNextPermutation(newArrayList(3, 1, 2, 4), permutations); assertNextPermutation(newArrayList(3, 1, 4, 2), permutations); assertNextPermutation(newArrayList(3, 4, 1, 2), permutations); assertNextPermutation(newArrayList(4, 3, 1, 2), permutations); assertNextPermutation(newArrayList(4, 3, 2, 1), permutations); assertNextPermutation(newArrayList(3, 4, 2, 1), permutations); assertNextPermutation(newArrayList(3, 2, 4, 1), permutations); assertNextPermutation(newArrayList(3, 2, 1, 4), permutations); assertNextPermutation(newArrayList(2, 3, 1, 4), permutations); assertNextPermutation(newArrayList(2, 3, 4, 1), permutations); assertNextPermutation(newArrayList(2, 4, 3, 1), permutations); assertNextPermutation(newArrayList(4, 2, 3, 1), permutations); assertNextPermutation(newArrayList(4, 2, 1, 3), permutations); assertNextPermutation(newArrayList(2, 4, 1, 3), permutations); assertNextPermutation(newArrayList(2, 1, 4, 3), permutations); assertNextPermutation(newArrayList(2, 1, 3, 4), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetSize() { assertPermutationsCount(1, Collections2.permutations(Collections.<Integer>emptyList())); assertPermutationsCount(1, Collections2.permutations(newArrayList(1))); assertPermutationsCount(2, Collections2.permutations(newArrayList(1, 2))); assertPermutationsCount(6, Collections2.permutations(newArrayList(1, 2, 3))); assertPermutationsCount(5040, Collections2.permutations(newArrayList(1, 2, 3, 4, 5, 6, 7))); assertPermutationsCount(40320, Collections2.permutations(newArrayList(1, 2, 3, 4, 5, 6, 7, 8))); } public void testPermutationSetSizeOverflow() { // 13 elements overflow an int assertEquals(Integer.MAX_VALUE, Collections2.permutations(newArrayList( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)).size()); // 21 elements overflow a long assertEquals(Integer.MAX_VALUE, Collections2.orderedPermutations( newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)).size()); assertEquals(Integer.MAX_VALUE, Collections2.orderedPermutations( newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21)).size()); } public void testPermutationSetContains() { List<Integer> list = newArrayList(3, 2, 1); Collection<List<Integer>> permutationSet = Collections2.permutations(list); assertTrue(permutationSet.contains(newArrayList(1, 2, 3))); assertTrue(permutationSet.contains(newArrayList(2, 3, 1))); assertFalse(permutationSet.contains(newArrayList(1, 2))); assertFalse(permutationSet.contains(newArrayList(1, 1, 2, 3))); assertFalse(permutationSet.contains(newArrayList(1, 2, 3, 4))); assertFalse(permutationSet.contains(null)); } private <T> void assertNextPermutation(List<T> expectedPermutation, Iterator<List<T>> permutations) { assertTrue("Expected another permutation, but there was none.", permutations.hasNext()); assertEquals(expectedPermutation, permutations.next()); } private <T> void assertNoMorePermutations( Iterator<List<T>> permutations) { assertFalse("Expected no more permutations, but there was one.", permutations.hasNext()); try { permutations.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException expected) {} } private <T> void assertPermutationsCount(int expected, Collection<List<T>> permutationSet) { assertEquals(expected, permutationSet.size()); Iterator<List<T>> permutations = permutationSet.iterator(); for (int i = 0; i < expected; i++) { assertTrue(permutations.hasNext()); permutations.next(); } assertNoMorePermutations(permutations); } public void testToStringImplWithNullEntries() throws Exception { List<String> list = Lists.newArrayList(); list.add("foo"); list.add(null); assertEquals(list.toString(), Collections2.toStringImpl(list)); } }
Java
/* * Copyright (C) 2008 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.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableMultimap.Builder; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.SampleElements.Unhashables; import com.google.common.collect.testing.UnhashableObject; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Map.Entry; /** * Tests for {@link ImmutableMultimap}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class ImmutableMultimapTest extends TestCase { public void testBuilder_withImmutableEntry() { ImmutableMultimap<String, Integer> multimap = new Builder<String, Integer>() .put(Maps.immutableEntry("one", 1)) .build(); assertEquals(Arrays.asList(1), multimap.get("one")); } public void testBuilder_withImmutableEntryAndNullContents() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(Maps.immutableEntry("one", (Integer) null)); fail(); } catch (NullPointerException expected) { } try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) { } } private static class StringHolder { String string; } public void testBuilder_withMutableEntry() { ImmutableMultimap.Builder<String, Integer> builder = new Builder<String, Integer>(); final StringHolder holder = new StringHolder(); holder.string = "one"; Entry<String, Integer> entry = new AbstractMapEntry<String, Integer>() { @Override public String getKey() { return holder.string; } @Override public Integer getValue() { return 1; } }; builder.put(entry); holder.string = "two"; assertEquals(Arrays.asList(1), builder.build().get("one")); } // TODO: test ImmutableMultimap builder and factory methods public void testCopyOf() { ImmutableSetMultimap<String, String> setMultimap = ImmutableSetMultimap.of("k1", "v1"); ImmutableMultimap<String, String> setMultimapCopy = ImmutableMultimap.copyOf(setMultimap); assertSame("copyOf(ImmutableSetMultimap) should not create a new instance", setMultimap, setMultimapCopy); ImmutableListMultimap<String, String> listMultimap = ImmutableListMultimap.of("k1", "v1"); ImmutableMultimap<String, String> listMultimapCopy = ImmutableMultimap.copyOf(listMultimap); assertSame("copyOf(ImmutableListMultimap) should not create a new instance", listMultimap, listMultimapCopy); } public void testUnhashableSingletonValue() { SampleElements<UnhashableObject> unhashables = new Unhashables(); Multimap<Integer, UnhashableObject> multimap = ImmutableMultimap.of( 0, unhashables.e0); assertEquals(1, multimap.get(0).size()); assertTrue(multimap.get(0).contains(unhashables.e0)); } public void testUnhashableMixedValues() { SampleElements<UnhashableObject> unhashables = new Unhashables(); Multimap<Integer, Object> multimap = ImmutableMultimap.<Integer, Object>of( 0, unhashables.e0, 2, "hey you", 0, unhashables.e1); assertEquals(2, multimap.get(0).size()); assertTrue(multimap.get(0).contains(unhashables.e0)); assertTrue(multimap.get(0).contains(unhashables.e1)); assertTrue(multimap.get(2).contains("hey you")); } public void testEquals() { new EqualsTester() .addEqualityGroup(ImmutableMultimap.of(), ImmutableMultimap.of()) .addEqualityGroup(ImmutableMultimap.of(1, "a"), ImmutableMultimap.of(1, "a")) .addEqualityGroup( ImmutableMultimap.of(1, "a", 2, "b"), ImmutableMultimap.of(2, "b", 1, "a")) .testEquals(); } }
Java
/* * Copyright (C) 2007 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.SortedSet; /** * Unit tests for {@code TreeMultimap} with explicit comparators. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class TreeMultimapExplicitTest extends TestCase { /** * Compare strings lengths, and if the lengths are equal compare the strings. * A {@code null} is less than any non-null value. */ private enum StringLength implements Comparator<String> { COMPARATOR; @Override public int compare(String first, String second) { if (first == second) { return 0; } else if (first == null) { return -1; } else if (second == null) { return 1; } else if (first.length() != second.length()) { return first.length() - second.length(); } else { return first.compareTo(second); } } } /** * Decreasing integer values. A {@code null} comes before any non-null value. */ private static final Comparator<Integer> DECREASING_INT_COMPARATOR = Ordering.<Integer>natural().reverse().nullsFirst(); private SetMultimap<String, Integer> create() { return TreeMultimap.create( StringLength.COMPARATOR, DECREASING_INT_COMPARATOR); } /** * Create and populate a {@code TreeMultimap} with explicit comparators. */ private TreeMultimap<String, Integer> createPopulate() { TreeMultimap<String, Integer> multimap = TreeMultimap.create( StringLength.COMPARATOR, DECREASING_INT_COMPARATOR); multimap.put("google", 2); multimap.put("google", 6); multimap.put(null, 3); multimap.put(null, 1); multimap.put(null, 7); multimap.put("tree", 0); multimap.put("tree", null); return multimap; } /** * Test that a TreeMultimap created from another uses the natural ordering. */ public void testMultimapCreateFromTreeMultimap() { TreeMultimap<String, Integer> tree = TreeMultimap.create( StringLength.COMPARATOR, DECREASING_INT_COMPARATOR); tree.put("google", 2); tree.put("google", 6); tree.put("tree", 0); tree.put("tree", 3); ASSERT.that(tree.keySet()).has().exactly("tree", "google").inOrder(); ASSERT.that(tree.get("google")).has().exactly(6, 2).inOrder(); TreeMultimap<String, Integer> copy = TreeMultimap.create(tree); assertEquals(tree, copy); ASSERT.that(copy.keySet()).has().exactly("google", "tree").inOrder(); ASSERT.that(copy.get("google")).has().exactly(2, 6).inOrder(); assertEquals(Ordering.natural(), copy.keyComparator()); assertEquals(Ordering.natural(), copy.valueComparator()); assertEquals(Ordering.natural(), copy.get("google").comparator()); } public void testToString() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 3); multimap.put("bar", 1); multimap.putAll("foo", Arrays.asList(-1, 2, 4)); multimap.putAll("bar", Arrays.asList(2, 3)); multimap.put("foo", 1); assertEquals("{bar=[3, 2, 1], foo=[4, 3, 2, 1, -1]}", multimap.toString()); } public void testGetComparator() { TreeMultimap<String, Integer> multimap = createPopulate(); assertEquals(StringLength.COMPARATOR, multimap.keyComparator()); assertEquals(DECREASING_INT_COMPARATOR, multimap.valueComparator()); } public void testOrderedGet() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.get(null)).has().exactly(7, 3, 1).inOrder(); ASSERT.that(multimap.get("google")).has().exactly(6, 2).inOrder(); ASSERT.that(multimap.get("tree")).has().exactly(null, 0).inOrder(); } public void testOrderedKeySet() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.keySet()).has().exactly(null, "tree", "google").inOrder(); } public void testOrderedAsMapEntries() { TreeMultimap<String, Integer> multimap = createPopulate(); Iterator<Map.Entry<String, Collection<Integer>>> iterator = multimap.asMap().entrySet().iterator(); Map.Entry<String, Collection<Integer>> entry = iterator.next(); assertEquals(null, entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(7, 3, 1); entry = iterator.next(); assertEquals("tree", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(null, 0); entry = iterator.next(); assertEquals("google", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(6, 2); } public void testOrderedEntries() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.entries()).has().exactly( Maps.immutableEntry((String) null, 7), Maps.immutableEntry((String) null, 3), Maps.immutableEntry((String) null, 1), Maps.immutableEntry("tree", (Integer) null), Maps.immutableEntry("tree", 0), Maps.immutableEntry("google", 6), Maps.immutableEntry("google", 2)).inOrder(); } public void testOrderedValues() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.values()).has().exactly(7, 3, 1, null, 0, 6, 2).inOrder(); } public void testComparator() { TreeMultimap<String, Integer> multimap = createPopulate(); assertEquals(DECREASING_INT_COMPARATOR, multimap.get("foo").comparator()); assertEquals(DECREASING_INT_COMPARATOR, multimap.get("missing").comparator()); } public void testMultimapComparators() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 3); multimap.put("bar", 1); multimap.putAll("foo", Arrays.asList(-1, 2, 4)); multimap.putAll("bar", Arrays.asList(2, 3)); multimap.put("foo", 1); TreeMultimap<String, Integer> copy = TreeMultimap.create(StringLength.COMPARATOR, DECREASING_INT_COMPARATOR); copy.putAll(multimap); assertEquals(multimap, copy); assertEquals(StringLength.COMPARATOR, copy.keyComparator()); assertEquals(DECREASING_INT_COMPARATOR, copy.valueComparator()); } public void testSortedKeySet() { TreeMultimap<String, Integer> multimap = createPopulate(); SortedSet<String> keySet = multimap.keySet(); assertEquals(null, keySet.first()); assertEquals("google", keySet.last()); assertEquals(StringLength.COMPARATOR, keySet.comparator()); assertEquals(Sets.newHashSet(null, "tree"), keySet.headSet("yahoo")); assertEquals(Sets.newHashSet("google"), keySet.tailSet("yahoo")); assertEquals(Sets.newHashSet("tree"), keySet.subSet("ask", "yahoo")); } }
Java
/* * Copyright (C) 2007 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.Arrays; import java.util.List; /** * Unit test for {@code ObjectArrays}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class ObjectArraysTest extends TestCase { public void testNewArray_fromArray_Empty() { String[] in = new String[0]; String[] empty = ObjectArrays.newArray(in, 0); assertEquals(0, empty.length); } public void testNewArray_fromArray_Nonempty() { String[] array = ObjectArrays.newArray(new String[0], 2); assertEquals(String[].class, array.getClass()); assertEquals(2, array.length); assertNull(array[0]); } public void testNewArray_fromArray_OfArray() { String[][] array = ObjectArrays.newArray(new String[0][0], 1); assertEquals(String[][].class, array.getClass()); assertEquals(1, array.length); assertNull(array[0]); } public void testToArrayImpl1() { doTestToArrayImpl1(Lists.<Integer>newArrayList()); doTestToArrayImpl1(Lists.newArrayList(1)); doTestToArrayImpl1(Lists.newArrayList(1, null, 3)); } private void doTestToArrayImpl1(List<Integer> list) { Object[] reference = list.toArray(); Object[] target = ObjectArrays.toArrayImpl(list); assertEquals(reference.getClass(), target.getClass()); assertTrue(Arrays.equals(reference, target)); } public void testToArrayImpl2() { doTestToArrayImpl2(Lists.<Integer>newArrayList(), new Integer[0], false); doTestToArrayImpl2(Lists.<Integer>newArrayList(), new Integer[1], true); doTestToArrayImpl2(Lists.newArrayList(1), new Integer[0], false); doTestToArrayImpl2(Lists.newArrayList(1), new Integer[1], true); doTestToArrayImpl2(Lists.newArrayList(1), new Integer[] { 2, 3 }, true); doTestToArrayImpl2(Lists.newArrayList(1, null, 3), new Integer[0], false); doTestToArrayImpl2(Lists.newArrayList(1, null, 3), new Integer[2], false); doTestToArrayImpl2(Lists.newArrayList(1, null, 3), new Integer[3], true); } private void doTestToArrayImpl2(List<Integer> list, Integer[] array1, boolean expectModify) { Integer[] starting = ObjectArrays.arraysCopyOf(array1, array1.length); Integer[] array2 = ObjectArrays.arraysCopyOf(array1, array1.length); Object[] reference = list.toArray(array1); Object[] target = ObjectArrays.toArrayImpl(list, array2); assertEquals(reference.getClass(), target.getClass()); assertTrue(Arrays.equals(reference, target)); assertTrue(Arrays.equals(reference, target)); Object[] expectedArray1 = expectModify ? reference : starting; Object[] expectedArray2 = expectModify ? target : starting; assertTrue(Arrays.equals(expectedArray1, array1)); assertTrue(Arrays.equals(expectedArray2, array2)); } public void testPrependZeroElements() { String[] result = ObjectArrays.concat("foo", new String[] {}); ASSERT.that(result).has().item("foo"); } public void testPrependOneElement() { String[] result = ObjectArrays.concat("foo", new String[] { "bar" }); ASSERT.that(result).has().exactly("foo", "bar").inOrder(); } public void testPrependTwoElements() { String[] result = ObjectArrays.concat("foo", new String[] { "bar", "baz" }); ASSERT.that(result).has().exactly("foo", "bar", "baz").inOrder(); } public void testAppendZeroElements() { String[] result = ObjectArrays.concat(new String[] {}, "foo"); ASSERT.that(result).has().item("foo"); } public void testAppendOneElement() { String[] result = ObjectArrays.concat(new String[] { "foo" }, "bar"); ASSERT.that(result).has().exactly("foo", "bar").inOrder(); } public void testAppendTwoElements() { String[] result = ObjectArrays.concat(new String[] { "foo", "bar" }, "baz"); ASSERT.that(result).has().exactly("foo", "bar", "baz").inOrder(); } public void testEmptyArrayToEmpty() { doTestNewArrayEquals(new Object[0], 0); } public void testEmptyArrayToNonEmpty() { checkArrayEquals(new Long[5], ObjectArrays.newArray(new Long[0], 5)); } public void testNonEmptyToShorter() { checkArrayEquals(new String[9], ObjectArrays.newArray(new String[10], 9)); } public void testNonEmptyToSameLength() { doTestNewArrayEquals(new String[10], 10); } public void testNonEmptyToLonger() { checkArrayEquals(new String[10], ObjectArrays.newArray(new String[] { "a", "b", "c", "d", "e" }, 10)); } private static void checkArrayEquals(Object[] expected, Object[] actual) { assertTrue("expected(" + expected.getClass() + "): " + Arrays.toString(expected) + " actual(" + actual.getClass() + "): " + Arrays.toString(actual), arrayEquals(expected, actual)); } private static boolean arrayEquals(Object[] array1, Object[] array2) { assertSame(array1.getClass(), array2.getClass()); return Arrays.equals(array1, array2); } private static void doTestNewArrayEquals(Object[] expected, int length) { checkArrayEquals(expected, ObjectArrays.newArray(expected, length)); } }
Java
/* * Copyright (C) 2007 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.collect; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; /** * Unit tests for {@link HashMultimap}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class HashMultimapTest extends TestCase { /* * The behavior of toString() is tested by TreeMultimap, which shares a * lot of code with HashMultimap and has deterministic iteration order. */ public void testCreate() { HashMultimap<String, Integer> multimap = HashMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("foo", 3); assertEquals(ImmutableSet.of(1, 3), multimap.get("foo")); assertEquals(2, multimap.expectedValuesPerKey); } public void testCreateFromMultimap() { HashMultimap<String, Integer> multimap = HashMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("foo", 3); HashMultimap<String, Integer> copy = HashMultimap.create(multimap); assertEquals(multimap, copy); assertEquals(2, copy.expectedValuesPerKey); } public void testCreateFromSizes() { HashMultimap<String, Integer> multimap = HashMultimap.create(20, 15); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("foo", 3); assertEquals(ImmutableSet.of(1, 3), multimap.get("foo")); assertEquals(15, multimap.expectedValuesPerKey); } public void testCreateFromIllegalSizes() { try { HashMultimap.create(-20, 15); fail(); } catch (IllegalArgumentException expected) {} try { HashMultimap.create(20, -15); fail(); } catch (IllegalArgumentException expected) {} } public void testEmptyMultimapsEqual() { Multimap<String, Integer> setMultimap = HashMultimap.create(); Multimap<String, Integer> listMultimap = ArrayListMultimap.create(); assertTrue(setMultimap.equals(listMultimap)); assertTrue(listMultimap.equals(setMultimap)); } }
Java
/* * Copyright (C) 2011 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.collect; import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import junit.framework.TestCase; import java.util.Arrays; import java.util.List; /** * Tests for {@code GeneralRange}. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class GeneralRangeTest extends TestCase { private static final Ordering<Integer> ORDERING = Ordering.natural().nullsFirst(); private static final List<Integer> IN_ORDER_VALUES = Arrays.asList(null, 1, 2, 3, 4, 5); public void testCreateEmptyRangeFails() { for (BoundType lboundType : BoundType.values()) { for (BoundType uboundType : BoundType.values()) { try { GeneralRange.range(ORDERING, 4, lboundType, 2, uboundType); fail("Expected IAE"); } catch (IllegalArgumentException expected) {} } } } public void testCreateEmptyRangeOpenOpenFails() { for (Integer i : IN_ORDER_VALUES) { try { GeneralRange.range(ORDERING, i, OPEN, i, OPEN); fail("Expected IAE"); } catch (IllegalArgumentException expected) {} } } public void testCreateEmptyRangeClosedOpenSucceeds() { for (Integer i : IN_ORDER_VALUES) { GeneralRange<Integer> range = GeneralRange.range(ORDERING, i, CLOSED, i, OPEN); for (Integer j : IN_ORDER_VALUES) { assertFalse(range.contains(j)); } } } public void testCreateEmptyRangeOpenClosedSucceeds() { for (Integer i : IN_ORDER_VALUES) { GeneralRange<Integer> range = GeneralRange.range(ORDERING, i, OPEN, i, CLOSED); for (Integer j : IN_ORDER_VALUES) { assertFalse(range.contains(j)); } } } public void testCreateSingletonRangeSucceeds() { for (Integer i : IN_ORDER_VALUES) { GeneralRange<Integer> range = GeneralRange.range(ORDERING, i, CLOSED, i, CLOSED); for (Integer j : IN_ORDER_VALUES) { assertEquals(Objects.equal(i, j), range.contains(j)); } } } public void testSingletonRange() { GeneralRange<Integer> range = GeneralRange.range(ORDERING, 3, CLOSED, 3, CLOSED); for (Integer i : IN_ORDER_VALUES) { assertEquals(ORDERING.compare(i, 3) == 0, range.contains(i)); } } public void testLowerRange() { for (BoundType lBoundType : BoundType.values()) { GeneralRange<Integer> range = GeneralRange.downTo(ORDERING, 3, lBoundType); for (Integer i : IN_ORDER_VALUES) { assertEquals(ORDERING.compare(i, 3) > 0 || (ORDERING.compare(i, 3) == 0 && lBoundType == CLOSED), range.contains(i)); assertEquals(ORDERING.compare(i, 3) < 0 || (ORDERING.compare(i, 3) == 0 && lBoundType == OPEN), range.tooLow(i)); assertFalse(range.tooHigh(i)); } } } public void testUpperRange() { for (BoundType lBoundType : BoundType.values()) { GeneralRange<Integer> range = GeneralRange.upTo(ORDERING, 3, lBoundType); for (Integer i : IN_ORDER_VALUES) { assertEquals(ORDERING.compare(i, 3) < 0 || (ORDERING.compare(i, 3) == 0 && lBoundType == CLOSED), range.contains(i)); assertEquals(ORDERING.compare(i, 3) > 0 || (ORDERING.compare(i, 3) == 0 && lBoundType == OPEN), range.tooHigh(i)); assertFalse(range.tooLow(i)); } } } public void testDoublyBoundedAgainstRange() { for (BoundType lboundType : BoundType.values()) { for (BoundType uboundType : BoundType.values()) { Range<Integer> range = Range.range(2, lboundType, 4, uboundType); GeneralRange<Integer> gRange = GeneralRange.range(ORDERING, 2, lboundType, 4, uboundType); for (Integer i : IN_ORDER_VALUES) { assertEquals(i != null && range.contains(i), gRange.contains(i)); } } } } public void testIntersectAgainstMatchingEndpointsRange() { GeneralRange<Integer> range = GeneralRange.range(ORDERING, 2, CLOSED, 4, OPEN); assertEquals(GeneralRange.range(ORDERING, 2, OPEN, 4, OPEN), range.intersect(GeneralRange.range(ORDERING, 2, OPEN, 4, CLOSED))); } public void testIntersectAgainstBiggerRange() { GeneralRange<Integer> range = GeneralRange.range(ORDERING, 2, CLOSED, 4, OPEN); assertEquals(GeneralRange.range(ORDERING, 2, CLOSED, 4, OPEN), range.intersect(GeneralRange.range(ORDERING, null, OPEN, 5, CLOSED))); assertEquals(GeneralRange.range(ORDERING, 2, OPEN, 4, OPEN), range.intersect(GeneralRange.range(ORDERING, 2, OPEN, 5, CLOSED))); assertEquals(GeneralRange.range(ORDERING, 2, CLOSED, 4, OPEN), range.intersect(GeneralRange.range(ORDERING, 1, OPEN, 4, OPEN))); } public void testIntersectAgainstSmallerRange() { GeneralRange<Integer> range = GeneralRange.range(ORDERING, 2, OPEN, 4, OPEN); assertEquals(GeneralRange.range(ORDERING, 3, CLOSED, 4, OPEN), range.intersect(GeneralRange.range(ORDERING, 3, CLOSED, 4, CLOSED))); } public void testIntersectOverlappingRange() { GeneralRange<Integer> range = GeneralRange.range(ORDERING, 2, OPEN, 4, CLOSED); assertEquals(GeneralRange.range(ORDERING, 3, CLOSED, 4, CLOSED), range.intersect(GeneralRange.range(ORDERING, 3, CLOSED, 5, CLOSED))); assertEquals(GeneralRange.range(ORDERING, 2, OPEN, 3, OPEN), range.intersect(GeneralRange.range(ORDERING, 1, OPEN, 3, OPEN))); } public void testIntersectNonOverlappingRange() { GeneralRange<Integer> range = GeneralRange.range(ORDERING, 2, OPEN, 4, CLOSED); assertTrue(range.intersect(GeneralRange.range(ORDERING, 5, CLOSED, 6, CLOSED)).isEmpty()); assertTrue(range.intersect(GeneralRange.range(ORDERING, 1, OPEN, 2, OPEN)).isEmpty()); } public void testFromRangeAll() { assertEquals(GeneralRange.all(Ordering.natural()), GeneralRange.from(Range.all())); } public void testFromRangeOneEnd() { for (BoundType endpointType : BoundType.values()) { assertEquals(GeneralRange.upTo(Ordering.natural(), 3, endpointType), GeneralRange.from(Range.upTo(3, endpointType))); assertEquals(GeneralRange.downTo(Ordering.natural(), 3, endpointType), GeneralRange.from(Range.downTo(3, endpointType))); } } public void testFromRangeTwoEnds() { for (BoundType lowerType : BoundType.values()) { for (BoundType upperType : BoundType.values()) { assertEquals(GeneralRange.range(Ordering.natural(), 3, lowerType, 4, upperType), GeneralRange.from(Range.range(3, lowerType, 4, upperType))); } } } public void testReverse() { assertEquals(GeneralRange.all(ORDERING.reverse()), GeneralRange.all(ORDERING).reverse()); assertEquals(GeneralRange.downTo(ORDERING.reverse(), 3, CLOSED), GeneralRange.upTo(ORDERING, 3, CLOSED).reverse()); assertEquals(GeneralRange.upTo(ORDERING.reverse(), 3, OPEN), GeneralRange.downTo(ORDERING, 3, OPEN).reverse()); assertEquals(GeneralRange.range(ORDERING.reverse(), 5, OPEN, 3, CLOSED), GeneralRange.range(ORDERING, 3, CLOSED, 5, OPEN).reverse()); } }
Java
/* * Copyright (C) 2007 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.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.testing.Helpers.nefariousMapEntry; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Predicates; import com.google.common.base.Supplier; import com.google.common.collect.Maps.EntryTransformer; import com.google.common.collect.testing.IteratorTester; import com.google.common.collect.testing.google.UnmodifiableCollectionTests; import junit.framework.TestCase; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nullable; /** * Unit test for {@code Multimaps}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class MultimapsTest extends TestCase { private static final Comparator<Integer> INT_COMPARATOR = Ordering.<Integer>natural().reverse().nullsFirst(); private static final EntryTransformer<Object, Object, Object> ALWAYS_NULL = new EntryTransformer<Object, Object, Object>() { @Override public Object transformEntry(Object k, Object v1) { return null; } }; @SuppressWarnings("deprecation") public void testUnmodifiableListMultimapShortCircuit() { ListMultimap<String, Integer> mod = ArrayListMultimap.create(); ListMultimap<String, Integer> unmod = Multimaps.unmodifiableListMultimap(mod); assertNotSame(mod, unmod); assertSame(unmod, Multimaps.unmodifiableListMultimap(unmod)); ImmutableListMultimap<String, Integer> immutable = ImmutableListMultimap.of("a", 1, "b", 2, "a", 3); assertSame(immutable, Multimaps.unmodifiableListMultimap(immutable)); assertSame( immutable, Multimaps.unmodifiableListMultimap((ListMultimap<String, Integer>) immutable)); } @SuppressWarnings("deprecation") public void testUnmodifiableSetMultimapShortCircuit() { SetMultimap<String, Integer> mod = HashMultimap.create(); SetMultimap<String, Integer> unmod = Multimaps.unmodifiableSetMultimap(mod); assertNotSame(mod, unmod); assertSame(unmod, Multimaps.unmodifiableSetMultimap(unmod)); ImmutableSetMultimap<String, Integer> immutable = ImmutableSetMultimap.of("a", 1, "b", 2, "a", 3); assertSame(immutable, Multimaps.unmodifiableSetMultimap(immutable)); assertSame( immutable, Multimaps.unmodifiableSetMultimap((SetMultimap<String, Integer>) immutable)); } @SuppressWarnings("deprecation") public void testUnmodifiableMultimapShortCircuit() { Multimap<String, Integer> mod = HashMultimap.create(); Multimap<String, Integer> unmod = Multimaps.unmodifiableMultimap(mod); assertNotSame(mod, unmod); assertSame(unmod, Multimaps.unmodifiableMultimap(unmod)); ImmutableMultimap<String, Integer> immutable = ImmutableMultimap.of("a", 1, "b", 2, "a", 3); assertSame(immutable, Multimaps.unmodifiableMultimap(immutable)); assertSame(immutable, Multimaps.unmodifiableMultimap((Multimap<String, Integer>) immutable)); } public void testUnmodifiableArrayListMultimapRandomAccess() { ListMultimap<String, Integer> delegate = ArrayListMultimap.create(); delegate.put("foo", 1); delegate.put("foo", 3); ListMultimap<String, Integer> multimap = Multimaps.unmodifiableListMultimap(delegate); assertTrue(multimap.get("foo") instanceof RandomAccess); assertTrue(multimap.get("bar") instanceof RandomAccess); } public void testUnmodifiableLinkedListMultimapRandomAccess() { ListMultimap<String, Integer> delegate = LinkedListMultimap.create(); delegate.put("foo", 1); delegate.put("foo", 3); ListMultimap<String, Integer> multimap = Multimaps.unmodifiableListMultimap(delegate); assertFalse(multimap.get("foo") instanceof RandomAccess); assertFalse(multimap.get("bar") instanceof RandomAccess); } public void testUnmodifiableMultimapIsView() { Multimap<String, Integer> mod = HashMultimap.create(); Multimap<String, Integer> unmod = Multimaps.unmodifiableMultimap(mod); assertEquals(mod, unmod); mod.put("foo", 1); assertTrue(unmod.containsEntry("foo", 1)); assertEquals(mod, unmod); } @SuppressWarnings("unchecked") public void testUnmodifiableMultimapEntries() { Multimap<String, Integer> mod = HashMultimap.create(); Multimap<String, Integer> unmod = Multimaps.unmodifiableMultimap(mod); mod.put("foo", 1); Entry<String, Integer> entry = unmod.entries().iterator().next(); try { entry.setValue(2); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} entry = (Entry<String, Integer>) unmod.entries().toArray()[0]; try { entry.setValue(2); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} Entry<String, Integer>[] array = (Entry<String, Integer>[]) new Entry<?, ?>[2]; assertSame(array, unmod.entries().toArray(array)); try { array[0].setValue(2); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} assertFalse(unmod.entries().contains(nefariousMapEntry("pwnd", 2))); assertFalse(unmod.keys().contains("pwnd")); } /** * The supplied multimap will be mutated and an unmodifiable instance used * in its stead. The multimap must support null keys and values. */ private static void checkUnmodifiableMultimap( Multimap<String, Integer> multimap, boolean permitsDuplicates) { checkUnmodifiableMultimap(multimap, permitsDuplicates, null, null); } /** * The supplied multimap will be mutated and an unmodifiable instance used * in its stead. If the multimap does not support null keys or values, * alternatives may be specified for tests involving nulls. */ private static void checkUnmodifiableMultimap( Multimap<String, Integer> multimap, boolean permitsDuplicates, @Nullable String nullKey, @Nullable Integer nullValue) { Multimap<String, Integer> unmodifiable = prepareUnmodifiableTests(multimap, permitsDuplicates, nullKey, nullValue); UnmodifiableCollectionTests.assertMultimapIsUnmodifiable( unmodifiable, "test", 123); assertUnmodifiableIterableInTandem( unmodifiable.keys(), multimap.keys()); assertUnmodifiableIterableInTandem( unmodifiable.keySet(), multimap.keySet()); assertUnmodifiableIterableInTandem( unmodifiable.entries(), multimap.entries()); assertUnmodifiableIterableInTandem( unmodifiable.asMap().entrySet(), multimap.asMap().entrySet()); assertEquals(multimap.toString(), unmodifiable.toString()); assertEquals(multimap.hashCode(), unmodifiable.hashCode()); assertEquals(multimap, unmodifiable); ASSERT.that(unmodifiable.asMap().get("bar")).has().exactly(5, -1); assertNull(unmodifiable.asMap().get("missing")); assertFalse(unmodifiable.entries() instanceof Serializable); } /** * Prepares the multimap for unmodifiable tests, returning an unmodifiable view * of the map. */ private static Multimap<String, Integer> prepareUnmodifiableTests( Multimap<String, Integer> multimap, boolean permitsDuplicates, @Nullable String nullKey, @Nullable Integer nullValue) { multimap.clear(); multimap.put("foo", 1); multimap.put("foo", 2); multimap.put("foo", 3); multimap.put("bar", 5); multimap.put("bar", -1); multimap.put(nullKey, nullValue); multimap.put("foo", nullValue); multimap.put(nullKey, 5); multimap.put("foo", 2); if (permitsDuplicates) { assertEquals(9, multimap.size()); } else { assertEquals(8, multimap.size()); } Multimap<String, Integer> unmodifiable; if (multimap instanceof SortedSetMultimap) { unmodifiable = Multimaps.unmodifiableSortedSetMultimap( (SortedSetMultimap<String, Integer>) multimap); } else if (multimap instanceof SetMultimap) { unmodifiable = Multimaps.unmodifiableSetMultimap( (SetMultimap<String, Integer>) multimap); } else if (multimap instanceof ListMultimap) { unmodifiable = Multimaps.unmodifiableListMultimap( (ListMultimap<String, Integer>) multimap); } else { unmodifiable = Multimaps.unmodifiableMultimap(multimap); } return unmodifiable; } private static <T> void assertUnmodifiableIterableInTandem( Iterable<T> unmodifiable, Iterable<T> modifiable) { UnmodifiableCollectionTests.assertIteratorIsUnmodifiable( unmodifiable.iterator()); UnmodifiableCollectionTests.assertIteratorsInOrder( unmodifiable.iterator(), modifiable.iterator()); } public void testInvertFrom() { ImmutableMultimap<Integer, String> empty = ImmutableMultimap.of(); // typical usage example - sad that ArrayListMultimap.create() won't work Multimap<String, Integer> multimap = Multimaps.invertFrom(empty, ArrayListMultimap.<String, Integer>create()); assertTrue(multimap.isEmpty()); ImmutableMultimap<Integer, String> single = new ImmutableMultimap.Builder<Integer, String>() .put(1, "one") .put(2, "two") .build(); // copy into existing multimap assertSame(multimap, Multimaps.invertFrom(single, multimap)); ImmutableMultimap<String, Integer> expected = new ImmutableMultimap.Builder<String, Integer>() .put("one", 1) .put("two", 2) .build(); assertEquals(expected, multimap); } public void testAsMap_multimap() { Multimap<String, Integer> multimap = Multimaps.newMultimap( new HashMap<String, Collection<Integer>>(), new QueueSupplier()); Map<String, Collection<Integer>> map = Multimaps.asMap(multimap); assertSame(multimap.asMap(), map); } public void testAsMap_listMultimap() { ListMultimap<String, Integer> listMultimap = ArrayListMultimap.create(); Map<String, List<Integer>> map = Multimaps.asMap(listMultimap); assertSame(listMultimap.asMap(), map); } public void testAsMap_setMultimap() { SetMultimap<String, Integer> setMultimap = LinkedHashMultimap.create(); Map<String, Set<Integer>> map = Multimaps.asMap(setMultimap); assertSame(setMultimap.asMap(), map); } public void testAsMap_sortedSetMultimap() { SortedSetMultimap<String, Integer> sortedSetMultimap = TreeMultimap.create(); Map<String, SortedSet<Integer>> map = Multimaps.asMap(sortedSetMultimap); assertSame(sortedSetMultimap.asMap(), map); } public void testForMap() { Map<String, Integer> map = Maps.newHashMap(); map.put("foo", 1); map.put("bar", 2); Multimap<String, Integer> multimap = HashMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); Multimap<String, Integer> multimapView = Multimaps.forMap(map); assertTrue(multimap.equals(multimapView)); assertTrue(multimapView.equals(multimap)); assertTrue(multimapView.equals(multimapView)); assertFalse(multimapView.equals(map)); Multimap<String, Integer> multimap2 = HashMultimap.create(); multimap2.put("foo", 1); assertFalse(multimapView.equals(multimap2)); multimap2.put("bar", 1); assertFalse(multimapView.equals(multimap2)); ListMultimap<String, Integer> listMultimap = new ImmutableListMultimap.Builder<String, Integer>() .put("foo", 1).put("bar", 2).build(); assertFalse("SetMultimap equals ListMultimap", multimapView.equals(listMultimap)); assertEquals(multimap.toString(), multimapView.toString()); assertEquals(multimap.hashCode(), multimapView.hashCode()); assertEquals(multimap.size(), multimapView.size()); assertTrue(multimapView.containsKey("foo")); assertTrue(multimapView.containsValue(1)); assertTrue(multimapView.containsEntry("bar", 2)); assertEquals(Collections.singleton(1), multimapView.get("foo")); assertEquals(Collections.singleton(2), multimapView.get("bar")); try { multimapView.put("baz", 3); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { multimapView.putAll("baz", Collections.singleton(3)); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { multimapView.putAll(multimap); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { multimapView.replaceValues("foo", Collections.<Integer>emptySet()); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} multimapView.remove("bar", 2); assertFalse(multimapView.containsKey("bar")); assertFalse(map.containsKey("bar")); assertEquals(map.keySet(), multimapView.keySet()); assertEquals(map.keySet(), multimapView.keys().elementSet()); ASSERT.that(multimapView.keys()).has().item("foo"); ASSERT.that(multimapView.values()).has().item(1); ASSERT.that(multimapView.entries()).has().item( Maps.immutableEntry("foo", 1)); ASSERT.that(multimapView.asMap().entrySet()).has().item( Maps.immutableEntry( "foo", (Collection<Integer>) Collections.singleton(1))); multimapView.clear(); assertFalse(multimapView.containsKey("foo")); assertFalse(map.containsKey("foo")); assertTrue(map.isEmpty()); assertTrue(multimapView.isEmpty()); multimap.clear(); assertEquals(multimap.toString(), multimapView.toString()); assertEquals(multimap.hashCode(), multimapView.hashCode()); assertEquals(multimap.size(), multimapView.size()); assertEquals(multimapView, ArrayListMultimap.create()); } public void testForMapRemoveAll() { Map<String, Integer> map = Maps.newHashMap(); map.put("foo", 1); map.put("bar", 2); map.put("cow", 3); Multimap<String, Integer> multimap = Multimaps.forMap(map); assertEquals(3, multimap.size()); assertEquals(Collections.emptySet(), multimap.removeAll("dog")); assertEquals(3, multimap.size()); assertTrue(multimap.containsKey("bar")); assertEquals(Collections.singleton(2), multimap.removeAll("bar")); assertEquals(2, multimap.size()); assertFalse(multimap.containsKey("bar")); } public void testForMapAsMap() { Map<String, Integer> map = Maps.newHashMap(); map.put("foo", 1); map.put("bar", 2); Map<String, Collection<Integer>> asMap = Multimaps.forMap(map).asMap(); assertEquals(Collections.singleton(1), asMap.get("foo")); assertNull(asMap.get("cow")); assertTrue(asMap.containsKey("foo")); assertFalse(asMap.containsKey("cow")); Set<Entry<String, Collection<Integer>>> entries = asMap.entrySet(); assertFalse(entries.contains(4.5)); assertFalse(entries.remove(4.5)); assertFalse(entries.contains(Maps.immutableEntry("foo", Collections.singletonList(1)))); assertFalse(entries.remove(Maps.immutableEntry("foo", Collections.singletonList(1)))); assertFalse(entries.contains(Maps.immutableEntry("foo", Sets.newLinkedHashSet(asList(1, 2))))); assertFalse(entries.remove(Maps.immutableEntry("foo", Sets.newLinkedHashSet(asList(1, 2))))); assertFalse(entries.contains(Maps.immutableEntry("foo", Collections.singleton(2)))); assertFalse(entries.remove(Maps.immutableEntry("foo", Collections.singleton(2)))); assertTrue(map.containsKey("foo")); assertTrue(entries.contains(Maps.immutableEntry("foo", Collections.singleton(1)))); assertTrue(entries.remove(Maps.immutableEntry("foo", Collections.singleton(1)))); assertFalse(map.containsKey("foo")); } public void testForMapGetIteration() { IteratorTester<Integer> tester = new IteratorTester<Integer>(4, MODIFIABLE, newHashSet(1), IteratorTester.KnownOrder.KNOWN_ORDER) { private Multimap<String, Integer> multimap; @Override protected Iterator<Integer> newTargetIterator() { Map<String, Integer> map = Maps.newHashMap(); map.put("foo", 1); map.put("bar", 2); multimap = Multimaps.forMap(map); return multimap.get("foo").iterator(); } @Override protected void verify(List<Integer> elements) { assertEquals(newHashSet(elements), multimap.get("foo")); } }; tester.ignoreSunJavaBug6529795(); tester.test(); } private enum Color {BLUE, RED, YELLOW, GREEN} private abstract static class CountingSupplier<E> implements Supplier<E>, Serializable { int count; abstract E getImpl(); @Override public E get() { count++; return getImpl(); } } private static class QueueSupplier extends CountingSupplier<Queue<Integer>> { @Override public Queue<Integer> getImpl() { return new LinkedList<Integer>(); } private static final long serialVersionUID = 0; } public void testNewMultimapWithCollectionRejectingNegativeElements() { CountingSupplier<Set<Integer>> factory = new SetSupplier() { @Override public Set<Integer> getImpl() { final Set<Integer> backing = super.getImpl(); return new ForwardingSet<Integer>() { @Override protected Set<Integer> delegate() { return backing; } @Override public boolean add(Integer element) { checkArgument(element >= 0); return super.add(element); } @Override public boolean addAll(Collection<? extends Integer> collection) { return standardAddAll(collection); } }; } }; Map<Color, Collection<Integer>> map = Maps.newEnumMap(Color.class); Multimap<Color, Integer> multimap = Multimaps.newMultimap(map, factory); try { multimap.put(Color.BLUE, -1); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } multimap.put(Color.RED, 1); multimap.put(Color.BLUE, 2); try { multimap.put(Color.GREEN, -1); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } ASSERT.that(multimap.entries()).has().exactly( Maps.immutableEntry(Color.RED, 1), Maps.immutableEntry(Color.BLUE, 2)); } public void testNewMultimap() { // The ubiquitous EnumArrayBlockingQueueMultimap CountingSupplier<Queue<Integer>> factory = new QueueSupplier(); Map<Color, Collection<Integer>> map = Maps.newEnumMap(Color.class); Multimap<Color, Integer> multimap = Multimaps.newMultimap(map, factory); assertEquals(0, factory.count); multimap.putAll(Color.BLUE, asList(3, 1, 4)); assertEquals(1, factory.count); multimap.putAll(Color.RED, asList(2, 7, 1, 8)); assertEquals(2, factory.count); assertEquals("[3, 1, 4]", multimap.get(Color.BLUE).toString()); Multimap<Color, Integer> ummodifiable = Multimaps.unmodifiableMultimap(multimap); assertEquals("[3, 1, 4]", ummodifiable.get(Color.BLUE).toString()); Collection<Integer> collection = multimap.get(Color.BLUE); assertEquals(collection, collection); assertFalse(multimap.keySet() instanceof SortedSet); assertFalse(multimap.asMap() instanceof SortedMap); } private static class ListSupplier extends CountingSupplier<LinkedList<Integer>> { @Override public LinkedList<Integer> getImpl() { return new LinkedList<Integer>(); } private static final long serialVersionUID = 0; } public void testNewListMultimap() { CountingSupplier<LinkedList<Integer>> factory = new ListSupplier(); Map<Color, Collection<Integer>> map = Maps.newTreeMap(); ListMultimap<Color, Integer> multimap = Multimaps.newListMultimap(map, factory); assertEquals(0, factory.count); multimap.putAll(Color.BLUE, asList(3, 1, 4, 1)); assertEquals(1, factory.count); multimap.putAll(Color.RED, asList(2, 7, 1, 8)); assertEquals(2, factory.count); assertEquals("{BLUE=[3, 1, 4, 1], RED=[2, 7, 1, 8]}", multimap.toString()); assertFalse(multimap.get(Color.BLUE) instanceof RandomAccess); assertTrue(multimap.keySet() instanceof SortedSet); assertTrue(multimap.asMap() instanceof SortedMap); } private static class SetSupplier extends CountingSupplier<Set<Integer>> { @Override public Set<Integer> getImpl() { return new HashSet<Integer>(4); } private static final long serialVersionUID = 0; } public void testNewSetMultimap() { CountingSupplier<Set<Integer>> factory = new SetSupplier(); Map<Color, Collection<Integer>> map = Maps.newHashMap(); SetMultimap<Color, Integer> multimap = Multimaps.newSetMultimap(map, factory); assertEquals(0, factory.count); multimap.putAll(Color.BLUE, asList(3, 1, 4)); assertEquals(1, factory.count); multimap.putAll(Color.RED, asList(2, 7, 1, 8)); assertEquals(2, factory.count); assertEquals(Sets.newHashSet(4, 3, 1), multimap.get(Color.BLUE)); } private static class SortedSetSupplier extends CountingSupplier<TreeSet<Integer>> { @Override public TreeSet<Integer> getImpl() { return Sets.newTreeSet(INT_COMPARATOR); } private static final long serialVersionUID = 0; } public void testNewSortedSetMultimap() { CountingSupplier<TreeSet<Integer>> factory = new SortedSetSupplier(); Map<Color, Collection<Integer>> map = Maps.newEnumMap(Color.class); SortedSetMultimap<Color, Integer> multimap = Multimaps.newSortedSetMultimap(map, factory); // newSortedSetMultimap calls the factory once to determine the comparator. assertEquals(1, factory.count); multimap.putAll(Color.BLUE, asList(3, 1, 4)); assertEquals(2, factory.count); multimap.putAll(Color.RED, asList(2, 7, 1, 8)); assertEquals(3, factory.count); assertEquals("[4, 3, 1]", multimap.get(Color.BLUE).toString()); assertEquals(INT_COMPARATOR, multimap.valueComparator()); } public void testIndex() { final Multimap<String, Object> stringToObject = new ImmutableMultimap.Builder<String, Object>() .put("1", 1) .put("1", 1L) .put("1", "1") .put("2", 2) .put("2", 2L) .build(); ImmutableMultimap<String, Object> outputMap = Multimaps.index(stringToObject.values(), Functions.toStringFunction()); assertEquals(stringToObject, outputMap); } public void testIndexIterator() { final Multimap<String, Object> stringToObject = new ImmutableMultimap.Builder<String, Object>() .put("1", 1) .put("1", 1L) .put("1", "1") .put("2", 2) .put("2", 2L) .build(); ImmutableMultimap<String, Object> outputMap = Multimaps.index(stringToObject.values().iterator(), Functions.toStringFunction()); assertEquals(stringToObject, outputMap); } public void testIndex_ordering() { final Multimap<Integer, String> expectedIndex = new ImmutableListMultimap.Builder<Integer, String>() .put(4, "Inky") .put(6, "Blinky") .put(5, "Pinky") .put(5, "Pinky") .put(5, "Clyde") .build(); final List<String> badGuys = Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde"); final Function<String, Integer> stringLengthFunction = new Function<String, Integer>() { @Override public Integer apply(String input) { return input.length(); } }; Multimap<Integer, String> index = Multimaps.index(badGuys, stringLengthFunction); assertEquals(expectedIndex, index); } public void testIndex_nullValue() { List<Integer> values = Arrays.asList(1, null); try { Multimaps.index(values, Functions.identity()); fail(); } catch (NullPointerException e) {} } public void testIndex_nullKey() { List<Integer> values = Arrays.asList(1, 2); try { Multimaps.index(values, Functions.constant(null)); fail(); } catch (NullPointerException e) {} } public <K, V> void testSynchronizedMultimapSampleCodeCompilation() { K key = null; Multimap<K, V> multimap = Multimaps.synchronizedMultimap( HashMultimap.<K, V>create()); Collection<V> values = multimap.get(key); // Needn't be in synchronized block synchronized (multimap) { // Synchronizing on multimap, not values! Iterator<V> i = values.iterator(); // Must be in synchronized block while (i.hasNext()) { foo(i.next()); } } } private static void foo(Object o) {} public void testFilteredKeysSetMultimapReplaceValues() { SetMultimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("baz", 3); multimap.put("bar", 4); SetMultimap<String, Integer> filtered = Multimaps.filterKeys( multimap, Predicates.in(ImmutableSet.of("foo", "bar"))); assertEquals( ImmutableSet.of(), filtered.replaceValues("baz", ImmutableSet.<Integer>of())); try { filtered.replaceValues("baz", ImmutableSet.of(5)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testFilteredKeysSetMultimapGetBadValue() { SetMultimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("baz", 3); multimap.put("bar", 4); SetMultimap<String, Integer> filtered = Multimaps.filterKeys( multimap, Predicates.in(ImmutableSet.of("foo", "bar"))); Set<Integer> bazSet = filtered.get("baz"); ASSERT.that(bazSet).isEmpty(); try { bazSet.add(5); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { bazSet.addAll(ImmutableSet.of(6, 7)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testFilteredKeysListMultimapGetBadValue() { ListMultimap<String, Integer> multimap = ArrayListMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("baz", 3); multimap.put("bar", 4); ListMultimap<String, Integer> filtered = Multimaps.filterKeys( multimap, Predicates.in(ImmutableSet.of("foo", "bar"))); List<Integer> bazList = filtered.get("baz"); ASSERT.that(bazList).isEmpty(); try { bazList.add(5); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { bazList.add(0, 6); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { bazList.addAll(ImmutableList.of(7, 8)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { bazList.addAll(0, ImmutableList.of(9, 10)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } }
Java
/* * Copyright (C) 2009 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; /** * Tests common methods in {@link ImmutableTable} * * @author Gregory Kick */ @GwtCompatible(emulated = true) public class ImmutableTableTest extends AbstractTableReadTest { @Override protected Table<String, Integer, Character> create(Object... data) { ImmutableTable.Builder<String, Integer, Character> builder = ImmutableTable.builder(); for (int i = 0; i < data.length; i = i + 3) { builder.put((String) data[i], (Integer) data[i + 1], (Character) data[i + 2]); } return builder.build(); } public void testBuilder() { ImmutableTable.Builder<Character, Integer, String> builder = new ImmutableTable.Builder<Character, Integer, String>(); assertEquals(ImmutableTable.of(), builder.build()); assertEquals(ImmutableTable.of('a', 1, "foo"), builder .put('a', 1, "foo") .build()); Table<Character, Integer, String> expectedTable = HashBasedTable.create(); expectedTable.put('a', 1, "foo"); expectedTable.put('b', 1, "bar"); expectedTable.put('a', 2, "baz"); Table<Character, Integer, String> otherTable = HashBasedTable.create(); otherTable.put('b', 1, "bar"); otherTable.put('a', 2, "baz"); assertEquals(expectedTable, builder .putAll(otherTable) .build()); } public void testBuilder_withImmutableCell() { ImmutableTable.Builder<Character, Integer, String> builder = new ImmutableTable.Builder<Character, Integer, String>(); assertEquals(ImmutableTable.of('a', 1, "foo"), builder .put(Tables.immutableCell('a', 1, "foo")) .build()); } public void testBuilder_withImmutableCellAndNullContents() { ImmutableTable.Builder<Character, Integer, String> builder = new ImmutableTable.Builder<Character, Integer, String>(); try { builder.put(Tables.immutableCell((Character) null, 1, "foo")); fail(); } catch (NullPointerException e) { // success } try { builder.put(Tables.immutableCell('a', (Integer) null, "foo")); fail(); } catch (NullPointerException e) { // success } try { builder.put(Tables.immutableCell('a', 1, (String) null)); fail(); } catch (NullPointerException e) { // success } } private static class StringHolder { String string; } public void testBuilder_withMutableCell() { ImmutableTable.Builder<Character, Integer, String> builder = new ImmutableTable.Builder<Character, Integer, String>(); final StringHolder holder = new StringHolder(); holder.string = "foo"; Table.Cell<Character, Integer, String> mutableCell = new Tables.AbstractCell<Character, Integer, String>() { @Override public Character getRowKey() { return 'K'; } @Override public Integer getColumnKey() { return 42; } @Override public String getValue() { return holder.string; } }; // Add the mutable cell to the builder builder.put(mutableCell); // Mutate the value holder.string = "bar"; // Make sure it uses the original value. assertEquals(ImmutableTable.of('K', 42, "foo"), builder.build()); } public void testBuilder_noDuplicates() { ImmutableTable.Builder<Character, Integer, String> builder = new ImmutableTable.Builder<Character, Integer, String>() .put('a', 1, "foo") .put('a', 1, "bar"); try { builder.build(); fail(); } catch (IllegalArgumentException e) { // success } } public void testBuilder_noNulls() { ImmutableTable.Builder<Character, Integer, String> builder = new ImmutableTable.Builder<Character, Integer, String>(); try { builder.put(null, 1, "foo"); fail(); } catch (NullPointerException e) { // success } try { builder.put('a', null, "foo"); fail(); } catch (NullPointerException e) { // success } try { builder.put('a', 1, null); fail(); } catch (NullPointerException e) { // success } } private static <R, C, V> void validateTableCopies(Table<R, C, V> original) { Table<R, C, V> copy = ImmutableTable.copyOf(original); assertEquals(original, copy); validateViewOrdering(original, copy); Table<R, C, V> built = ImmutableTable.<R, C, V>builder().putAll(original).build(); assertEquals(original, built); validateViewOrdering(original, built); } private static <R, C, V> void validateViewOrdering( Table<R, C, V> original, Table<R, C, V> copy) { assertTrue(Iterables.elementsEqual(original.cellSet(), copy.cellSet())); assertTrue(Iterables.elementsEqual(original.rowKeySet(), copy.rowKeySet())); assertTrue(Iterables.elementsEqual(original.values(), copy.values())); } public void testCopyOf() { Table<Character, Integer, String> table = TreeBasedTable.create(); validateTableCopies(table); table.put('b', 2, "foo"); validateTableCopies(table); table.put('b', 1, "bar"); table.put('a', 2, "baz"); validateTableCopies(table); // Even though rowKeySet, columnKeySet, and cellSet have the same // iteration ordering, row has an inconsistent ordering. ASSERT.that(table.row('b').keySet()).has().exactly(1, 2).inOrder(); ASSERT.that(ImmutableTable.copyOf(table).row('b').keySet()) .has().exactly(2, 1).inOrder(); } public void testCopyOfSparse() { Table<Character, Integer, String> table = TreeBasedTable.create(); table.put('x', 2, "foo"); table.put('r', 1, "bar"); table.put('c', 3, "baz"); table.put('b', 7, "cat"); table.put('e', 5, "dog"); table.put('c', 0, "axe"); table.put('e', 3, "tub"); table.put('r', 4, "foo"); table.put('x', 5, "bar"); validateTableCopies(table); } public void testCopyOfDense() { Table<Character, Integer, String> table = TreeBasedTable.create(); table.put('c', 3, "foo"); table.put('c', 2, "bar"); table.put('c', 1, "baz"); table.put('b', 3, "cat"); table.put('b', 1, "dog"); table.put('a', 3, "foo"); table.put('a', 2, "bar"); table.put('a', 1, "baz"); validateTableCopies(table); } public void testBuilder_orderRowsAndColumnsBy_putAll() { Table<Character, Integer, String> table = HashBasedTable.create(); table.put('b', 2, "foo"); table.put('b', 1, "bar"); table.put('a', 2, "baz"); ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); Table<Character, Integer, String> copy = builder.orderRowsBy(Ordering.natural()) .orderColumnsBy(Ordering.natural()) .putAll(table).build(); ASSERT.that(copy.rowKeySet()).has().exactly('a', 'b').inOrder(); ASSERT.that(copy.columnKeySet()).has().exactly(1, 2).inOrder(); ASSERT.that(copy.values()).has().exactly("baz", "bar", "foo").inOrder(); ASSERT.that(copy.row('b').keySet()).has().exactly(1, 2).inOrder(); } public void testBuilder_orderRowsAndColumnsBy_sparse() { ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); builder.orderRowsBy(Ordering.natural()); builder.orderColumnsBy(Ordering.natural()); builder.put('x', 2, "foo"); builder.put('r', 1, "bar"); builder.put('c', 3, "baz"); builder.put('b', 7, "cat"); builder.put('e', 5, "dog"); builder.put('c', 0, "axe"); builder.put('e', 3, "tub"); builder.put('r', 4, "foo"); builder.put('x', 5, "bar"); Table<Character, Integer, String> table = builder.build(); ASSERT.that(table.rowKeySet()).has().exactly('b', 'c', 'e', 'r', 'x').inOrder(); ASSERT.that(table.columnKeySet()).has().exactly(0, 1, 2, 3, 4, 5, 7).inOrder(); ASSERT.that(table.values()).has().exactly("cat", "axe", "baz", "tub", "dog", "bar", "foo", "foo", "bar").inOrder(); ASSERT.that(table.row('c').keySet()).has().exactly(0, 3).inOrder(); ASSERT.that(table.column(5).keySet()).has().exactly('e', 'x').inOrder(); } public void testBuilder_orderRowsAndColumnsBy_dense() { ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); builder.orderRowsBy(Ordering.natural()); builder.orderColumnsBy(Ordering.natural()); builder.put('c', 3, "foo"); builder.put('c', 2, "bar"); builder.put('c', 1, "baz"); builder.put('b', 3, "cat"); builder.put('b', 1, "dog"); builder.put('a', 3, "foo"); builder.put('a', 2, "bar"); builder.put('a', 1, "baz"); Table<Character, Integer, String> table = builder.build(); ASSERT.that(table.rowKeySet()).has().exactly('a', 'b', 'c').inOrder(); ASSERT.that(table.columnKeySet()).has().exactly(1, 2, 3).inOrder(); ASSERT.that(table.values()).has().exactly("baz", "bar", "foo", "dog", "cat", "baz", "bar", "foo").inOrder(); ASSERT.that(table.row('c').keySet()).has().exactly(1, 2, 3).inOrder(); ASSERT.that(table.column(1).keySet()).has().exactly('a', 'b', 'c').inOrder(); } public void testBuilder_orderRowsBy_sparse() { ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); builder.orderRowsBy(Ordering.natural()); builder.put('x', 2, "foo"); builder.put('r', 1, "bar"); builder.put('c', 3, "baz"); builder.put('b', 7, "cat"); builder.put('e', 5, "dog"); builder.put('c', 0, "axe"); builder.put('e', 3, "tub"); builder.put('r', 4, "foo"); builder.put('x', 5, "bar"); Table<Character, Integer, String> table = builder.build(); ASSERT.that(table.rowKeySet()).has().exactly('b', 'c', 'e', 'r', 'x').inOrder(); ASSERT.that(table.column(5).keySet()).has().exactly('e', 'x').inOrder(); } public void testBuilder_orderRowsBy_dense() { ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); builder.orderRowsBy(Ordering.natural()); builder.put('c', 3, "foo"); builder.put('c', 2, "bar"); builder.put('c', 1, "baz"); builder.put('b', 3, "cat"); builder.put('b', 1, "dog"); builder.put('a', 3, "foo"); builder.put('a', 2, "bar"); builder.put('a', 1, "baz"); Table<Character, Integer, String> table = builder.build(); ASSERT.that(table.rowKeySet()).has().exactly('a', 'b', 'c').inOrder(); ASSERT.that(table.column(1).keySet()).has().exactly('a', 'b', 'c').inOrder(); } public void testBuilder_orderColumnsBy_sparse() { ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); builder.orderColumnsBy(Ordering.natural()); builder.put('x', 2, "foo"); builder.put('r', 1, "bar"); builder.put('c', 3, "baz"); builder.put('b', 7, "cat"); builder.put('e', 5, "dog"); builder.put('c', 0, "axe"); builder.put('e', 3, "tub"); builder.put('r', 4, "foo"); builder.put('x', 5, "bar"); Table<Character, Integer, String> table = builder.build(); ASSERT.that(table.columnKeySet()).has().exactly(0, 1, 2, 3, 4, 5, 7).inOrder(); ASSERT.that(table.row('c').keySet()).has().exactly(0, 3).inOrder(); } public void testBuilder_orderColumnsBy_dense() { ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); builder.orderColumnsBy(Ordering.natural()); builder.put('c', 3, "foo"); builder.put('c', 2, "bar"); builder.put('c', 1, "baz"); builder.put('b', 3, "cat"); builder.put('b', 1, "dog"); builder.put('a', 3, "foo"); builder.put('a', 2, "bar"); builder.put('a', 1, "baz"); Table<Character, Integer, String> table = builder.build(); ASSERT.that(table.columnKeySet()).has().exactly(1, 2, 3).inOrder(); ASSERT.that(table.row('c').keySet()).has().exactly(1, 2, 3).inOrder(); } }
Java
/* * Copyright (C) 2008 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.collect; import static com.google.common.collect.Iterators.peekingIterator; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static java.util.Collections.emptyList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.IteratorTester; import junit.framework.TestCase; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * Unit test for {@link PeekingIterator}. * * @author Mick Killianey */ @SuppressWarnings("serial") // No serialization is used in this test @GwtCompatible(emulated = true) public class PeekingIteratorTest extends TestCase { /** * Version of {@link IteratorTester} that compares an iterator over * a given collection of elements (used as the reference iterator) * against a {@code PeekingIterator} that *wraps* such an iterator * (used as the target iterator). * * <p>This IteratorTester makes copies of the master so that it can * later verify that {@link PeekingIterator#remove()} removes the * same elements as the reference's iterator {@code #remove()}. */ private static class PeekingIteratorTester<T> extends IteratorTester<T> { private Iterable<T> master; private List<T> targetList; public PeekingIteratorTester(Collection<T> master) { super(master.size() + 3, MODIFIABLE, master, IteratorTester.KnownOrder.KNOWN_ORDER); this.master = master; } @Override protected Iterator<T> newTargetIterator() { // make copy from master to verify later targetList = Lists.newArrayList(master); Iterator<T> iterator = targetList.iterator(); return Iterators.peekingIterator(iterator); } @Override protected void verify(List<T> elements) { // verify same objects were removed from reference and target assertEquals(elements, targetList); } } private <T> void actsLikeIteratorHelper(final List<T> list) { // Check with modifiable copies of the list new PeekingIteratorTester<T>(list).test(); // Check with unmodifiable lists new IteratorTester<T>(list.size() * 2 + 2, UNMODIFIABLE, list, IteratorTester.KnownOrder.KNOWN_ORDER) { @Override protected Iterator<T> newTargetIterator() { Iterator<T> iterator = Collections.unmodifiableList(list).iterator(); return Iterators.peekingIterator(iterator); } }.test(); } public void testPeekingIteratorBehavesLikeIteratorOnEmptyIterable() { actsLikeIteratorHelper(Collections.emptyList()); } public void testPeekingIteratorBehavesLikeIteratorOnSingletonIterable() { actsLikeIteratorHelper(Collections.singletonList(new Object())); } // TODO(cpovirk): instead of skipping, use a smaller number of steps public void testPeekOnEmptyList() { List<?> list = Collections.emptyList(); Iterator<?> iterator = list.iterator(); PeekingIterator<?> peekingIterator = Iterators.peekingIterator(iterator); try { peekingIterator.peek(); fail("Should throw NoSuchElementException if nothing to peek()"); } catch (NoSuchElementException e) { /* expected */ } } public void testPeekDoesntChangeIteration() { List<?> list = Lists.newArrayList("A", "B", "C"); Iterator<?> iterator = list.iterator(); PeekingIterator<?> peekingIterator = Iterators.peekingIterator(iterator); assertEquals("Should be able to peek() at first element", "A", peekingIterator.peek()); assertEquals("Should be able to peek() first element multiple times", "A", peekingIterator.peek()); assertEquals("next() should still return first element after peeking", "A", peekingIterator.next()); assertEquals("Should be able to peek() at middle element", "B", peekingIterator.peek()); assertEquals("Should be able to peek() middle element multiple times", "B", peekingIterator.peek()); assertEquals("next() should still return middle element after peeking", "B", peekingIterator.next()); assertEquals("Should be able to peek() at last element", "C", peekingIterator.peek()); assertEquals("Should be able to peek() last element multiple times", "C", peekingIterator.peek()); assertEquals("next() should still return last element after peeking", "C", peekingIterator.next()); try { peekingIterator.peek(); fail("Should throw exception if no next to peek()"); } catch (NoSuchElementException e) { /* expected */ } try { peekingIterator.peek(); fail("Should continue to throw exception if no next to peek()"); } catch (NoSuchElementException e) { /* expected */ } try { peekingIterator.next(); fail("next() should still throw exception after the end of iteration"); } catch (NoSuchElementException e) { /* expected */ } } public void testCantRemoveAfterPeek() { List<String> list = Lists.newArrayList("A", "B", "C"); Iterator<String> iterator = list.iterator(); PeekingIterator<?> peekingIterator = Iterators.peekingIterator(iterator); assertEquals("A", peekingIterator.next()); assertEquals("B", peekingIterator.peek()); /* Should complain on attempt to remove() after peek(). */ try { peekingIterator.remove(); fail("remove() should throw IllegalStateException after a peek()"); } catch (IllegalStateException e) { /* expected */ } assertEquals("After remove() throws exception, peek should still be ok", "B", peekingIterator.peek()); /* Should recover to be able to remove() after next(). */ assertEquals("B", peekingIterator.next()); peekingIterator.remove(); assertEquals("Should have removed an element", 2, list.size()); assertFalse("Second element should be gone", list.contains("B")); } static class ThrowsAtEndException extends RuntimeException { /* nothing */ } /** * This Iterator claims to have more elements than the underlying * iterable, but when you try to fetch the extra elements, it throws * an unchecked exception. */ static class ThrowsAtEndIterator<E> implements Iterator<E> { Iterator<E> iterator; public ThrowsAtEndIterator(Iterable<E> iterable) { this.iterator = iterable.iterator(); } @Override public boolean hasNext() { return true; // pretend that you have more... } @Override public E next() { // ...but throw an unchecked exception when you ask for it. if (!iterator.hasNext()) { throw new ThrowsAtEndException(); } return iterator.next(); } @Override public void remove() { iterator.remove(); } } public void testPeekingIteratorDoesntAdvancePrematurely() throws Exception { /* * This test will catch problems where the underlying iterator * throws a RuntimeException when retrieving the nth element. * * If the PeekingIterator is caching elements too aggressively, * it may throw the exception on the (n-1)th element (oops!). */ /* Checks the case where the first element throws an exception. */ List<Integer> list = emptyList(); Iterator<Integer> iterator = peekingIterator(new ThrowsAtEndIterator<Integer>(list)); assertNextThrows(iterator); /* Checks the case where a later element throws an exception. */ list = Lists.newArrayList(1, 2); iterator = peekingIterator(new ThrowsAtEndIterator<Integer>(list)); assertTrue(iterator.hasNext()); iterator.next(); assertTrue(iterator.hasNext()); iterator.next(); assertNextThrows(iterator); } private void assertNextThrows(Iterator<?> iterator) { try { iterator.next(); fail(); } catch (ThrowsAtEndException expected) { } } }
Java
/* * Copyright (C) 2007 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.collect; import static java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.google.TestStringMultisetGenerator; import junit.framework.TestCase; import java.util.Arrays; /** * Unit test for {@link HashMultiset}. * * @author Kevin Bourrillion * @author Jared Levy */ @GwtCompatible(emulated = true) public class HashMultisetTest extends TestCase { private static TestStringMultisetGenerator hashMultisetGenerator() { return new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { return HashMultiset.create(asList(elements)); } }; } public void testCreate() { Multiset<String> multiset = HashMultiset.create(); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); } public void testCreateWithSize() { Multiset<String> multiset = HashMultiset.create(50); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); } public void testCreateFromIterable() { Multiset<String> multiset = HashMultiset.create(Arrays.asList("foo", "bar", "foo")); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); } /* * The behavior of toString() and iteration is tested by LinkedHashMultiset, * which shares a lot of code with HashMultiset and has deterministic * iteration order. */ }
Java
/* * Copyright (C) 2007 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.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.google.TestBiMapGenerator; import junit.framework.TestCase; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Tests for {@code EnumHashBiMap}. * * @author Mike Bostock */ @GwtCompatible(emulated = true) public class EnumHashBiMapTest extends TestCase { private enum Currency { DOLLAR, FRANC, PESO, POUND, YEN } private enum Country { CANADA, CHILE, JAPAN, SWITZERLAND, UK } public static final class EnumHashBiMapGenerator implements TestBiMapGenerator<Country, String> { @SuppressWarnings("unchecked") @Override public BiMap<Country, String> create(Object... entries) { BiMap<Country, String> result = EnumHashBiMap.create(Country.class); for (Object o : entries) { Entry<Country, String> entry = (Entry<Country, String>) o; result.put(entry.getKey(), entry.getValue()); } return result; } @Override public SampleElements<Entry<Country, String>> samples() { return new SampleElements<Entry<Country, String>>( Maps.immutableEntry(Country.CANADA, "DOLLAR"), Maps.immutableEntry(Country.CHILE, "PESO"), Maps.immutableEntry(Country.UK, "POUND"), Maps.immutableEntry(Country.JAPAN, "YEN"), Maps.immutableEntry(Country.SWITZERLAND, "FRANC")); } @SuppressWarnings("unchecked") @Override public Entry<Country, String>[] createArray(int length) { return new Entry[length]; } @Override public Iterable<Entry<Country, String>> order(List<Entry<Country, String>> insertionOrder) { return insertionOrder; } @Override public Country[] createKeyArray(int length) { return new Country[length]; } @Override public String[] createValueArray(int length) { return new String[length]; } } public void testCreate() { EnumHashBiMap<Currency, String> bimap = EnumHashBiMap.create(Currency.class); assertTrue(bimap.isEmpty()); assertEquals("{}", bimap.toString()); assertEquals(HashBiMap.create(), bimap); bimap.put(Currency.DOLLAR, "dollar"); assertEquals("dollar", bimap.get(Currency.DOLLAR)); assertEquals(Currency.DOLLAR, bimap.inverse().get("dollar")); } public void testCreateFromMap() { /* Test with non-empty Map. */ Map<Currency, String> map = ImmutableMap.of( Currency.DOLLAR, "dollar", Currency.PESO, "peso", Currency.FRANC, "franc"); EnumHashBiMap<Currency, String> bimap = EnumHashBiMap.create(map); assertEquals("dollar", bimap.get(Currency.DOLLAR)); assertEquals(Currency.DOLLAR, bimap.inverse().get("dollar")); /* Map must have at least one entry if not an EnumHashBiMap. */ try { EnumHashBiMap.create( Collections.<Currency, String>emptyMap()); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException expected) {} /* Map can be empty if it's an EnumHashBiMap. */ Map<Currency, String> emptyBimap = EnumHashBiMap.create(Currency.class); bimap = EnumHashBiMap.create(emptyBimap); assertTrue(bimap.isEmpty()); /* Map can be empty if it's an EnumBiMap. */ Map<Currency, Country> emptyBimap2 = EnumBiMap.create(Currency.class, Country.class); EnumHashBiMap<Currency, Country> bimap2 = EnumHashBiMap.create(emptyBimap2); assertTrue(bimap2.isEmpty()); } public void testEnumHashBiMapConstructor() { /* Test that it copies existing entries. */ EnumHashBiMap<Currency, String> bimap1 = EnumHashBiMap.create(Currency.class); bimap1.put(Currency.DOLLAR, "dollar"); EnumHashBiMap<Currency, String> bimap2 = EnumHashBiMap.create(bimap1); assertEquals("dollar", bimap2.get(Currency.DOLLAR)); assertEquals(bimap1, bimap2); bimap2.inverse().put("franc", Currency.FRANC); assertEquals("franc", bimap2.get(Currency.FRANC)); assertNull(bimap1.get(Currency.FRANC)); assertFalse(bimap2.equals(bimap1)); /* Test that it can be empty. */ EnumHashBiMap<Currency, String> emptyBimap = EnumHashBiMap.create(Currency.class); EnumHashBiMap<Currency, String> bimap3 = EnumHashBiMap.create(emptyBimap); assertEquals(bimap3, emptyBimap); } public void testEnumBiMapConstructor() { /* Test that it copies existing entries. */ EnumBiMap<Currency, Country> bimap1 = EnumBiMap.create(Currency.class, Country.class); bimap1.put(Currency.DOLLAR, Country.SWITZERLAND); EnumHashBiMap<Currency, Object> bimap2 = // use supertype EnumHashBiMap.<Currency, Object>create(bimap1); assertEquals(Country.SWITZERLAND, bimap2.get(Currency.DOLLAR)); assertEquals(bimap1, bimap2); bimap2.inverse().put("franc", Currency.FRANC); assertEquals("franc", bimap2.get(Currency.FRANC)); assertNull(bimap1.get(Currency.FRANC)); assertFalse(bimap2.equals(bimap1)); /* Test that it can be empty. */ EnumBiMap<Currency, Country> emptyBimap = EnumBiMap.create(Currency.class, Country.class); EnumHashBiMap<Currency, Country> bimap3 = // use exact type EnumHashBiMap.create(emptyBimap); assertEquals(bimap3, emptyBimap); } public void testKeyType() { EnumHashBiMap<Currency, String> bimap = EnumHashBiMap.create(Currency.class); assertEquals(Currency.class, bimap.keyType()); } public void testEntrySet() { // Bug 3168290 Map<Currency, String> map = ImmutableMap.of( Currency.DOLLAR, "dollar", Currency.PESO, "peso", Currency.FRANC, "franc"); EnumHashBiMap<Currency, String> bimap = EnumHashBiMap.create(map); Set<Object> uniqueEntries = Sets.newIdentityHashSet(); uniqueEntries.addAll(bimap.entrySet()); assertEquals(3, uniqueEntries.size()); } }
Java
/* * Copyright (C) 2007 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.collect; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.collect.testing.IteratorTester; import junit.framework.TestCase; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.RandomAccess; /** * Unit test for {@code Lists}. * * @author Kevin Bourrillion * @author Mike Bostock * @author Jared Levy */ @GwtCompatible(emulated = true) public class ListsTest extends TestCase { private static final Collection<Integer> SOME_COLLECTION = asList(0, 1, 1); private static final Iterable<Integer> SOME_ITERABLE = new SomeIterable(); private static final class RemoveFirstFunction implements Function<String, String>, Serializable { @Override public String apply(String from) { return (from.length() == 0) ? from : from.substring(1); } } private static class SomeIterable implements Iterable<Integer>, Serializable { @Override public Iterator<Integer> iterator() { return SOME_COLLECTION.iterator(); } private static final long serialVersionUID = 0; } private static final List<Integer> SOME_LIST = Lists.newArrayList(1, 2, 3, 4); private static final List<Integer> SOME_SEQUENTIAL_LIST = Lists.newLinkedList(asList(1, 2, 3, 4)); private static final List<String> SOME_STRING_LIST = asList("1", "2", "3", "4"); private static final Function<Number, String> SOME_FUNCTION = new SomeFunction(); private static class SomeFunction implements Function<Number, String>, Serializable { @Override public String apply(Number n) { return String.valueOf(n); } private static final long serialVersionUID = 0; } public void testCharactersOfIsView() { StringBuilder builder = new StringBuilder("abc"); List<Character> chars = Lists.charactersOf(builder); assertEquals(asList('a', 'b', 'c'), chars); builder.append("def"); assertEquals( asList('a', 'b', 'c', 'd', 'e', 'f'), chars); builder.deleteCharAt(5); assertEquals( asList('a', 'b', 'c', 'd', 'e'), chars); } public void testNewArrayListEmpty() { ArrayList<Integer> list = Lists.newArrayList(); assertEquals(Collections.emptyList(), list); } public void testNewArrayListWithCapacity() { ArrayList<Integer> list = Lists.newArrayListWithCapacity(0); assertEquals(Collections.emptyList(), list); ArrayList<Integer> bigger = Lists.newArrayListWithCapacity(256); assertEquals(Collections.emptyList(), bigger); } public void testNewArrayListWithCapacity_negative() { try { Lists.newArrayListWithCapacity(-1); fail(); } catch (IllegalArgumentException expected) { } } public void testNewArrayListWithExpectedSize() { ArrayList<Integer> list = Lists.newArrayListWithExpectedSize(0); assertEquals(Collections.emptyList(), list); ArrayList<Integer> bigger = Lists.newArrayListWithExpectedSize(256); assertEquals(Collections.emptyList(), bigger); } public void testNewArrayListWithExpectedSize_negative() { try { Lists.newArrayListWithExpectedSize(-1); fail(); } catch (IllegalArgumentException expected) { } } public void testNewArrayListVarArgs() { ArrayList<Integer> list = Lists.newArrayList(0, 1, 1); assertEquals(SOME_COLLECTION, list); } public void testComputeArrayListCapacity() { assertEquals(5, Lists.computeArrayListCapacity(0)); assertEquals(13, Lists.computeArrayListCapacity(8)); assertEquals(89, Lists.computeArrayListCapacity(77)); assertEquals(22000005, Lists.computeArrayListCapacity(20000000)); assertEquals(Integer.MAX_VALUE, Lists.computeArrayListCapacity(Integer.MAX_VALUE - 1000)); } public void testNewArrayListFromCollection() { ArrayList<Integer> list = Lists.newArrayList(SOME_COLLECTION); assertEquals(SOME_COLLECTION, list); } public void testNewArrayListFromIterable() { ArrayList<Integer> list = Lists.newArrayList(SOME_ITERABLE); assertEquals(SOME_COLLECTION, list); } public void testNewArrayListFromIterator() { ArrayList<Integer> list = Lists.newArrayList(SOME_COLLECTION.iterator()); assertEquals(SOME_COLLECTION, list); } public void testNewLinkedListEmpty() { LinkedList<Integer> list = Lists.newLinkedList(); assertEquals(Collections.emptyList(), list); } public void testNewLinkedListFromCollection() { LinkedList<Integer> list = Lists.newLinkedList(SOME_COLLECTION); assertEquals(SOME_COLLECTION, list); } public void testNewLinkedListFromIterable() { LinkedList<Integer> list = Lists.newLinkedList(SOME_ITERABLE); assertEquals(SOME_COLLECTION, list); } /** * This is just here to illustrate how {@code Arrays#asList} differs from * {@code Lists#newArrayList}. */ public void testArraysAsList() { List<String> ourWay = Lists.newArrayList("foo", "bar", "baz"); List<String> otherWay = asList("foo", "bar", "baz"); // They're logically equal assertEquals(ourWay, otherWay); // The result of Arrays.asList() is mutable otherWay.set(0, "FOO"); assertEquals("FOO", otherWay.get(0)); // But it can't grow try { otherWay.add("nope"); fail("no exception thrown"); } catch (UnsupportedOperationException expected) { } // And it can't shrink try { otherWay.remove(2); fail("no exception thrown"); } catch (UnsupportedOperationException expected) { } } private void checkFooBarBazList(List<String> list) { ASSERT.that(list).has().exactly("foo", "bar", "baz").inOrder(); assertEquals(3, list.size()); assertIndexIsOutOfBounds(list, -1); assertEquals("foo", list.get(0)); assertEquals("bar", list.get(1)); assertEquals("baz", list.get(2)); assertIndexIsOutOfBounds(list, 3); } public void testAsList1Small() { List<String> list = Lists.asList("foo", new String[0]); ASSERT.that(list).has().item("foo"); assertEquals(1, list.size()); assertIndexIsOutOfBounds(list, -1); assertEquals("foo", list.get(0)); assertIndexIsOutOfBounds(list, 1); assertTrue(list instanceof RandomAccess); new IteratorTester<String>(3, UNMODIFIABLE, singletonList("foo"), IteratorTester.KnownOrder.KNOWN_ORDER) { @Override protected Iterator<String> newTargetIterator() { return Lists.asList("foo", new String[0]).iterator(); } }.test(); } public void testAsList2() { List<String> list = Lists.asList("foo", "bar", new String[] { "baz" }); checkFooBarBazList(list); assertTrue(list instanceof RandomAccess); new IteratorTester<String>(5, UNMODIFIABLE, asList("foo", "bar", "baz"), IteratorTester.KnownOrder.KNOWN_ORDER) { @Override protected Iterator<String> newTargetIterator() { return Lists.asList("foo", "bar", new String[] {"baz"}).iterator(); } }.test(); } private static void assertIndexIsOutOfBounds(List<String> list, int index) { try { list.get(index); fail(); } catch (IndexOutOfBoundsException expected) { } } public void testReverseViewRandomAccess() { List<Integer> fromList = Lists.newArrayList(SOME_LIST); List<Integer> toList = Lists.reverse(fromList); assertReverseView(fromList, toList); } public void testReverseViewSequential() { List<Integer> fromList = Lists.newLinkedList(SOME_SEQUENTIAL_LIST); List<Integer> toList = Lists.reverse(fromList); assertReverseView(fromList, toList); } private static void assertReverseView(List<Integer> fromList, List<Integer> toList) { /* fromList modifications reflected in toList */ fromList.set(0, 5); assertEquals(asList(4, 3, 2, 5), toList); fromList.add(6); assertEquals(asList(6, 4, 3, 2, 5), toList); fromList.add(2, 9); assertEquals(asList(6, 4, 3, 9, 2, 5), toList); fromList.remove(Integer.valueOf(2)); assertEquals(asList(6, 4, 3, 9, 5), toList); fromList.remove(3); assertEquals(asList(6, 3, 9, 5), toList); /* toList modifications reflected in fromList */ toList.remove(0); assertEquals(asList(5, 9, 3), fromList); toList.add(7); assertEquals(asList(7, 5, 9, 3), fromList); toList.add(5); assertEquals(asList(5, 7, 5, 9, 3), fromList); toList.remove(Integer.valueOf(5)); assertEquals(asList(5, 7, 9, 3), fromList); toList.set(1, 8); assertEquals(asList(5, 7, 8, 3), fromList); toList.clear(); assertEquals(Collections.emptyList(), fromList); } private static <E> List<E> list(E... elements) { return ImmutableList.copyOf(elements); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x1() { ASSERT.that(Lists.cartesianProduct(list(1), list(2))).has().item(list(1, 2)); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x2() { ASSERT.that(Lists.cartesianProduct(list(1), list(2, 3))) .has().exactly(list(1, 2), list(1, 3)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary2x2() { ASSERT.that(Lists.cartesianProduct(list(1, 2), list(3, 4))) .has().exactly(list(1, 3), list(1, 4), list(2, 3), list(2, 4)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_2x2x2() { ASSERT.that(Lists.cartesianProduct(list(0, 1), list(0, 1), list(0, 1))).has().exactly( list(0, 0, 0), list(0, 0, 1), list(0, 1, 0), list(0, 1, 1), list(1, 0, 0), list(1, 0, 1), list(1, 1, 0), list(1, 1, 1)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_contains() { List<List<Integer>> actual = Lists.cartesianProduct(list(1, 2), list(3, 4)); assertTrue(actual.contains(list(1, 3))); assertTrue(actual.contains(list(1, 4))); assertTrue(actual.contains(list(2, 3))); assertTrue(actual.contains(list(2, 4))); assertFalse(actual.contains(list(3, 1))); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_unrelatedTypes() { List<Integer> x = list(1, 2); List<String> y = list("3", "4"); List<Object> exp1 = list((Object) 1, "3"); List<Object> exp2 = list((Object) 1, "4"); List<Object> exp3 = list((Object) 2, "3"); List<Object> exp4 = list((Object) 2, "4"); ASSERT.that(Lists.<Object>cartesianProduct(x, y)) .has().exactly(exp1, exp2, exp3, exp4).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProductTooBig() { List<String> list = Collections.nCopies(10000, "foo"); try { Lists.cartesianProduct(list, list, list, list, list); fail("Expected IAE"); } catch (IllegalArgumentException expected) {} } public void testTransformHashCodeRandomAccess() { List<String> list = Lists.transform(SOME_LIST, SOME_FUNCTION); assertEquals(SOME_STRING_LIST.hashCode(), list.hashCode()); } public void testTransformHashCodeSequential() { List<String> list = Lists.transform(SOME_SEQUENTIAL_LIST, SOME_FUNCTION); assertEquals(SOME_STRING_LIST.hashCode(), list.hashCode()); } public void testTransformModifiableRandomAccess() { List<Integer> fromList = Lists.newArrayList(SOME_LIST); List<String> list = Lists.transform(fromList, SOME_FUNCTION); assertTransformModifiable(list); } public void testTransformModifiableSequential() { List<Integer> fromList = Lists.newLinkedList(SOME_SEQUENTIAL_LIST); List<String> list = Lists.transform(fromList, SOME_FUNCTION); assertTransformModifiable(list); } private static void assertTransformModifiable(List<String> list) { try { list.add("5"); fail("transformed list is addable"); } catch (UnsupportedOperationException expected) {} list.remove(0); assertEquals(asList("2", "3", "4"), list); list.remove("3"); assertEquals(asList("2", "4"), list); try { list.set(0, "5"); fail("transformed list is setable"); } catch (UnsupportedOperationException expected) {} list.clear(); assertEquals(Collections.emptyList(), list); } public void testTransformViewRandomAccess() { List<Integer> fromList = Lists.newArrayList(SOME_LIST); List<String> toList = Lists.transform(fromList, SOME_FUNCTION); assertTransformView(fromList, toList); } public void testTransformViewSequential() { List<Integer> fromList = Lists.newLinkedList(SOME_SEQUENTIAL_LIST); List<String> toList = Lists.transform(fromList, SOME_FUNCTION); assertTransformView(fromList, toList); } private static void assertTransformView(List<Integer> fromList, List<String> toList) { /* fromList modifications reflected in toList */ fromList.set(0, 5); assertEquals(asList("5", "2", "3", "4"), toList); fromList.add(6); assertEquals(asList("5", "2", "3", "4", "6"), toList); fromList.remove(Integer.valueOf(2)); assertEquals(asList("5", "3", "4", "6"), toList); fromList.remove(2); assertEquals(asList("5", "3", "6"), toList); /* toList modifications reflected in fromList */ toList.remove(2); assertEquals(asList(5, 3), fromList); toList.remove("5"); assertEquals(asList(3), fromList); toList.clear(); assertEquals(Collections.emptyList(), fromList); } public void testTransformRandomAccess() { List<String> list = Lists.transform(SOME_LIST, SOME_FUNCTION); assertTrue(list instanceof RandomAccess); } public void testTransformSequential() { List<String> list = Lists.transform(SOME_SEQUENTIAL_LIST, SOME_FUNCTION); assertFalse(list instanceof RandomAccess); } public void testTransformListIteratorRandomAccess() { List<Integer> fromList = Lists.newArrayList(SOME_LIST); List<String> list = Lists.transform(fromList, SOME_FUNCTION); assertTransformListIterator(list); } public void testTransformListIteratorSequential() { List<Integer> fromList = Lists.newLinkedList(SOME_SEQUENTIAL_LIST); List<String> list = Lists.transform(fromList, SOME_FUNCTION); assertTransformListIterator(list); } private static void assertTransformListIterator(List<String> list) { ListIterator<String> iterator = list.listIterator(1); assertEquals(1, iterator.nextIndex()); assertEquals("2", iterator.next()); assertEquals("3", iterator.next()); assertEquals("4", iterator.next()); assertEquals(4, iterator.nextIndex()); try { iterator.next(); fail("did not detect end of list"); } catch (NoSuchElementException expected) {} assertEquals(3, iterator.previousIndex()); assertEquals("4", iterator.previous()); assertEquals("3", iterator.previous()); assertEquals("2", iterator.previous()); assertTrue(iterator.hasPrevious()); assertEquals("1", iterator.previous()); assertFalse(iterator.hasPrevious()); assertEquals(-1, iterator.previousIndex()); try { iterator.previous(); fail("did not detect beginning of list"); } catch (NoSuchElementException expected) {} iterator.remove(); assertEquals(asList("2", "3", "4"), list); assertFalse(list.isEmpty()); // An UnsupportedOperationException or IllegalStateException may occur. try { iterator.add("1"); fail("transformed list iterator is addable"); } catch (UnsupportedOperationException expected) { } catch (IllegalStateException expected) {} try { iterator.set("1"); fail("transformed list iterator is settable"); } catch (UnsupportedOperationException expected) { } catch (IllegalStateException expected) {} } public void testTransformIteratorRandomAccess() { List<Integer> fromList = Lists.newArrayList(SOME_LIST); List<String> list = Lists.transform(fromList, SOME_FUNCTION); assertTransformIterator(list); } public void testTransformIteratorSequential() { List<Integer> fromList = Lists.newLinkedList(SOME_SEQUENTIAL_LIST); List<String> list = Lists.transform(fromList, SOME_FUNCTION); assertTransformIterator(list); } /** * We use this class to avoid the need to suppress generics checks with * easy mock. */ private interface IntegerList extends List<Integer> {} private static void assertTransformIterator(List<String> list) { Iterator<String> iterator = list.iterator(); assertTrue(iterator.hasNext()); assertEquals("1", iterator.next()); assertTrue(iterator.hasNext()); assertEquals("2", iterator.next()); assertTrue(iterator.hasNext()); assertEquals("3", iterator.next()); assertTrue(iterator.hasNext()); assertEquals("4", iterator.next()); assertFalse(iterator.hasNext()); try { iterator.next(); fail("did not detect end of list"); } catch (NoSuchElementException expected) {} iterator.remove(); assertEquals(asList("1", "2", "3"), list); assertFalse(iterator.hasNext()); } public void testPartition_badSize() { List<Integer> source = Collections.singletonList(1); try { Lists.partition(source, 0); fail(); } catch (IllegalArgumentException expected) { } } public void testPartition_empty() { List<Integer> source = Collections.emptyList(); List<List<Integer>> partitions = Lists.partition(source, 1); assertTrue(partitions.isEmpty()); assertEquals(0, partitions.size()); } public void testPartition_1_1() { List<Integer> source = Collections.singletonList(1); List<List<Integer>> partitions = Lists.partition(source, 1); assertEquals(1, partitions.size()); assertEquals(Collections.singletonList(1), partitions.get(0)); } public void testPartition_1_2() { List<Integer> source = Collections.singletonList(1); List<List<Integer>> partitions = Lists.partition(source, 2); assertEquals(1, partitions.size()); assertEquals(Collections.singletonList(1), partitions.get(0)); } public void testPartition_2_1() { List<Integer> source = asList(1, 2); List<List<Integer>> partitions = Lists.partition(source, 1); assertEquals(2, partitions.size()); assertEquals(Collections.singletonList(1), partitions.get(0)); assertEquals(Collections.singletonList(2), partitions.get(1)); } public void testPartition_3_2() { List<Integer> source = asList(1, 2, 3); List<List<Integer>> partitions = Lists.partition(source, 2); assertEquals(2, partitions.size()); assertEquals(asList(1, 2), partitions.get(0)); assertEquals(asList(3), partitions.get(1)); } public void testPartitionRandomAccessFalse() { List<Integer> source = Lists.newLinkedList(asList(1, 2, 3)); List<List<Integer>> partitions = Lists.partition(source, 2); assertFalse(partitions instanceof RandomAccess); assertFalse(partitions.get(0) instanceof RandomAccess); assertFalse(partitions.get(1) instanceof RandomAccess); } // TODO: use the ListTestSuiteBuilder public void testPartition_view() { List<Integer> list = asList(1, 2, 3); List<List<Integer>> partitions = Lists.partition(list, 3); // Changes before the partition is retrieved are reflected list.set(0, 3); Iterator<List<Integer>> iterator = partitions.iterator(); // Changes before the partition is retrieved are reflected list.set(1, 4); List<Integer> first = iterator.next(); // Changes after are too (unlike Iterables.partition) list.set(2, 5); assertEquals(asList(3, 4, 5), first); // Changes to a sublist also write through to the original list first.set(1, 6); assertEquals(asList(3, 6, 5), list); } public void testPartitionSize_1() { List<Integer> list = asList(1, 2, 3); assertEquals(1, Lists.partition(list, Integer.MAX_VALUE).size()); assertEquals(1, Lists.partition(list, Integer.MAX_VALUE - 1).size()); } }
Java
/* * Copyright (C) 2008 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableListMultimap.Builder; import com.google.common.collect.testing.google.TestStringListMultimapGenerator; import com.google.common.collect.testing.google.UnmodifiableCollectionTests; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collections; import java.util.Map.Entry; /** * Tests for {@link ImmutableListMultimap}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class ImmutableListMultimapTest extends TestCase { public static class ImmutableListMultimapGenerator extends TestStringListMultimapGenerator { @Override protected ListMultimap<String, String> create(Entry<String, String>[] entries) { ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder(); for (Entry<String, String> entry : entries) { builder.put(entry.getKey(), entry.getValue()); } return builder.build(); } } public void testBuilder_withImmutableEntry() { ImmutableListMultimap<String, Integer> multimap = new Builder<String, Integer>() .put(Maps.immutableEntry("one", 1)) .build(); assertEquals(Arrays.asList(1), multimap.get("one")); } public void testBuilder_withImmutableEntryAndNullContents() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(Maps.immutableEntry("one", (Integer) null)); fail(); } catch (NullPointerException expected) { } try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) { } } private static class StringHolder { String string; } public void testBuilder_withMutableEntry() { ImmutableListMultimap.Builder<String, Integer> builder = new Builder<String, Integer>(); final StringHolder holder = new StringHolder(); holder.string = "one"; Entry<String, Integer> entry = new AbstractMapEntry<String, Integer>() { @Override public String getKey() { return holder.string; } @Override public Integer getValue() { return 1; } }; builder.put(entry); holder.string = "two"; assertEquals(Arrays.asList(1), builder.build().get("one")); } public void testBuilderPutAllIterable() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.putAll("foo", Arrays.asList(1, 2, 3)); builder.putAll("bar", Arrays.asList(4, 5)); builder.putAll("foo", Arrays.asList(6, 7)); Multimap<String, Integer> multimap = builder.build(); assertEquals(Arrays.asList(1, 2, 3, 6, 7), multimap.get("foo")); assertEquals(Arrays.asList(4, 5), multimap.get("bar")); assertEquals(7, multimap.size()); } public void testBuilderPutAllVarargs() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.putAll("foo", 1, 2, 3); builder.putAll("bar", 4, 5); builder.putAll("foo", 6, 7); Multimap<String, Integer> multimap = builder.build(); assertEquals(Arrays.asList(1, 2, 3, 6, 7), multimap.get("foo")); assertEquals(Arrays.asList(4, 5), multimap.get("bar")); assertEquals(7, multimap.size()); } public void testBuilderPutAllMultimap() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put("foo", 1); toPut.put("bar", 4); toPut.put("foo", 2); toPut.put("foo", 3); Multimap<String, Integer> moreToPut = LinkedListMultimap.create(); moreToPut.put("foo", 6); moreToPut.put("bar", 5); moreToPut.put("foo", 7); ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.putAll(toPut); builder.putAll(moreToPut); Multimap<String, Integer> multimap = builder.build(); assertEquals(Arrays.asList(1, 2, 3, 6, 7), multimap.get("foo")); assertEquals(Arrays.asList(4, 5), multimap.get("bar")); assertEquals(7, multimap.size()); } public void testBuilderPutAllWithDuplicates() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.putAll("foo", 1, 2, 3); builder.putAll("bar", 4, 5); builder.putAll("foo", 1, 6, 7); ImmutableListMultimap<String, Integer> multimap = builder.build(); assertEquals(Arrays.asList(1, 2, 3, 1, 6, 7), multimap.get("foo")); assertEquals(Arrays.asList(4, 5), multimap.get("bar")); assertEquals(8, multimap.size()); } public void testBuilderPutWithDuplicates() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.putAll("foo", 1, 2, 3); builder.putAll("bar", 4, 5); builder.put("foo", 1); ImmutableListMultimap<String, Integer> multimap = builder.build(); assertEquals(Arrays.asList(1, 2, 3, 1), multimap.get("foo")); assertEquals(Arrays.asList(4, 5), multimap.get("bar")); assertEquals(6, multimap.size()); } public void testBuilderPutAllMultimapWithDuplicates() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put("foo", 1); toPut.put("bar", 4); toPut.put("foo", 2); toPut.put("foo", 1); toPut.put("bar", 5); Multimap<String, Integer> moreToPut = LinkedListMultimap.create(); moreToPut.put("foo", 6); moreToPut.put("bar", 4); moreToPut.put("foo", 7); moreToPut.put("foo", 2); ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.putAll(toPut); builder.putAll(moreToPut); Multimap<String, Integer> multimap = builder.build(); assertEquals(Arrays.asList(1, 2, 1, 6, 7, 2), multimap.get("foo")); assertEquals(Arrays.asList(4, 5, 4), multimap.get("bar")); assertEquals(9, multimap.size()); } public void testBuilderPutNullKey() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put("foo", null); ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); try { builder.put(null, 1); fail(); } catch (NullPointerException expected) {} try { builder.putAll(null, Arrays.asList(1, 2, 3)); fail(); } catch (NullPointerException expected) {} try { builder.putAll(null, 1, 2, 3); fail(); } catch (NullPointerException expected) {} try { builder.putAll(toPut); fail(); } catch (NullPointerException expected) {} } public void testBuilderPutNullValue() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put(null, 1); ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); try { builder.put("foo", null); fail(); } catch (NullPointerException expected) {} try { builder.putAll("foo", Arrays.asList(1, null, 3)); fail(); } catch (NullPointerException expected) {} try { builder.putAll("foo", 1, null, 3); fail(); } catch (NullPointerException expected) {} try { builder.putAll(toPut); fail(); } catch (NullPointerException expected) {} } public void testBuilderOrderKeysBy() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.put("b", 3); builder.put("d", 2); builder.put("a", 5); builder.orderKeysBy(Collections.reverseOrder()); builder.put("c", 4); builder.put("a", 2); builder.put("b", 6); ImmutableListMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); ASSERT.that(multimap.values()).has().exactly(2, 4, 3, 6, 5, 2).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("b")).has().exactly(3, 6).inOrder(); } public void testBuilderOrderKeysByDuplicates() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.put("bb", 3); builder.put("d", 2); builder.put("a", 5); builder.orderKeysBy(new Ordering<String>() { @Override public int compare(String left, String right) { return left.length() - right.length(); } }); builder.put("cc", 4); builder.put("a", 2); builder.put("bb", 6); ImmutableListMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("d", "a", "bb", "cc").inOrder(); ASSERT.that(multimap.values()).has().exactly(2, 5, 2, 3, 6, 4).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("bb")).has().exactly(3, 6).inOrder(); } public void testBuilderOrderValuesBy() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.put("b", 3); builder.put("d", 2); builder.put("a", 5); builder.orderValuesBy(Collections.reverseOrder()); builder.put("c", 4); builder.put("a", 2); builder.put("b", 6); ImmutableListMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("b", "d", "a", "c").inOrder(); ASSERT.that(multimap.values()).has().exactly(6, 3, 2, 5, 2, 4).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("b")).has().exactly(6, 3).inOrder(); } public void testBuilderOrderKeysAndValuesBy() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.put("b", 3); builder.put("d", 2); builder.put("a", 5); builder.orderKeysBy(Collections.reverseOrder()); builder.orderValuesBy(Collections.reverseOrder()); builder.put("c", 4); builder.put("a", 2); builder.put("b", 6); ImmutableListMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); ASSERT.that(multimap.values()).has().exactly(2, 4, 6, 3, 5, 2).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("b")).has().exactly(6, 3).inOrder(); } public void testCopyOf() { ArrayListMultimap<String, Integer> input = ArrayListMultimap.create(); input.put("foo", 1); input.put("bar", 2); input.put("foo", 3); Multimap<String, Integer> multimap = ImmutableListMultimap.copyOf(input); assertEquals(multimap, input); assertEquals(input, multimap); } public void testCopyOfWithDuplicates() { ArrayListMultimap<String, Integer> input = ArrayListMultimap.create(); input.put("foo", 1); input.put("bar", 2); input.put("foo", 3); input.put("foo", 1); Multimap<String, Integer> multimap = ImmutableListMultimap.copyOf(input); assertEquals(multimap, input); assertEquals(input, multimap); } public void testCopyOfEmpty() { ArrayListMultimap<String, Integer> input = ArrayListMultimap.create(); Multimap<String, Integer> multimap = ImmutableListMultimap.copyOf(input); assertEquals(multimap, input); assertEquals(input, multimap); } public void testCopyOfImmutableListMultimap() { Multimap<String, Integer> multimap = createMultimap(); assertSame(multimap, ImmutableListMultimap.copyOf(multimap)); } public void testCopyOfNullKey() { ArrayListMultimap<String, Integer> input = ArrayListMultimap.create(); input.put(null, 1); try { ImmutableListMultimap.copyOf(input); fail(); } catch (NullPointerException expected) {} } public void testCopyOfNullValue() { ArrayListMultimap<String, Integer> input = ArrayListMultimap.create(); input.putAll("foo", Arrays.asList(1, null, 3)); try { ImmutableListMultimap.copyOf(input); fail(); } catch (NullPointerException expected) {} } public void testEmptyMultimapReads() { Multimap<String, Integer> multimap = ImmutableListMultimap.of(); assertFalse(multimap.containsKey("foo")); assertFalse(multimap.containsValue(1)); assertFalse(multimap.containsEntry("foo", 1)); assertTrue(multimap.entries().isEmpty()); assertTrue(multimap.equals(ArrayListMultimap.create())); assertEquals(Collections.emptyList(), multimap.get("foo")); assertEquals(0, multimap.hashCode()); assertTrue(multimap.isEmpty()); assertEquals(HashMultiset.create(), multimap.keys()); assertEquals(Collections.emptySet(), multimap.keySet()); assertEquals(0, multimap.size()); assertTrue(multimap.values().isEmpty()); assertEquals("{}", multimap.toString()); } public void testEmptyMultimapWrites() { Multimap<String, Integer> multimap = ImmutableListMultimap.of(); UnmodifiableCollectionTests.assertMultimapIsUnmodifiable( multimap, "foo", 1); } private Multimap<String, Integer> createMultimap() { return ImmutableListMultimap.<String, Integer>builder() .put("foo", 1).put("bar", 2).put("foo", 3).build(); } public void testMultimapReads() { Multimap<String, Integer> multimap = createMultimap(); assertTrue(multimap.containsKey("foo")); assertFalse(multimap.containsKey("cat")); assertTrue(multimap.containsValue(1)); assertFalse(multimap.containsValue(5)); assertTrue(multimap.containsEntry("foo", 1)); assertFalse(multimap.containsEntry("cat", 1)); assertFalse(multimap.containsEntry("foo", 5)); assertFalse(multimap.entries().isEmpty()); assertEquals(3, multimap.size()); assertFalse(multimap.isEmpty()); assertEquals("{foo=[1, 3], bar=[2]}", multimap.toString()); } public void testMultimapWrites() { Multimap<String, Integer> multimap = createMultimap(); UnmodifiableCollectionTests.assertMultimapIsUnmodifiable( multimap, "bar", 2); } public void testMultimapEquals() { Multimap<String, Integer> multimap = createMultimap(); Multimap<String, Integer> arrayListMultimap = ArrayListMultimap.create(); arrayListMultimap.putAll("foo", Arrays.asList(1, 3)); arrayListMultimap.put("bar", 2); new EqualsTester() .addEqualityGroup(multimap, createMultimap(), arrayListMultimap, ImmutableListMultimap.<String, Integer>builder() .put("bar", 2).put("foo", 1).put("foo", 3).build()) .addEqualityGroup(ImmutableListMultimap.<String, Integer>builder() .put("bar", 2).put("foo", 3).put("foo", 1).build()) .addEqualityGroup(ImmutableListMultimap.<String, Integer>builder() .put("foo", 2).put("foo", 3).put("foo", 1).build()) .addEqualityGroup(ImmutableListMultimap.<String, Integer>builder() .put("bar", 2).put("foo", 3).build()) .testEquals(); } public void testOf() { assertMultimapEquals( ImmutableListMultimap.of("one", 1), "one", 1); assertMultimapEquals( ImmutableListMultimap.of("one", 1, "two", 2), "one", 1, "two", 2); assertMultimapEquals( ImmutableListMultimap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3); assertMultimapEquals( ImmutableListMultimap.of("one", 1, "two", 2, "three", 3, "four", 4), "one", 1, "two", 2, "three", 3, "four", 4); assertMultimapEquals( ImmutableListMultimap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); } public void testInverse() { assertEquals( ImmutableListMultimap.<Integer, String>of(), ImmutableListMultimap.<String, Integer>of().inverse()); assertEquals( ImmutableListMultimap.of(1, "one"), ImmutableListMultimap.of("one", 1).inverse()); assertEquals( ImmutableListMultimap.of(1, "one", 2, "two"), ImmutableListMultimap.of("one", 1, "two", 2).inverse()); assertEquals( ImmutableListMultimap.of("of", 'o', "of", 'f', "to", 't', "to", 'o').inverse(), ImmutableListMultimap.of('o', "of", 'f', "of", 't', "to", 'o', "to")); assertEquals( ImmutableListMultimap.of('f', "foo", 'o', "foo", 'o', "foo"), ImmutableListMultimap.of("foo", 'f', "foo", 'o', "foo", 'o').inverse()); } public void testInverseMinimizesWork() { ImmutableListMultimap<String, Character> multimap = ImmutableListMultimap.<String, Character>builder() .put("foo", 'f') .put("foo", 'o') .put("foo", 'o') .put("poo", 'p') .put("poo", 'o') .put("poo", 'o') .build(); assertSame(multimap.inverse(), multimap.inverse()); assertSame(multimap, multimap.inverse().inverse()); } private static <K, V> void assertMultimapEquals(Multimap<K, V> multimap, Object... alternatingKeysAndValues) { assertEquals(multimap.size(), alternatingKeysAndValues.length / 2); int i = 0; for (Entry<K, V> entry : multimap.entries()) { assertEquals(alternatingKeysAndValues[i++], entry.getKey()); assertEquals(alternatingKeysAndValues[i++], entry.getValue()); } } }
Java
/* * Copyright (C) 2008 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.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.collect.Table.Cell; import com.google.common.collect.testing.MapInterfaceTest; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.TestSetGenerator; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.Feature; import junit.framework.TestCase; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; /** * Collection tests for {@link Table} implementations. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class TableCollectionTest extends TestCase { private static final Feature<?>[] COLLECTION_FEATURES = { CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_QUERIES }; private static final Feature<?>[] COLLECTION_FEATURES_ORDER = { CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, CollectionFeature.ALLOWS_NULL_QUERIES }; private static final Feature<?>[] COLLECTION_FEATURES_REMOVE = { CollectionSize.ANY, CollectionFeature.SUPPORTS_REMOVE, CollectionFeature.ALLOWS_NULL_QUERIES }; private static final Feature<?>[] COLLECTION_FEATURES_REMOVE_ORDER = { CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, CollectionFeature.SUPPORTS_REMOVE, CollectionFeature.ALLOWS_NULL_QUERIES }; private static void populateForRowKeySet( Table<String, Integer, Character> table, String[] elements) { for (String row : elements) { table.put(row, 1, 'a'); table.put(row, 2, 'b'); } } private static void populateForColumnKeySet( Table<Integer, String, Character> table, String[] elements) { for (String column : elements) { table.put(1, column, 'a'); table.put(2, column, 'b'); } } private static void populateForValues( Table<Integer, Character, String> table, String[] elements) { for (int i = 0; i < elements.length; i++) { table.put(i, 'a', elements[i]); } } private static abstract class TestCellSetGenerator implements TestSetGenerator<Cell<String, Integer, Character>> { @Override public SampleElements<Cell<String, Integer, Character>> samples() { return new SampleElements<Cell<String, Integer, Character>>( Tables.immutableCell("bar", 1, 'a'), Tables.immutableCell("bar", 2, 'b'), Tables.immutableCell("foo", 3, 'c'), Tables.immutableCell("bar", 1, 'b'), Tables.immutableCell("cat", 2, 'b')); } @Override public Set<Cell<String, Integer, Character>> create( Object... elements) { Table<String, Integer, Character> table = createTable(); for (Object element : elements) { @SuppressWarnings("unchecked") Cell<String, Integer, Character> cell = (Cell<String, Integer, Character>) element; table.put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); } return table.cellSet(); } abstract Table<String, Integer, Character> createTable(); @Override @SuppressWarnings("unchecked") public Cell<String, Integer, Character>[] createArray(int length) { return (Cell<String, Integer, Character>[]) new Cell<?, ?, ?>[length]; } @Override public List<Cell<String, Integer, Character>> order( List<Cell<String, Integer, Character>> insertionOrder) { return insertionOrder; } } private static abstract class MapTests extends MapInterfaceTest<String, Integer> { MapTests(boolean allowsNullValues, boolean supportsPut, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { super(false, allowsNullValues, supportsPut, supportsRemove, supportsClear, supportsIteratorRemove); } @Override protected String getKeyNotInPopulatedMap() { return "four"; } @Override protected Integer getValueNotInPopulatedMap() { return 4; } } private static abstract class RowTests extends MapTests { RowTests(boolean allowsNullValues, boolean supportsPut, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { super(allowsNullValues, supportsPut, supportsRemove, supportsClear, supportsIteratorRemove); } abstract Table<Character, String, Integer> makeTable(); @Override protected Map<String, Integer> makeEmptyMap() { return makeTable().row('a'); } @Override protected Map<String, Integer> makePopulatedMap() { Table<Character, String, Integer> table = makeTable(); table.put('a', "one", 1); table.put('a', "two", 2); table.put('a', "three", 3); table.put('b', "four", 4); return table.row('a'); } } public static class HashRowTests extends RowTests { public HashRowTests() { super(false, true, true, true, true); } @Override Table<Character, String, Integer> makeTable() { return HashBasedTable.create(); } } public static class TreeRowTests extends RowTests { public TreeRowTests() { super(false, true, true, true, true); } @Override Table<Character, String, Integer> makeTable() { return TreeBasedTable.create(); } } public static class TransposeRowTests extends RowTests { public TransposeRowTests() { super(false, true, true, true, false); } @Override Table<Character, String, Integer> makeTable() { Table<String, Character, Integer> original = TreeBasedTable.create(); return Tables.transpose(original); } } private static final Function<Integer, Integer> DIVIDE_BY_2 = new Function<Integer, Integer>() { @Override public Integer apply(Integer input) { return (input == null) ? null : input / 2; } }; public static class TransformValueRowTests extends RowTests { public TransformValueRowTests() { super(false, false, true, true, true); } @Override Table<Character, String, Integer> makeTable() { Table<Character, String, Integer> table = HashBasedTable.create(); return Tables.transformValues(table, DIVIDE_BY_2); } @Override protected Map<String, Integer> makePopulatedMap() { Table<Character, String, Integer> table = HashBasedTable.create(); table.put('a', "one", 2); table.put('a', "two", 4); table.put('a', "three", 6); table.put('b', "four", 8); return Tables.transformValues(table, DIVIDE_BY_2).row('a'); } } public static class UnmodifiableHashRowTests extends RowTests { public UnmodifiableHashRowTests() { super(false, false, false, false, false); } @Override Table<Character, String, Integer> makeTable() { Table<Character, String, Integer> table = HashBasedTable.create(); return Tables.unmodifiableTable(table); } @Override protected Map<String, Integer> makePopulatedMap() { Table<Character, String, Integer> table = HashBasedTable.create(); table.put('a', "one", 1); table.put('a', "two", 2); table.put('a', "three", 3); table.put('b', "four", 4); return Tables.unmodifiableTable(table).row('a'); } } public static class UnmodifiableTreeRowTests extends RowTests { public UnmodifiableTreeRowTests() { super(false, false, false, false, false); } @Override Table<Character, String, Integer> makeTable() { RowSortedTable<Character, String, Integer> table = TreeBasedTable.create(); return Tables.unmodifiableRowSortedTable(table); } @Override protected Map<String, Integer> makePopulatedMap() { RowSortedTable<Character, String, Integer> table = TreeBasedTable.create(); table.put('a', "one", 1); table.put('a', "two", 2); table.put('a', "three", 3); table.put('b', "four", 4); return Tables.unmodifiableRowSortedTable(table).row('a'); } } private static abstract class ColumnTests extends MapTests { ColumnTests(boolean allowsNullValues, boolean supportsPut, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { super(allowsNullValues, supportsPut, supportsRemove, supportsClear, supportsIteratorRemove); } abstract Table<String, Character, Integer> makeTable(); @Override protected Map<String, Integer> makeEmptyMap() { return makeTable().column('a'); } @Override protected Map<String, Integer> makePopulatedMap() { Table<String, Character, Integer> table = makeTable(); table.put("one", 'a', 1); table.put("two", 'a', 2); table.put("three", 'a', 3); table.put("four", 'b', 4); return table.column('a'); } } public static class HashColumnTests extends ColumnTests { public HashColumnTests() { super(false, true, true, true, false); } @Override Table<String, Character, Integer> makeTable() { return HashBasedTable.create(); } } public static class TreeColumnTests extends ColumnTests { public TreeColumnTests() { super(false, true, true, true, false); } @Override Table<String, Character, Integer> makeTable() { return TreeBasedTable.create(); } } public static class TransposeColumnTests extends ColumnTests { public TransposeColumnTests() { super(false, true, true, true, true); } @Override Table<String, Character, Integer> makeTable() { Table<Character, String, Integer> original = TreeBasedTable.create(); return Tables.transpose(original); } } public static class TransformValueColumnTests extends ColumnTests { public TransformValueColumnTests() { super(false, false, true, true, false); } @Override Table<String, Character, Integer> makeTable() { Table<String, Character, Integer> table = HashBasedTable.create(); return Tables.transformValues(table, DIVIDE_BY_2); } @Override protected Map<String, Integer> makePopulatedMap() { Table<String, Character, Integer> table = HashBasedTable.create(); table.put("one", 'a', 1); table.put("two", 'a', 2); table.put("three", 'a', 3); table.put("four", 'b', 4); return Tables.transformValues(table, DIVIDE_BY_2).column('a'); } } public static class UnmodifiableHashColumnTests extends ColumnTests { public UnmodifiableHashColumnTests() { super(false, false, false, false, false); } @Override Table<String, Character, Integer> makeTable() { Table<String, Character, Integer> table = HashBasedTable.create(); return Tables.unmodifiableTable(table); } @Override protected Map<String, Integer> makePopulatedMap() { Table<String, Character, Integer> table = HashBasedTable.create(); table.put("one", 'a', 1); table.put("two", 'a', 2); table.put("three", 'a', 3); table.put("four", 'b', 4); return Tables.unmodifiableTable(table).column('a'); } } public static class UnmodifiableTreeColumnTests extends ColumnTests { public UnmodifiableTreeColumnTests() { super(false, false, false, false, false); } @Override Table<String, Character, Integer> makeTable() { RowSortedTable<String, Character, Integer> table = TreeBasedTable.create(); return Tables.unmodifiableRowSortedTable(table); } @Override protected Map<String, Integer> makePopulatedMap() { RowSortedTable<String, Character, Integer> table = TreeBasedTable.create(); table.put("one", 'a', 1); table.put("two", 'a', 2); table.put("three", 'a', 3); table.put("four", 'b', 4); return Tables.unmodifiableRowSortedTable(table).column('a'); } } private static abstract class MapMapTests extends MapInterfaceTest<String, Map<Integer, Character>> { MapMapTests(boolean allowsNullValues, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { super(false, allowsNullValues, false, supportsRemove, supportsClear, supportsIteratorRemove); } @Override protected String getKeyNotInPopulatedMap() { return "cat"; } @Override protected Map<Integer, Character> getValueNotInPopulatedMap() { return ImmutableMap.of(); } /** * The version of this test supplied by {@link MapInterfaceTest} fails for * this particular map implementation, because {@code map.get()} returns a * view collection that changes in the course of a call to {@code remove()}. * Thus, the expectation doesn't hold that {@code map.remove(x)} returns the * same value which {@code map.get(x)} did immediately beforehand. */ @Override public void testRemove() { final Map<String, Map<Integer, Character>> map; final String keyToRemove; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } keyToRemove = map.keySet().iterator().next(); if (supportsRemove) { int initialSize = map.size(); map.get(keyToRemove); map.remove(keyToRemove); // This line doesn't hold - see the Javadoc comments above. // assertEquals(expectedValue, oldValue); assertFalse(map.containsKey(keyToRemove)); assertEquals(initialSize - 1, map.size()); } else { try { map.remove(keyToRemove); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } } private static abstract class RowMapTests extends MapMapTests { RowMapTests(boolean allowsNullValues, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { super(allowsNullValues, supportsRemove, supportsClear, supportsIteratorRemove); } abstract Table<String, Integer, Character> makeTable(); @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { Table<String, Integer, Character> table = makeTable(); populateTable(table); return table.rowMap(); } void populateTable(Table<String, Integer, Character> table) { table.put("foo", 1, 'a'); table.put("bar", 1, 'b'); table.put("foo", 3, 'c'); } @Override protected Map<String, Map<Integer, Character>> makeEmptyMap() { return makeTable().rowMap(); } } public static class HashRowMapTests extends RowMapTests { public HashRowMapTests() { super(false, true, true, true); } @Override Table<String, Integer, Character> makeTable() { return HashBasedTable.create(); } } public static class TreeRowMapTests extends RowMapTests { public TreeRowMapTests() { super(false, true, true, true); } @Override Table<String, Integer, Character> makeTable() { return TreeBasedTable.create(); } } public static class TreeRowMapHeadMapTests extends RowMapTests { public TreeRowMapHeadMapTests() { super(false, true, true, true); } @Override TreeBasedTable<String, Integer, Character> makeTable() { TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create(); table.put("z", 1, 'a'); return table; } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { TreeBasedTable<String, Integer, Character> table = makeTable(); populateTable(table); return table.rowMap().headMap("x"); } @Override protected Map<String, Map<Integer, Character>> makeEmptyMap() { return makeTable().rowMap().headMap("x"); } @Override protected String getKeyNotInPopulatedMap() { return "z"; } } public static class TreeRowMapTailMapTests extends RowMapTests { public TreeRowMapTailMapTests() { super(false, true, true, true); } @Override TreeBasedTable<String, Integer, Character> makeTable() { TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create(); table.put("a", 1, 'a'); return table; } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { TreeBasedTable<String, Integer, Character> table = makeTable(); populateTable(table); return table.rowMap().tailMap("b"); } @Override protected Map<String, Map<Integer, Character>> makeEmptyMap() { return makeTable().rowMap().tailMap("b"); } @Override protected String getKeyNotInPopulatedMap() { return "a"; } } public static class TreeRowMapSubMapTests extends RowMapTests { public TreeRowMapSubMapTests() { super(false, true, true, true); } @Override TreeBasedTable<String, Integer, Character> makeTable() { TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create(); table.put("a", 1, 'a'); table.put("z", 1, 'a'); return table; } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { TreeBasedTable<String, Integer, Character> table = makeTable(); populateTable(table); return table.rowMap().subMap("b", "x"); } @Override protected Map<String, Map<Integer, Character>> makeEmptyMap() { return makeTable().rowMap().subMap("b", "x"); } @Override protected String getKeyNotInPopulatedMap() { return "z"; } } private static final Function<String, Character> FIRST_CHARACTER = new Function<String, Character>() { @Override public Character apply(String input) { return input == null ? null : input.charAt(0); } }; public static class TransformValueRowMapTests extends RowMapTests { public TransformValueRowMapTests() { super(false, true, true, true); } @Override Table<String, Integer, Character> makeTable() { Table<String, Integer, String> original = HashBasedTable.create(); return Tables.transformValues(original, FIRST_CHARACTER); } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { Table<String, Integer, String> table = HashBasedTable.create(); table.put("foo", 1, "apple"); table.put("bar", 1, "banana"); table.put("foo", 3, "cat"); return Tables.transformValues(table, FIRST_CHARACTER).rowMap(); } } public static class UnmodifiableHashRowMapTests extends RowMapTests { public UnmodifiableHashRowMapTests() { super(false, false, false, false); } @Override Table<String, Integer, Character> makeTable() { Table<String, Integer, Character> original = HashBasedTable.create(); return Tables.unmodifiableTable(original); } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { Table<String, Integer, Character> table = HashBasedTable.create(); table.put("foo", 1, 'a'); table.put("bar", 1, 'b'); table.put("foo", 3, 'c'); return Tables.unmodifiableTable(table).rowMap(); } } public static class UnmodifiableTreeRowMapTests extends RowMapTests { public UnmodifiableTreeRowMapTests() { super(false, false, false, false); } @Override RowSortedTable<String, Integer, Character> makeTable() { RowSortedTable<String, Integer, Character> original = TreeBasedTable.create(); return Tables.unmodifiableRowSortedTable(original); } @Override protected SortedMap<String, Map<Integer, Character>> makePopulatedMap() { RowSortedTable<String, Integer, Character> table = TreeBasedTable.create(); table.put("foo", 1, 'a'); table.put("bar", 1, 'b'); table.put("foo", 3, 'c'); return Tables.unmodifiableRowSortedTable(table).rowMap(); } } private static abstract class ColumnMapTests extends MapMapTests { ColumnMapTests(boolean allowsNullValues, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { super(allowsNullValues, supportsRemove, supportsClear, supportsIteratorRemove); } abstract Table<Integer, String, Character> makeTable(); @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { Table<Integer, String, Character> table = makeTable(); table.put(1, "foo", 'a'); table.put(1, "bar", 'b'); table.put(3, "foo", 'c'); return table.columnMap(); } @Override protected Map<String, Map<Integer, Character>> makeEmptyMap() { return makeTable().columnMap(); } } public static class HashColumnMapTests extends ColumnMapTests { public HashColumnMapTests() { super(false, true, true, false); } @Override Table<Integer, String, Character> makeTable() { return HashBasedTable.create(); } } public static class TreeColumnMapTests extends ColumnMapTests { public TreeColumnMapTests() { super(false, true, true, false); } @Override Table<Integer, String, Character> makeTable() { return TreeBasedTable.create(); } } public static class TransformValueColumnMapTests extends ColumnMapTests { public TransformValueColumnMapTests() { super(false, true, true, false); } @Override Table<Integer, String, Character> makeTable() { Table<Integer, String, String> original = HashBasedTable.create(); return Tables.transformValues(original, FIRST_CHARACTER); } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { Table<Integer, String, String> table = HashBasedTable.create(); table.put(1, "foo", "apple"); table.put(1, "bar", "banana"); table.put(3, "foo", "cat"); return Tables.transformValues(table, FIRST_CHARACTER).columnMap(); } } public static class UnmodifiableHashColumnMapTests extends ColumnMapTests { public UnmodifiableHashColumnMapTests() { super(false, false, false, false); } @Override Table<Integer, String, Character> makeTable() { Table<Integer, String, Character> original = HashBasedTable.create(); return Tables.unmodifiableTable(original); } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { Table<Integer, String, Character> table = HashBasedTable.create(); table.put(1, "foo", 'a'); table.put(1, "bar", 'b'); table.put(3, "foo", 'c'); return Tables.unmodifiableTable(table).columnMap(); } } public static class UnmodifiableTreeColumnMapTests extends ColumnMapTests { public UnmodifiableTreeColumnMapTests() { super(false, false, false, false); } @Override Table<Integer, String, Character> makeTable() { RowSortedTable<Integer, String, Character> original = TreeBasedTable.create(); return Tables.unmodifiableRowSortedTable(original); } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { RowSortedTable<Integer, String, Character> table = TreeBasedTable.create(); table.put(1, "foo", 'a'); table.put(1, "bar", 'b'); table.put(3, "foo", 'c'); return Tables.unmodifiableRowSortedTable(table).columnMap(); } } }
Java
/* * Copyright (C) 2010 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.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.SortedLists.KeyAbsentBehavior; import com.google.common.collect.SortedLists.KeyPresentBehavior; import junit.framework.TestCase; import java.util.List; /** * Tests for SortedLists. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class SortedListsTest extends TestCase { private static final ImmutableList<Integer> LIST_WITH_DUPS = ImmutableList.of(1, 1, 2, 4, 4, 4, 8); private static final ImmutableList<Integer> LIST_WITHOUT_DUPS = ImmutableList.of(1, 2, 4, 8); void assertModelAgrees(List<Integer> list, Integer key, int answer, KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { switch (presentBehavior) { case FIRST_PRESENT: if (list.contains(key)) { assertEquals(list.indexOf(key), answer); return; } break; case LAST_PRESENT: if (list.contains(key)) { assertEquals(list.lastIndexOf(key), answer); return; } break; case ANY_PRESENT: if (list.contains(key)) { assertEquals(key, list.get(answer)); return; } break; case FIRST_AFTER: if (list.contains(key)) { assertEquals(list.lastIndexOf(key) + 1, answer); return; } break; case LAST_BEFORE: if (list.contains(key)) { assertEquals(list.indexOf(key) - 1, answer); return; } break; default: throw new AssertionError(); } // key is not present int nextHigherIndex = list.size(); for (int i = list.size() - 1; i >= 0 && list.get(i) > key; i--) { nextHigherIndex = i; } switch (absentBehavior) { case NEXT_LOWER: assertEquals(nextHigherIndex - 1, answer); return; case NEXT_HIGHER: assertEquals(nextHigherIndex, answer); return; case INVERTED_INSERTION_INDEX: assertEquals(-1 - nextHigherIndex, answer); return; default: throw new AssertionError(); } } public void testWithoutDups() { for (KeyPresentBehavior presentBehavior : KeyPresentBehavior.values()) { for (KeyAbsentBehavior absentBehavior : KeyAbsentBehavior.values()) { for (int key = 0; key <= 10; key++) { assertModelAgrees(LIST_WITHOUT_DUPS, key, SortedLists.binarySearch(LIST_WITHOUT_DUPS, key, presentBehavior, absentBehavior), presentBehavior, absentBehavior); } } } } public void testWithDups() { for (KeyPresentBehavior presentBehavior : KeyPresentBehavior.values()) { for (KeyAbsentBehavior absentBehavior : KeyAbsentBehavior.values()) { for (int key = 0; key <= 10; key++) { assertModelAgrees(LIST_WITH_DUPS, key, SortedLists.binarySearch(LIST_WITH_DUPS, key, presentBehavior, absentBehavior), presentBehavior, absentBehavior); } } } } }
Java
/* * Copyright (C) 2007 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.DerivedComparable; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collections; /** * Tests for {@link Multisets}. * * @author Mike Bostock * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class MultisetsTest extends TestCase { /* See MultisetsImmutableEntryTest for immutableEntry() tests. */ public void testNewTreeMultisetDerived() { TreeMultiset<DerivedComparable> set = TreeMultiset.create(); assertTrue(set.isEmpty()); set.add(new DerivedComparable("foo"), 2); set.add(new DerivedComparable("bar"), 3); ASSERT.that(set).has().exactly( new DerivedComparable("bar"), new DerivedComparable("bar"), new DerivedComparable("bar"), new DerivedComparable("foo"), new DerivedComparable("foo")).inOrder(); } public void testNewTreeMultisetNonGeneric() { TreeMultiset<LegacyComparable> set = TreeMultiset.create(); assertTrue(set.isEmpty()); set.add(new LegacyComparable("foo"), 2); set.add(new LegacyComparable("bar"), 3); ASSERT.that(set).has().exactly(new LegacyComparable("bar"), new LegacyComparable("bar"), new LegacyComparable("bar"), new LegacyComparable("foo"), new LegacyComparable("foo")).inOrder(); } public void testNewTreeMultisetComparator() { TreeMultiset<String> multiset = TreeMultiset.create(Collections.reverseOrder()); multiset.add("bar", 3); multiset.add("foo", 2); ASSERT.that(multiset).has().exactly("foo", "foo", "bar", "bar", "bar").inOrder(); } public void testRetainOccurrencesEmpty() { Multiset<String> multiset = HashMultiset.create(); Multiset<String> toRetain = HashMultiset.create(Arrays.asList("a", "b", "a")); assertFalse(Multisets.retainOccurrences(multiset, toRetain)); ASSERT.that(multiset).isEmpty(); } public void testRemoveOccurrencesEmpty() { Multiset<String> multiset = HashMultiset.create(); Multiset<String> toRemove = HashMultiset.create(Arrays.asList("a", "b", "a")); assertFalse(Multisets.retainOccurrences(multiset, toRemove)); assertTrue(multiset.isEmpty()); } public void testUnion() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create( Arrays.asList("a", "b", "b", "c")); ASSERT.that(Multisets.union(ms1, ms2)).has().exactly("a", "a", "b", "b", "c"); } public void testUnionEqualMultisets() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "a")); assertEquals(ms1, Multisets.union(ms1, ms2)); } public void testUnionEmptyNonempty() { Multiset<String> ms1 = HashMultiset.create(); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "a")); assertEquals(ms2, Multisets.union(ms1, ms2)); } public void testUnionNonemptyEmpty() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(); assertEquals(ms1, Multisets.union(ms1, ms2)); } public void testIntersectEmptyNonempty() { Multiset<String> ms1 = HashMultiset.create(); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "a")); ASSERT.that(Multisets.intersection(ms1, ms2)).isEmpty(); } public void testIntersectNonemptyEmpty() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(); ASSERT.that(Multisets.intersection(ms1, ms2)).isEmpty(); } public void testSum() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("b", "c")); ASSERT.that(Multisets.sum(ms1, ms2)).has().exactly("a", "a", "b", "b", "c"); } public void testSumEmptyNonempty() { Multiset<String> ms1 = HashMultiset.create(); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "a")); ASSERT.that(Multisets.sum(ms1, ms2)).has().exactly("a", "b", "a"); } public void testSumNonemptyEmpty() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(); ASSERT.that(Multisets.sum(ms1, ms2)).has().exactly("a", "b", "a"); } public void testDifferenceWithNoRemovedElements() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a")); ASSERT.that(Multisets.difference(ms1, ms2)).has().exactly("a", "b"); } public void testDifferenceWithRemovedElement() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("b")); ASSERT.that(Multisets.difference(ms1, ms2)).has().exactly("a", "a"); } public void testDifferenceWithMoreElementsInSecondMultiset() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "b", "b")); Multiset<String> diff = Multisets.difference(ms1, ms2); ASSERT.that(diff).has().item("a"); assertEquals(0, diff.count("b")); assertEquals(1, diff.count("a")); assertFalse(diff.contains("b")); assertTrue(diff.contains("a")); } public void testDifferenceEmptyNonempty() { Multiset<String> ms1 = HashMultiset.create(); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "a")); assertEquals(ms1, Multisets.difference(ms1, ms2)); } public void testDifferenceNonemptyEmpty() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(); assertEquals(ms1, Multisets.difference(ms1, ms2)); } public void testContainsOccurrencesEmpty() { Multiset<String> superMultiset = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> subMultiset = HashMultiset.create(); assertTrue(Multisets.containsOccurrences(superMultiset, subMultiset)); assertFalse(Multisets.containsOccurrences(subMultiset, superMultiset)); } public void testContainsOccurrences() { Multiset<String> superMultiset = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> subMultiset = HashMultiset.create(Arrays.asList("a", "b")); assertTrue(Multisets.containsOccurrences(superMultiset, subMultiset)); assertFalse(Multisets.containsOccurrences(subMultiset, superMultiset)); Multiset<String> diffMultiset = HashMultiset.create(Arrays.asList("a", "b", "c")); assertFalse(Multisets.containsOccurrences(superMultiset, diffMultiset)); assertTrue(Multisets.containsOccurrences(diffMultiset, subMultiset)); } public void testRetainEmptyOccurrences() { Multiset<String> multiset = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> toRetain = HashMultiset.create(); assertTrue(Multisets.retainOccurrences(multiset, toRetain)); assertTrue(multiset.isEmpty()); } public void testRetainOccurrences() { Multiset<String> multiset = TreeMultiset.create(Arrays.asList("a", "b", "a", "c")); Multiset<String> toRetain = HashMultiset.create(Arrays.asList("a", "b", "b")); assertTrue(Multisets.retainOccurrences(multiset, toRetain)); ASSERT.that(multiset).has().exactly("a", "b").inOrder(); } public void testRemoveEmptyOccurrences() { Multiset<String> multiset = TreeMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> toRemove = HashMultiset.create(); assertFalse(Multisets.removeOccurrences(multiset, toRemove)); ASSERT.that(multiset).has().exactly("a", "a", "b").inOrder(); } public void testRemoveOccurrences() { Multiset<String> multiset = TreeMultiset.create(Arrays.asList("a", "b", "a", "c")); Multiset<String> toRemove = HashMultiset.create(Arrays.asList("a", "b", "b")); assertTrue(Multisets.removeOccurrences(multiset, toRemove)); ASSERT.that(multiset).has().exactly("a", "c").inOrder(); } @SuppressWarnings("deprecation") public void testUnmodifiableMultisetShortCircuit() { Multiset<String> mod = HashMultiset.create(); Multiset<String> unmod = Multisets.unmodifiableMultiset(mod); assertNotSame(mod, unmod); assertSame(unmod, Multisets.unmodifiableMultiset(unmod)); ImmutableMultiset<String> immutable = ImmutableMultiset.of("a", "a", "b", "a"); assertSame(immutable, Multisets.unmodifiableMultiset(immutable)); assertSame(immutable, Multisets.unmodifiableMultiset((Multiset<String>) immutable)); } public void testHighestCountFirst() { Multiset<String> multiset = HashMultiset.create( Arrays.asList("a", "a", "a", "b", "c", "c")); ImmutableMultiset<String> sortedMultiset = Multisets.copyHighestCountFirst(multiset); ASSERT.that(sortedMultiset.entrySet()).has().exactly( Multisets.immutableEntry("a", 3), Multisets.immutableEntry("c", 2), Multisets.immutableEntry("b", 1)).inOrder(); ASSERT.that(sortedMultiset).has().exactly( "a", "a", "a", "c", "c", "b").inOrder(); ASSERT.that(Multisets.copyHighestCountFirst(ImmutableMultiset.of())).isEmpty(); } }
Java
/* * Copyright (C) 2008 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.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * Unit tests for {@link ImmutableSortedSet}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class ImmutableSortedSetTest extends AbstractImmutableSetTest { // enum singleton pattern private enum StringLengthComparator implements Comparator<String> { INSTANCE; @Override public int compare(String a, String b) { return a.length() - b.length(); } } private static final Comparator<String> STRING_LENGTH = StringLengthComparator.INSTANCE; @Override protected SortedSet<String> of() { return ImmutableSortedSet.of(); } @Override protected SortedSet<String> of(String e) { return ImmutableSortedSet.of(e); } @Override protected SortedSet<String> of(String e1, String e2) { return ImmutableSortedSet.of(e1, e2); } @Override protected SortedSet<String> of(String e1, String e2, String e3) { return ImmutableSortedSet.of(e1, e2, e3); } @Override protected SortedSet<String> of( String e1, String e2, String e3, String e4) { return ImmutableSortedSet.of(e1, e2, e3, e4); } @Override protected SortedSet<String> of( String e1, String e2, String e3, String e4, String e5) { return ImmutableSortedSet.of(e1, e2, e3, e4, e5); } @Override protected SortedSet<String> of(String e1, String e2, String e3, String e4, String e5, String e6, String... rest) { return ImmutableSortedSet.of(e1, e2, e3, e4, e5, e6, rest); } @Override protected SortedSet<String> copyOf(String[] elements) { return ImmutableSortedSet.copyOf(elements); } @Override protected SortedSet<String> copyOf(Collection<String> elements) { return ImmutableSortedSet.copyOf(elements); } @Override protected SortedSet<String> copyOf(Iterable<String> elements) { return ImmutableSortedSet.copyOf(elements); } @Override protected SortedSet<String> copyOf(Iterator<String> elements) { return ImmutableSortedSet.copyOf(elements); } public void testEmpty_comparator() { SortedSet<String> set = of(); assertSame(Ordering.natural(), set.comparator()); } public void testEmpty_headSet() { SortedSet<String> set = of(); assertSame(set, set.headSet("c")); } public void testEmpty_tailSet() { SortedSet<String> set = of(); assertSame(set, set.tailSet("f")); } public void testEmpty_subSet() { SortedSet<String> set = of(); assertSame(set, set.subSet("c", "f")); } public void testEmpty_first() { SortedSet<String> set = of(); try { set.first(); fail(); } catch (NoSuchElementException expected) { } } public void testEmpty_last() { SortedSet<String> set = of(); try { set.last(); fail(); } catch (NoSuchElementException expected) { } } public void testSingle_comparator() { SortedSet<String> set = of("e"); assertSame(Ordering.natural(), set.comparator()); } public void testSingle_headSet() { SortedSet<String> set = of("e"); assertTrue(set.headSet("g") instanceof ImmutableSortedSet); ASSERT.that(set.headSet("g")).has().item("e"); assertSame(of(), set.headSet("c")); assertSame(of(), set.headSet("e")); } public void testSingle_tailSet() { SortedSet<String> set = of("e"); assertTrue(set.tailSet("c") instanceof ImmutableSortedSet); ASSERT.that(set.tailSet("c")).has().item("e"); ASSERT.that(set.tailSet("e")).has().item("e"); assertSame(of(), set.tailSet("g")); } public void testSingle_subSet() { SortedSet<String> set = of("e"); assertTrue(set.subSet("c", "g") instanceof ImmutableSortedSet); ASSERT.that(set.subSet("c", "g")).has().item("e"); ASSERT.that(set.subSet("e", "g")).has().item("e"); assertSame(of(), set.subSet("f", "g")); assertSame(of(), set.subSet("c", "e")); assertSame(of(), set.subSet("c", "d")); } public void testSingle_first() { SortedSet<String> set = of("e"); assertEquals("e", set.first()); } public void testSingle_last() { SortedSet<String> set = of("e"); assertEquals("e", set.last()); } public void testOf_ordering() { SortedSet<String> set = of("e", "a", "f", "b", "d", "c"); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } /* * Tests that we workaround GWT bug #3621 (or that it is already fixed). * * A call to of() with a parameter that is not a plain Object[] (here, * Interface[]) creates a RegularImmutableSortedSet backed by an array of that * type. Later, RegularImmutableSortedSet.toArray() calls System.arraycopy() * to copy from that array to the destination array. This would be fine, but * GWT has a bug: It refuses to copy from an E[] to an Object[] when E is an * interface type. */ // TODO: test other collections for this problem public void testOf_gwtArraycopyBug() { /* * The test requires: * * 1) An interface I extending Comparable<I> so that the created array is of * an interface type. 2) An instance of a class implementing that interface * so that we can pass non-null instances of the interface. * * (Currently it's safe to pass instances for which compareTo() always * returns 0, but if we had a SingletonImmutableSortedSet, this might no * longer be the case.) * * javax.naming.Name and java.util.concurrent.Delayed might work, but * they're fairly obscure, we've invented our own interface and class. */ Interface a = new Impl(); Interface b = new Impl(); ImmutableSortedSet<Interface> set = ImmutableSortedSet.of(a, b); set.toArray(); set.toArray(new Object[2]); } interface Interface extends Comparable<Interface> { } static class Impl implements Interface { static int nextId; Integer id = nextId++; @Override public int compareTo(Interface other) { return id.compareTo(((Impl) other).id); } } public void testOf_ordering_dupes() { SortedSet<String> set = of("e", "a", "e", "f", "b", "b", "d", "a", "c"); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testOf_comparator() { SortedSet<String> set = of("e", "a", "f", "b", "d", "c"); assertSame(Ordering.natural(), set.comparator()); } public void testOf_headSet() { SortedSet<String> set = of("e", "f", "b", "d", "c"); assertTrue(set.headSet("e") instanceof ImmutableSortedSet); ASSERT.that(set.headSet("e")).has().exactly("b", "c", "d").inOrder(); ASSERT.that(set.headSet("g")).has().exactly("b", "c", "d", "e", "f").inOrder(); assertSame(of(), set.headSet("a")); assertSame(of(), set.headSet("b")); } public void testOf_tailSet() { SortedSet<String> set = of("e", "f", "b", "d", "c"); assertTrue(set.tailSet("e") instanceof ImmutableSortedSet); ASSERT.that(set.tailSet("e")).has().exactly("e", "f").inOrder(); ASSERT.that(set.tailSet("a")).has().exactly("b", "c", "d", "e", "f").inOrder(); assertSame(of(), set.tailSet("g")); } public void testOf_subSet() { SortedSet<String> set = of("e", "f", "b", "d", "c"); assertTrue(set.subSet("c", "e") instanceof ImmutableSortedSet); ASSERT.that(set.subSet("c", "e")).has().exactly("c", "d").inOrder(); ASSERT.that(set.subSet("a", "g")).has().exactly("b", "c", "d", "e", "f").inOrder(); assertSame(of(), set.subSet("a", "b")); assertSame(of(), set.subSet("g", "h")); assertSame(of(), set.subSet("c", "c")); try { set.subSet("e", "c"); fail(); } catch (IllegalArgumentException expected) { } } public void testOf_first() { SortedSet<String> set = of("e", "f", "b", "d", "c"); assertEquals("b", set.first()); } public void testOf_last() { SortedSet<String> set = of("e", "f", "b", "d", "c"); assertEquals("f", set.last()); } /* "Explicit" indicates an explicit comparator. */ public void testExplicit_ordering() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testExplicit_ordering_dupes() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "brown", "fox", "jumped", "over", "a", "lazy", "dog").build(); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testExplicit_contains() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertTrue(set.contains("quick")); assertTrue(set.contains("google")); assertFalse(set.contains("")); assertFalse(set.contains("california")); assertFalse(set.contains(null)); } public void testExplicit_containsMismatchedTypes() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertFalse(set.contains(3.7)); } public void testExplicit_comparator() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertSame(STRING_LENGTH, set.comparator()); } public void testExplicit_headSet() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertTrue(set.headSet("a") instanceof ImmutableSortedSet); assertTrue(set.headSet("fish") instanceof ImmutableSortedSet); ASSERT.that(set.headSet("fish")).has().exactly("a", "in", "the").inOrder(); ASSERT.that(set.headSet("california")).has() .exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); assertTrue(set.headSet("a").isEmpty()); assertTrue(set.headSet("").isEmpty()); } public void testExplicit_tailSet() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertTrue(set.tailSet("california") instanceof ImmutableSortedSet); assertTrue(set.tailSet("fish") instanceof ImmutableSortedSet); ASSERT.that(set.tailSet("fish")).has().exactly("over", "quick", "jumped").inOrder(); ASSERT.that( set.tailSet("a")).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); assertTrue(set.tailSet("california").isEmpty()); } public void testExplicit_subSet() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertTrue(set.subSet("the", "quick") instanceof ImmutableSortedSet); assertTrue(set.subSet("", "b") instanceof ImmutableSortedSet); ASSERT.that(set.subSet("the", "quick")).has().exactly("the", "over").inOrder(); ASSERT.that(set.subSet("a", "california")) .has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); assertTrue(set.subSet("", "b").isEmpty()); assertTrue(set.subSet("vermont", "california").isEmpty()); assertTrue(set.subSet("aaa", "zzz").isEmpty()); try { set.subSet("quick", "the"); fail(); } catch (IllegalArgumentException expected) { } } public void testExplicit_first() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertEquals("a", set.first()); } public void testExplicit_last() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertEquals("jumped", set.last()); } public void testCopyOf_ordering() { SortedSet<String> set = copyOf(asList("e", "a", "f", "b", "d", "c")); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_ordering_dupes() { SortedSet<String> set = copyOf(asList("e", "a", "e", "f", "b", "b", "d", "a", "c")); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_subSet() { SortedSet<String> set = of("e", "a", "f", "b", "d", "c"); SortedSet<String> subset = set.subSet("c", "e"); SortedSet<String> copy = copyOf(subset); assertEquals(subset, copy); } public void testCopyOf_headSet() { SortedSet<String> set = of("e", "a", "f", "b", "d", "c"); SortedSet<String> headset = set.headSet("d"); SortedSet<String> copy = copyOf(headset); assertEquals(headset, copy); } public void testCopyOf_tailSet() { SortedSet<String> set = of("e", "a", "f", "b", "d", "c"); SortedSet<String> tailset = set.tailSet("d"); SortedSet<String> copy = copyOf(tailset); assertEquals(tailset, copy); } public void testCopyOf_comparator() { SortedSet<String> set = copyOf(asList("e", "a", "f", "b", "d", "c")); assertSame(Ordering.natural(), set.comparator()); } public void testCopyOf_iterator_ordering() { SortedSet<String> set = copyOf(asIterator("e", "a", "f", "b", "d", "c")); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_iterator_ordering_dupes() { SortedSet<String> set = copyOf(asIterator("e", "a", "e", "f", "b", "b", "d", "a", "c")); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_iterator_comparator() { SortedSet<String> set = copyOf(asIterator("e", "a", "f", "b", "d", "c")); assertSame(Ordering.natural(), set.comparator()); } public void testCopyOf_sortedSet_ordering() { SortedSet<String> set = copyOf(Sets.newTreeSet(asList("e", "a", "f", "b", "d", "c"))); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_sortedSet_comparator() { SortedSet<String> set = copyOf(Sets.<String>newTreeSet()); assertSame(Ordering.natural(), set.comparator()); } public void testCopyOfExplicit_ordering() { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asList( "in", "the", "quick", "jumped", "over", "a")); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testCopyOfExplicit_ordering_dupes() { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asList( "in", "the", "quick", "brown", "fox", "jumped", "over", "a", "lazy", "dog")); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testCopyOfExplicit_comparator() { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asList( "in", "the", "quick", "jumped", "over", "a")); assertSame(STRING_LENGTH, set.comparator()); } public void testCopyOfExplicit_iterator_ordering() { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asIterator( "in", "the", "quick", "jumped", "over", "a")); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testCopyOfExplicit_iterator_ordering_dupes() { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asIterator( "in", "the", "quick", "brown", "fox", "jumped", "over", "a", "lazy", "dog")); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testCopyOfExplicit_iterator_comparator() { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asIterator( "in", "the", "quick", "jumped", "over", "a")); assertSame(STRING_LENGTH, set.comparator()); } public void testCopyOf_sortedSetIterable() { SortedSet<String> input = Sets.newTreeSet(STRING_LENGTH); Collections.addAll(input, "in", "the", "quick", "jumped", "over", "a"); SortedSet<String> set = copyOf(input); ASSERT.that(set).has().exactly("a", "in", "jumped", "over", "quick", "the").inOrder(); } public void testCopyOfSorted_natural_ordering() { SortedSet<String> input = Sets.newTreeSet( asList("in", "the", "quick", "jumped", "over", "a")); SortedSet<String> set = ImmutableSortedSet.copyOfSorted(input); ASSERT.that(set).has().exactly("a", "in", "jumped", "over", "quick", "the").inOrder(); } public void testCopyOfSorted_natural_comparator() { SortedSet<String> input = Sets.newTreeSet(asList("in", "the", "quick", "jumped", "over", "a")); SortedSet<String> set = ImmutableSortedSet.copyOfSorted(input); assertSame(Ordering.natural(), set.comparator()); } public void testCopyOfSorted_explicit_ordering() { SortedSet<String> input = Sets.newTreeSet(STRING_LENGTH); Collections.addAll(input, "in", "the", "quick", "jumped", "over", "a"); SortedSet<String> set = ImmutableSortedSet.copyOfSorted(input); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); assertSame(STRING_LENGTH, set.comparator()); } public void testEquals_bothDefaultOrdering() { SortedSet<String> set = of("a", "b", "c"); assertEquals(set, Sets.newTreeSet(asList("a", "b", "c"))); assertEquals(Sets.newTreeSet(asList("a", "b", "c")), set); assertFalse(set.equals(Sets.newTreeSet(asList("a", "b", "d")))); assertFalse(Sets.newTreeSet(asList("a", "b", "d")).equals(set)); assertFalse(set.equals(Sets.newHashSet(4, 5, 6))); assertFalse(Sets.newHashSet(4, 5, 6).equals(set)); } public void testEquals_bothExplicitOrdering() { SortedSet<String> set = of("in", "the", "a"); assertEquals(Sets.newTreeSet(asList("in", "the", "a")), set); assertFalse(set.equals(Sets.newTreeSet(asList("in", "the", "house")))); assertFalse(Sets.newTreeSet(asList("in", "the", "house")).equals(set)); assertFalse(set.equals(Sets.newHashSet(4, 5, 6))); assertFalse(Sets.newHashSet(4, 5, 6).equals(set)); Set<String> complex = Sets.newTreeSet(STRING_LENGTH); Collections.addAll(complex, "in", "the", "a"); assertEquals(set, complex); } public void testEquals_bothDefaultOrdering_StringVsInt() { SortedSet<String> set = of("a", "b", "c"); assertFalse(set.equals(Sets.newTreeSet(asList(4, 5, 6)))); assertNotEqualLenient(Sets.newTreeSet(asList(4, 5, 6)), set); } public void testEquals_bothExplicitOrdering_StringVsInt() { SortedSet<String> set = of("in", "the", "a"); assertFalse(set.equals(Sets.newTreeSet(asList(4, 5, 6)))); assertNotEqualLenient(Sets.newTreeSet(asList(4, 5, 6)), set); } public void testContainsAll_notSortedSet() { SortedSet<String> set = of("a", "b", "f"); assertTrue(set.containsAll(Collections.emptyList())); assertTrue(set.containsAll(asList("b"))); assertTrue(set.containsAll(asList("b", "b"))); assertTrue(set.containsAll(asList("b", "f"))); assertTrue(set.containsAll(asList("b", "f", "a"))); assertFalse(set.containsAll(asList("d"))); assertFalse(set.containsAll(asList("z"))); assertFalse(set.containsAll(asList("b", "d"))); assertFalse(set.containsAll(asList("f", "d", "a"))); } public void testContainsAll_sameComparator() { SortedSet<String> set = of("a", "b", "f"); assertTrue(set.containsAll(Sets.newTreeSet())); assertTrue(set.containsAll(Sets.newTreeSet(asList("b")))); assertTrue(set.containsAll(Sets.newTreeSet(asList("a", "f")))); assertTrue(set.containsAll(Sets.newTreeSet(asList("a", "b", "f")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("d")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("z")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("b", "d")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("f", "d", "a")))); } public void testContainsAll_sameComparator_StringVsInt() { SortedSet<String> set = of("a", "b", "f"); SortedSet<Integer> unexpected = Sets.newTreeSet(Ordering.natural()); unexpected.addAll(asList(1, 2, 3)); assertFalse(set.containsAll(unexpected)); } public void testContainsAll_differentComparator() { Comparator<Comparable<?>> comparator = Collections.reverseOrder(); SortedSet<String> set = new ImmutableSortedSet.Builder<String>(comparator) .add("a", "b", "f").build(); assertTrue(set.containsAll(Sets.newTreeSet())); assertTrue(set.containsAll(Sets.newTreeSet(asList("b")))); assertTrue(set.containsAll(Sets.newTreeSet(asList("a", "f")))); assertTrue(set.containsAll(Sets.newTreeSet(asList("a", "b", "f")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("d")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("z")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("b", "d")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("f", "d", "a")))); } public void testReverseOrder() { SortedSet<String> set = ImmutableSortedSet.<String>reverseOrder() .add("a", "b", "c").build(); ASSERT.that(set).has().exactly("c", "b", "a").inOrder(); assertEquals(Ordering.natural().reverse(), set.comparator()); } private static final Comparator<Object> TO_STRING = new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } }; public void testSupertypeComparator() { SortedSet<Integer> set = new ImmutableSortedSet.Builder<Integer>(TO_STRING) .add(3, 12, 101, 44).build(); ASSERT.that(set).has().exactly(101, 12, 3, 44).inOrder(); } public void testSupertypeComparatorSubtypeElements() { SortedSet<Number> set = new ImmutableSortedSet.Builder<Number>(TO_STRING) .add(3, 12, 101, 44).build(); ASSERT.that(set).has().exactly(101, 12, 3, 44).inOrder(); } @Override <E extends Comparable<E>> ImmutableSortedSet.Builder<E> builder() { return ImmutableSortedSet.naturalOrder(); } @Override int getComplexBuilderSetLastElement() { return 0x00FFFFFF; } public void testLegacyComparable_of() { ImmutableSortedSet<LegacyComparable> set0 = ImmutableSortedSet.of(); @SuppressWarnings("unchecked") // using a legacy comparable ImmutableSortedSet<LegacyComparable> set1 = ImmutableSortedSet.of( LegacyComparable.Z); @SuppressWarnings("unchecked") // using a legacy comparable ImmutableSortedSet<LegacyComparable> set2 = ImmutableSortedSet.of( LegacyComparable.Z, LegacyComparable.Y); } public void testLegacyComparable_copyOf_collection() { ImmutableSortedSet<LegacyComparable> set = ImmutableSortedSet.copyOf(LegacyComparable.VALUES_BACKWARD); assertTrue(Iterables.elementsEqual(LegacyComparable.VALUES_FORWARD, set)); } public void testLegacyComparable_copyOf_iterator() { ImmutableSortedSet<LegacyComparable> set = ImmutableSortedSet.copyOf( LegacyComparable.VALUES_BACKWARD.iterator()); assertTrue(Iterables.elementsEqual(LegacyComparable.VALUES_FORWARD, set)); } public void testLegacyComparable_builder_natural() { @SuppressWarnings("unchecked") // Note: IntelliJ wrongly reports an error for this statement ImmutableSortedSet.Builder<LegacyComparable> builder = ImmutableSortedSet.<LegacyComparable>naturalOrder(); builder.addAll(LegacyComparable.VALUES_BACKWARD); builder.add(LegacyComparable.X); builder.add(LegacyComparable.Y, LegacyComparable.Z); ImmutableSortedSet<LegacyComparable> set = builder.build(); assertTrue(Iterables.elementsEqual(LegacyComparable.VALUES_FORWARD, set)); } public void testLegacyComparable_builder_reverse() { @SuppressWarnings("unchecked") // Note: IntelliJ wrongly reports an error for this statement ImmutableSortedSet.Builder<LegacyComparable> builder = ImmutableSortedSet.<LegacyComparable>reverseOrder(); builder.addAll(LegacyComparable.VALUES_FORWARD); builder.add(LegacyComparable.X); builder.add(LegacyComparable.Y, LegacyComparable.Z); ImmutableSortedSet<LegacyComparable> set = builder.build(); assertTrue(Iterables.elementsEqual(LegacyComparable.VALUES_BACKWARD, set)); } @SuppressWarnings({"deprecation", "static-access"}) public void testBuilderMethod() { try { ImmutableSortedSet.builder(); fail(); } catch (UnsupportedOperationException expected) { } } public void testAsList() { ImmutableSet<String> set = ImmutableSortedSet.of("a", "e", "i", "o", "u"); ImmutableList<String> list = set.asList(); assertEquals(ImmutableList.of("a", "e", "i", "o", "u"), list); assertSame(list, ImmutableList.copyOf(set)); } public void testSubsetAsList() { ImmutableSet<String> set = ImmutableSortedSet.of("a", "e", "i", "o", "u").subSet("c", "r"); ImmutableList<String> list = set.asList(); assertEquals(ImmutableList.of("e", "i", "o"), list); assertEquals(list, ImmutableList.copyOf(set)); } public void testAsListInconsistentComprator() { ImmutableSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); ImmutableList<String> list = set.asList(); assertTrue(list.contains("the")); assertEquals(2, list.indexOf("the")); assertEquals(2, list.lastIndexOf("the")); assertFalse(list.contains("dog")); assertEquals(-1, list.indexOf("dog")); assertEquals(-1, list.lastIndexOf("dog")); assertFalse(list.contains("chicken")); assertEquals(-1, list.indexOf("chicken")); assertEquals(-1, list.lastIndexOf("chicken")); } private static <E> Iterator<E> asIterator(E... elements) { return asList(elements).iterator(); } // In GWT, java.util.TreeSet throws ClassCastException when the comparator // throws it, unlike JDK6. Therefore, we accept ClassCastException as a // valid result thrown by java.util.TreeSet#equals. private static void assertNotEqualLenient( TreeSet<?> unexpected, SortedSet<?> actual) { try { ASSERT.that(actual).isNotEqualTo(unexpected); } catch (ClassCastException accepted) { } } public void testHeadSetInclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { ASSERT.that(set.headSet(strings[i], true)) .has().exactlyAs(sortedNumberNames(0, i + 1)).inOrder(); } } public void testHeadSetExclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { ASSERT.that(set.headSet(strings[i], false)).has().exactlyAs( sortedNumberNames(0, i)).inOrder(); } } public void testTailSetInclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { ASSERT.that(set.tailSet(strings[i], true)).has().exactlyAs( sortedNumberNames(i, strings.length)).inOrder(); } } public void testTailSetExclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { ASSERT.that(set.tailSet(strings[i], false)).has().exactlyAs( sortedNumberNames(i + 1, strings.length)).inOrder(); } } public void testSubSetExclusiveExclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { for (int j = i; j < strings.length; j++) { ASSERT.that(set.subSet(strings[i], false, strings[j], false)) .has().exactlyAs(sortedNumberNames(Math.min(i + 1, j), j)).inOrder(); } } } public void testSubSetInclusiveExclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { for (int j = i; j < strings.length; j++) { ASSERT.that(set.subSet(strings[i], true, strings[j], false)) .has().exactlyAs(sortedNumberNames(i, j)).inOrder(); } } } public void testSubSetExclusiveInclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { for (int j = i; j < strings.length; j++) { ASSERT.that(set.subSet(strings[i], false, strings[j], true)) .has().exactlyAs(sortedNumberNames(i + 1, j + 1)).inOrder(); } } } public void testSubSetInclusiveInclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { for (int j = i; j < strings.length; j++) { ASSERT.that(set.subSet(strings[i], true, strings[j], true)) .has().exactlyAs(sortedNumberNames(i, j + 1)).inOrder(); } } } private static ImmutableList<String> sortedNumberNames(int i, int j) { return ImmutableList.copyOf(SORTED_NUMBER_NAMES.subList(i, j)); } private static final ImmutableList<String> NUMBER_NAMES = ImmutableList.of("one", "two", "three", "four", "five", "six", "seven"); private static final ImmutableList<String> SORTED_NUMBER_NAMES = Ordering.natural().immutableSortedCopy(NUMBER_NAMES); private static class SelfComparableExample implements Comparable<SelfComparableExample> { @Override public int compareTo(SelfComparableExample o) { return 0; } } public void testBuilderGenerics_SelfComparable() { ImmutableSortedSet.Builder<SelfComparableExample> natural = ImmutableSortedSet.naturalOrder(); ImmutableSortedSet.Builder<SelfComparableExample> reverse = ImmutableSortedSet.reverseOrder(); } private static class SuperComparableExample extends SelfComparableExample {} public void testBuilderGenerics_SuperComparable() { ImmutableSortedSet.Builder<SuperComparableExample> natural = ImmutableSortedSet.naturalOrder(); ImmutableSortedSet.Builder<SuperComparableExample> reverse = ImmutableSortedSet.reverseOrder(); } }
Java
/* * Copyright (C) 2011 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Optional; import junit.framework.TestCase; import java.util.Arrays; import java.util.List; import javax.annotation.Nullable; /** * Tests for {@code TreeTraverser}. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class TreeTraverserTest extends TestCase { private static final class Tree { final char value; final List<Tree> children; public Tree(char value, Tree... children) { this.value = value; this.children = Arrays.asList(children); } } private static final class BinaryTree { final char value; @Nullable final BinaryTree left; @Nullable final BinaryTree right; private BinaryTree(char value, BinaryTree left, BinaryTree right) { this.value = value; this.left = left; this.right = right; } } private static final TreeTraverser<Tree> ADAPTER = new TreeTraverser<Tree>() { @Override public Iterable<Tree> children(Tree node) { return node.children; } }; private static final BinaryTreeTraverser<BinaryTree> BIN_ADAPTER = new BinaryTreeTraverser<BinaryTree>() { @Override public Optional<BinaryTree> leftChild(BinaryTree node) { return Optional.fromNullable(node.left); } @Override public Optional<BinaryTree> rightChild(BinaryTree node) { return Optional.fromNullable(node.right); } }; // h // / | \ // / e \ // d g // /|\ | // / | \ f // a b c static final Tree a = new Tree('a'); static final Tree b = new Tree('b'); static final Tree c = new Tree('c'); static final Tree d = new Tree('d', a, b, c); static final Tree e = new Tree('e'); static final Tree f = new Tree('f'); static final Tree g = new Tree('g', f); static final Tree h = new Tree('h', d, e, g); // d // / \ // b e // / \ \ // a c f // / // g static final BinaryTree ba = new BinaryTree('a', null, null); static final BinaryTree bc = new BinaryTree('c', null, null); static final BinaryTree bb = new BinaryTree('b', ba, bc); static final BinaryTree bg = new BinaryTree('g', null, null); static final BinaryTree bf = new BinaryTree('f', bg, null); static final BinaryTree be = new BinaryTree('e', null, bf); static final BinaryTree bd = new BinaryTree('d', bb, be); static String iterationOrder(Iterable<Tree> iterable) { StringBuilder builder = new StringBuilder(); for (Tree t : iterable) { builder.append(t.value); } return builder.toString(); } static String binaryIterationOrder(Iterable<BinaryTree> iterable) { StringBuilder builder = new StringBuilder(); for (BinaryTree t : iterable) { builder.append(t.value); } return builder.toString(); } public void testPreOrder() { ASSERT.that(iterationOrder(ADAPTER.preOrderTraversal(h))).is("hdabcegf"); ASSERT.that(binaryIterationOrder(BIN_ADAPTER.preOrderTraversal(bd))).is("dbacefg"); } public void testPostOrder() { ASSERT.that(iterationOrder(ADAPTER.postOrderTraversal(h))).is("abcdefgh"); ASSERT.that(binaryIterationOrder(BIN_ADAPTER.postOrderTraversal(bd))).is("acbgfed"); } public void testBreadthOrder() { ASSERT.that(iterationOrder(ADAPTER.breadthFirstTraversal(h))).is("hdegabcf"); ASSERT.that(binaryIterationOrder(BIN_ADAPTER.breadthFirstTraversal(bd))).is("dbeacfg"); } public void testInOrder() { ASSERT.that(binaryIterationOrder(BIN_ADAPTER.inOrderTraversal(bd))).is("abcdegf"); } }
Java
/* * Copyright (C) 2008 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableBiMap.Builder; import com.google.common.collect.testing.MapInterfaceTest; import junit.framework.TestCase; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Tests for {@link ImmutableBiMap}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class ImmutableBiMapTest extends TestCase { // TODO: Reduce duplication of ImmutableMapTest code public static abstract class AbstractMapTests<K, V> extends MapInterfaceTest<K, V> { public AbstractMapTests() { super(false, false, false, false, false); } @Override protected Map<K, V> makeEmptyMap() { throw new UnsupportedOperationException(); } private static final Joiner joiner = Joiner.on(", "); @Override protected void assertMoreInvariants(Map<K, V> map) { BiMap<K, V> bimap = (BiMap<K, V>) map; for (Entry<K, V> entry : map.entrySet()) { assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString()); assertEquals(entry.getKey(), bimap.inverse().get(entry.getValue())); } assertEquals("{" + joiner.join(map.entrySet()) + "}", map.toString()); assertEquals("[" + joiner.join(map.entrySet()) + "]", map.entrySet().toString()); assertEquals("[" + joiner.join(map.keySet()) + "]", map.keySet().toString()); assertEquals("[" + joiner.join(map.values()) + "]", map.values().toString()); assertEquals(Sets.newHashSet(map.entrySet()), map.entrySet()); assertEquals(Sets.newHashSet(map.keySet()), map.keySet()); } } public static class MapTests extends AbstractMapTests<String, Integer> { @Override protected Map<String, Integer> makeEmptyMap() { return ImmutableBiMap.of(); } @Override protected Map<String, Integer> makePopulatedMap() { return ImmutableBiMap.of("one", 1, "two", 2, "three", 3); } @Override protected String getKeyNotInPopulatedMap() { return "minus one"; } @Override protected Integer getValueNotInPopulatedMap() { return -1; } } public static class InverseMapTests extends AbstractMapTests<String, Integer> { @Override protected Map<String, Integer> makeEmptyMap() { return ImmutableBiMap.of(); } @Override protected Map<String, Integer> makePopulatedMap() { return ImmutableBiMap.of(1, "one", 2, "two", 3, "three").inverse(); } @Override protected String getKeyNotInPopulatedMap() { return "minus one"; } @Override protected Integer getValueNotInPopulatedMap() { return -1; } } public static class CreationTests extends TestCase { public void testEmptyBuilder() { ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().build(); assertEquals(Collections.<String, Integer>emptyMap(), map); assertEquals(Collections.<Integer, String>emptyMap(), map.inverse()); assertSame(ImmutableBiMap.of(), map); } public void testSingletonBuilder() { ImmutableBiMap<String, Integer> map = new Builder<String, Integer>() .put("one", 1) .build(); assertMapEquals(map, "one", 1); assertMapEquals(map.inverse(), 1, "one"); } public void testBuilder() { ImmutableBiMap<String, Integer> map = ImmutableBiMap.<String, Integer>builder() .put("one", 1) .put("two", 2) .put("three", 3) .put("four", 4) .put("five", 5) .build(); assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five"); } public void testBuilderPutAllWithEmptyMap() { ImmutableBiMap<String, Integer> map = new Builder<String, Integer>() .putAll(Collections.<String, Integer>emptyMap()) .build(); assertEquals(Collections.<String, Integer>emptyMap(), map); } public void testBuilderPutAll() { Map<String, Integer> toPut = new LinkedHashMap<String, Integer>(); toPut.put("one", 1); toPut.put("two", 2); toPut.put("three", 3); Map<String, Integer> moreToPut = new LinkedHashMap<String, Integer>(); moreToPut.put("four", 4); moreToPut.put("five", 5); ImmutableBiMap<String, Integer> map = new Builder<String, Integer>() .putAll(toPut) .putAll(moreToPut) .build(); assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five"); } public void testBuilderReuse() { Builder<String, Integer> builder = new Builder<String, Integer>(); ImmutableBiMap<String, Integer> mapOne = builder .put("one", 1) .put("two", 2) .build(); ImmutableBiMap<String, Integer> mapTwo = builder .put("three", 3) .put("four", 4) .build(); assertMapEquals(mapOne, "one", 1, "two", 2); assertMapEquals(mapOne.inverse(), 1, "one", 2, "two"); assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4); assertMapEquals(mapTwo.inverse(), 1, "one", 2, "two", 3, "three", 4, "four"); } public void testBuilderPutNullKey() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(null, 1); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullValue() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put("one", null); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullKeyViaPutAll() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.putAll(Collections.<String, Integer>singletonMap(null, 1)); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullValueViaPutAll() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.putAll(Collections.<String, Integer>singletonMap("one", null)); fail(); } catch (NullPointerException expected) { } } public void testPuttingTheSameKeyTwiceThrowsOnBuild() { Builder<String, Integer> builder = new Builder<String, Integer>() .put("one", 1) .put("one", 1); // throwing on this line would be even better try { builder.build(); fail(); } catch (IllegalArgumentException expected) { assertTrue(expected.getMessage().contains("one")); } } public void testOf() { assertMapEquals( ImmutableBiMap.of("one", 1), "one", 1); assertMapEquals( ImmutableBiMap.of("one", 1).inverse(), 1, "one"); assertMapEquals( ImmutableBiMap.of("one", 1, "two", 2), "one", 1, "two", 2); assertMapEquals( ImmutableBiMap.of("one", 1, "two", 2).inverse(), 1, "one", 2, "two"); assertMapEquals( ImmutableBiMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3); assertMapEquals( ImmutableBiMap.of("one", 1, "two", 2, "three", 3).inverse(), 1, "one", 2, "two", 3, "three"); assertMapEquals( ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4), "one", 1, "two", 2, "three", 3, "four", 4); assertMapEquals( ImmutableBiMap.of( "one", 1, "two", 2, "three", 3, "four", 4).inverse(), 1, "one", 2, "two", 3, "three", 4, "four"); assertMapEquals( ImmutableBiMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); assertMapEquals( ImmutableBiMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5).inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five"); } public void testOfNullKey() { try { ImmutableBiMap.of(null, 1); fail(); } catch (NullPointerException expected) { } try { ImmutableBiMap.of("one", 1, null, 2); fail(); } catch (NullPointerException expected) { } } public void testOfNullValue() { try { ImmutableBiMap.of("one", null); fail(); } catch (NullPointerException expected) { } try { ImmutableBiMap.of("one", 1, "two", null); fail(); } catch (NullPointerException expected) { } } public void testOfWithDuplicateKey() { try { ImmutableBiMap.of("one", 1, "one", 1); fail(); } catch (IllegalArgumentException expected) { assertTrue(expected.getMessage().contains("one")); } } public void testCopyOfEmptyMap() { ImmutableBiMap<String, Integer> copy = ImmutableBiMap.copyOf(Collections.<String, Integer>emptyMap()); assertEquals(Collections.<String, Integer>emptyMap(), copy); assertSame(copy, ImmutableBiMap.copyOf(copy)); assertSame(ImmutableBiMap.of(), copy); } public void testCopyOfSingletonMap() { ImmutableBiMap<String, Integer> copy = ImmutableBiMap.copyOf(Collections.singletonMap("one", 1)); assertMapEquals(copy, "one", 1); assertSame(copy, ImmutableBiMap.copyOf(copy)); } public void testCopyOf() { Map<String, Integer> original = new LinkedHashMap<String, Integer>(); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableBiMap<String, Integer> copy = ImmutableBiMap.copyOf(original); assertMapEquals(copy, "one", 1, "two", 2, "three", 3); assertSame(copy, ImmutableBiMap.copyOf(copy)); } public void testEmpty() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of(); assertEquals(Collections.<String, Integer>emptyMap(), bimap); assertEquals(Collections.<String, Integer>emptyMap(), bimap.inverse()); } public void testFromHashMap() { Map<String, Integer> hashMap = Maps.newLinkedHashMap(); hashMap.put("one", 1); hashMap.put("two", 2); ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf( ImmutableMap.of("one", 1, "two", 2)); assertMapEquals(bimap, "one", 1, "two", 2); assertMapEquals(bimap.inverse(), 1, "one", 2, "two"); } public void testFromImmutableMap() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf( new ImmutableMap.Builder<String, Integer>() .put("one", 1) .put("two", 2) .put("three", 3) .put("four", 4) .put("five", 5) .build()); assertMapEquals(bimap, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); assertMapEquals(bimap.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five"); } public void testDuplicateValues() { ImmutableMap<String, Integer> map = new ImmutableMap.Builder<String, Integer>() .put("one", 1) .put("two", 2) .put("uno", 1) .put("dos", 2) .build(); try { ImmutableBiMap.copyOf(map); fail(); } catch (IllegalArgumentException expected) { assertTrue(expected.getMessage().contains("1")); } } } public static class BiMapSpecificTests extends TestCase { @SuppressWarnings("deprecation") public void testForcePut() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf( ImmutableMap.of("one", 1, "two", 2)); try { bimap.forcePut("three", 3); fail(); } catch (UnsupportedOperationException expected) {} } public void testKeySet() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf( ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4)); Set<String> keys = bimap.keySet(); assertEquals(Sets.newHashSet("one", "two", "three", "four"), keys); ASSERT.that(keys).has().exactly("one", "two", "three", "four").inOrder(); } public void testValues() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf( ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4)); Set<Integer> values = bimap.values(); assertEquals(Sets.newHashSet(1, 2, 3, 4), values); ASSERT.that(values).has().exactly(1, 2, 3, 4).inOrder(); } public void testDoubleInverse() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf( ImmutableMap.of("one", 1, "two", 2)); assertSame(bimap, bimap.inverse().inverse()); } } private static <K, V> void assertMapEquals(Map<K, V> map, Object... alternatingKeysAndValues) { int i = 0; for (Entry<K, V> entry : map.entrySet()) { assertEquals(alternatingKeysAndValues[i++], entry.getKey()); assertEquals(alternatingKeysAndValues[i++], entry.getValue()); } } }
Java
/* * Copyright (C) 2007 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.collect; import static com.google.common.collect.testing.Helpers.orderEntriesByKey; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.google.TestBiMapGenerator; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Tests for {@code EnumBiMap}. * * @author Mike Bostock * @author Jared Levy */ @GwtCompatible(emulated = true) public class EnumBiMapTest extends TestCase { private enum Currency { DOLLAR, FRANC, PESO, POUND, YEN } private enum Country { CANADA, CHILE, JAPAN, SWITZERLAND, UK } public static final class EnumBiMapGenerator implements TestBiMapGenerator<Country, Currency> { @SuppressWarnings("unchecked") @Override public BiMap<Country, Currency> create(Object... entries) { BiMap<Country, Currency> result = EnumBiMap.create(Country.class, Currency.class); for (Object object : entries) { Entry<Country, Currency> entry = (Entry<Country, Currency>) object; result.put(entry.getKey(), entry.getValue()); } return result; } @Override public SampleElements<Entry<Country, Currency>> samples() { return new SampleElements<Entry<Country, Currency>>( Helpers.mapEntry(Country.CANADA, Currency.DOLLAR), Helpers.mapEntry(Country.CHILE, Currency.PESO), Helpers.mapEntry(Country.UK, Currency.POUND), Helpers.mapEntry(Country.JAPAN, Currency.YEN), Helpers.mapEntry(Country.SWITZERLAND, Currency.FRANC)); } @SuppressWarnings("unchecked") @Override public Entry<Country, Currency>[] createArray(int length) { return new Entry[length]; } @Override public Iterable<Entry<Country, Currency>> order(List<Entry<Country, Currency>> insertionOrder) { return orderEntriesByKey(insertionOrder); } @Override public Country[] createKeyArray(int length) { return new Country[length]; } @Override public Currency[] createValueArray(int length) { return new Currency[length]; } } public void testCreate() { EnumBiMap<Currency, Country> bimap = EnumBiMap.create(Currency.class, Country.class); assertTrue(bimap.isEmpty()); assertEquals("{}", bimap.toString()); assertEquals(HashBiMap.create(), bimap); bimap.put(Currency.DOLLAR, Country.CANADA); assertEquals(Country.CANADA, bimap.get(Currency.DOLLAR)); assertEquals(Currency.DOLLAR, bimap.inverse().get(Country.CANADA)); } public void testCreateFromMap() { /* Test with non-empty Map. */ Map<Currency, Country> map = ImmutableMap.of( Currency.DOLLAR, Country.CANADA, Currency.PESO, Country.CHILE, Currency.FRANC, Country.SWITZERLAND); EnumBiMap<Currency, Country> bimap = EnumBiMap.create(map); assertEquals(Country.CANADA, bimap.get(Currency.DOLLAR)); assertEquals(Currency.DOLLAR, bimap.inverse().get(Country.CANADA)); /* Map must have at least one entry if not an EnumBiMap. */ try { EnumBiMap.create(Collections.<Currency, Country>emptyMap()); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException expected) {} try { EnumBiMap.create( EnumHashBiMap.<Currency, Country>create(Currency.class)); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException expected) {} /* Map can be empty if it's an EnumBiMap. */ Map<Currency, Country> emptyBimap = EnumBiMap.create(Currency.class, Country.class); bimap = EnumBiMap.create(emptyBimap); assertTrue(bimap.isEmpty()); } public void testEnumBiMapConstructor() { /* Test that it copies existing entries. */ EnumBiMap<Currency, Country> bimap1 = EnumBiMap.create(Currency.class, Country.class); bimap1.put(Currency.DOLLAR, Country.CANADA); EnumBiMap<Currency, Country> bimap2 = EnumBiMap.create(bimap1); assertEquals(Country.CANADA, bimap2.get(Currency.DOLLAR)); assertEquals(bimap1, bimap2); bimap2.inverse().put(Country.SWITZERLAND, Currency.FRANC); assertEquals(Country.SWITZERLAND, bimap2.get(Currency.FRANC)); assertNull(bimap1.get(Currency.FRANC)); assertFalse(bimap2.equals(bimap1)); /* Test that it can be empty. */ EnumBiMap<Currency, Country> emptyBimap = EnumBiMap.create(Currency.class, Country.class); EnumBiMap<Currency, Country> bimap3 = EnumBiMap.create(emptyBimap); assertEquals(bimap3, emptyBimap); } public void testKeyType() { EnumBiMap<Currency, Country> bimap = EnumBiMap.create(Currency.class, Country.class); assertEquals(Currency.class, bimap.keyType()); } public void testValueType() { EnumBiMap<Currency, Country> bimap = EnumBiMap.create(Currency.class, Country.class); assertEquals(Country.class, bimap.valueType()); } public void testIterationOrder() { // The enum orderings are alphabetical, leading to the bimap and its inverse // having inconsistent iteration orderings. Map<Currency, Country> map = ImmutableMap.of( Currency.DOLLAR, Country.CANADA, Currency.PESO, Country.CHILE, Currency.FRANC, Country.SWITZERLAND); EnumBiMap<Currency, Country> bimap = EnumBiMap.create(map); // forward map ordered by currency ASSERT.that(bimap.keySet()) .has().exactly(Currency.DOLLAR, Currency.FRANC, Currency.PESO).inOrder(); // forward map ordered by currency (even for country values) ASSERT.that(bimap.values()) .has().exactly(Country.CANADA, Country.SWITZERLAND, Country.CHILE).inOrder(); // backward map ordered by country ASSERT.that(bimap.inverse().keySet()) .has().exactly(Country.CANADA, Country.CHILE, Country.SWITZERLAND).inOrder(); // backward map ordered by country (even for currency values) ASSERT.that(bimap.inverse().values()) .has().exactly(Currency.DOLLAR, Currency.PESO, Currency.FRANC).inOrder(); } public void testKeySetIteratorRemove() { // The enum orderings are alphabetical, leading to the bimap and its inverse // having inconsistent iteration orderings. Map<Currency, Country> map = ImmutableMap.of( Currency.DOLLAR, Country.CANADA, Currency.PESO, Country.CHILE, Currency.FRANC, Country.SWITZERLAND); EnumBiMap<Currency, Country> bimap = EnumBiMap.create(map); Iterator<Currency> iter = bimap.keySet().iterator(); assertEquals(Currency.DOLLAR, iter.next()); iter.remove(); // forward map ordered by currency ASSERT.that(bimap.keySet()) .has().exactly(Currency.FRANC, Currency.PESO).inOrder(); // forward map ordered by currency (even for country values) ASSERT.that(bimap.values()) .has().exactly(Country.SWITZERLAND, Country.CHILE).inOrder(); // backward map ordered by country ASSERT.that(bimap.inverse().keySet()) .has().exactly(Country.CHILE, Country.SWITZERLAND).inOrder(); // backward map ordered by country (even for currency values) ASSERT.that(bimap.inverse().values()) .has().exactly(Currency.PESO, Currency.FRANC).inOrder(); } public void testValuesIteratorRemove() { // The enum orderings are alphabetical, leading to the bimap and its inverse // having inconsistent iteration orderings. Map<Currency, Country> map = ImmutableMap.of( Currency.DOLLAR, Country.CANADA, Currency.PESO, Country.CHILE, Currency.FRANC, Country.SWITZERLAND); EnumBiMap<Currency, Country> bimap = EnumBiMap.create(map); Iterator<Currency> iter = bimap.keySet().iterator(); assertEquals(Currency.DOLLAR, iter.next()); assertEquals(Currency.FRANC, iter.next()); iter.remove(); // forward map ordered by currency ASSERT.that(bimap.keySet()) .has().exactly(Currency.DOLLAR, Currency.PESO).inOrder(); // forward map ordered by currency (even for country values) ASSERT.that(bimap.values()) .has().exactly(Country.CANADA, Country.CHILE).inOrder(); // backward map ordered by country ASSERT.that(bimap.inverse().keySet()) .has().exactly(Country.CANADA, Country.CHILE).inOrder(); // backward map ordered by country (even for currency values) ASSERT.that(bimap.inverse().values()) .has().exactly(Currency.DOLLAR, Currency.PESO).inOrder(); } public void testEntrySet() { // Bug 3168290 Map<Currency, Country> map = ImmutableMap.of( Currency.DOLLAR, Country.CANADA, Currency.PESO, Country.CHILE, Currency.FRANC, Country.SWITZERLAND); EnumBiMap<Currency, Country> bimap = EnumBiMap.create(map); Set<Object> uniqueEntries = Sets.newIdentityHashSet(); uniqueEntries.addAll(bimap.entrySet()); assertEquals(3, uniqueEntries.size()); } public void testEquals() { new EqualsTester() .addEqualityGroup( EnumBiMap.create(ImmutableMap.of(Currency.DOLLAR, Country.CANADA)), EnumBiMap.create(ImmutableMap.of(Currency.DOLLAR, Country.CANADA))) .addEqualityGroup(EnumBiMap.create(ImmutableMap.of(Currency.DOLLAR, Country.CHILE))) .addEqualityGroup(EnumBiMap.create(ImmutableMap.of(Currency.FRANC, Country.CANADA))) .testEquals(); } /* Remaining behavior tested by AbstractBiMapTest. */ }
Java
/* * Copyright (C) 2012 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AnEnum; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.TestEnumMapGenerator; import junit.framework.TestCase; import java.util.Map; import java.util.Map.Entry; /** * Tests for {@code ImmutableEnumMap}. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class ImmutableEnumMapTest extends TestCase { public static class ImmutableEnumMapGenerator extends TestEnumMapGenerator { @Override protected Map<AnEnum, String> create(Entry<AnEnum, String>[] entries) { Map<AnEnum, String> map = Maps.newHashMap(); for (Entry<AnEnum, String> entry : entries) { map.put(entry.getKey(), entry.getValue()); } return Maps.immutableEnumMap(map); } } public void testEmptyImmutableEnumMap() { ImmutableMap<AnEnum, String> map = Maps.immutableEnumMap(ImmutableMap.<AnEnum, String>of()); assertEquals(ImmutableMap.of(), map); } public void testImmutableEnumMapOrdering() { ImmutableMap<AnEnum, String> map = Maps.immutableEnumMap( ImmutableMap.of(AnEnum.C, "c", AnEnum.A, "a", AnEnum.E, "e")); ASSERT.that(map.entrySet()).has().exactly( Helpers.mapEntry(AnEnum.A, "a"), Helpers.mapEntry(AnEnum.C, "c"), Helpers.mapEntry(AnEnum.E, "e")).inOrder(); } }
Java
/* * Copyright (C) 2011 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.collect; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; /** * Test cases for {@link Tables#transformValues}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class TablesTransformValuesTest extends AbstractTableTest { private static final Function<String, Character> FIRST_CHARACTER = new Function<String, Character>() { @Override public Character apply(String input) { return input == null ? null : input.charAt(0); } }; @Override protected Table<String, Integer, Character> create( Object... data) { Table<String, Integer, String> table = HashBasedTable.create(); checkArgument(data.length % 3 == 0); for (int i = 0; i < data.length; i+= 3) { String value = (data[i+2] == null) ? null : data[i+2].toString() + "transformed"; table.put((String) data[i], (Integer) data[i+1], value); } return Tables.transformValues(table, FIRST_CHARACTER); } // Null support depends on the underlying table and function. // put() and putAll() aren't supported. @Override public void testPut() { try { table.put("foo", 1, 'a'); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException expected) {} assertSize(0); } @Override public void testPutAllTable() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Table<String, Integer, Character> other = HashBasedTable.create(); other.put("foo", 1, 'd'); other.put("bar", 2, 'e'); other.put("cat", 2, 'f'); try { table.putAll(other); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException expected) {} assertEquals((Character) 'a', table.get("foo", 1)); assertEquals((Character) 'b', table.get("bar", 1)); assertEquals((Character) 'c', table.get("foo", 3)); assertSize(3); } @Override public void testPutNull() {} @Override public void testPutNullReplace() {} @Override public void testRowClearAndPut() {} }
Java
/* * Copyright (C) 2007 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; /** * Unit tests for {@code TreeMultimap} with natural ordering. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class TreeMultimapNaturalTest extends TestCase { protected SetMultimap<String, Integer> create() { return TreeMultimap.create(); } /** * Create and populate a {@code TreeMultimap} with the natural ordering of * keys and values. */ private TreeMultimap<String, Integer> createPopulate() { TreeMultimap<String, Integer> multimap = TreeMultimap.create(); multimap.put("google", 2); multimap.put("google", 6); multimap.put("foo", 3); multimap.put("foo", 1); multimap.put("foo", 7); multimap.put("tree", 4); multimap.put("tree", 0); return multimap; } public void testToString() { SetMultimap<String, Integer> multimap = create(); multimap.putAll("bar", Arrays.asList(3, 1, 2)); multimap.putAll("foo", Arrays.asList(2, 3, 1, -1, 4)); assertEquals("{bar=[1, 2, 3], foo=[-1, 1, 2, 3, 4]}", multimap.toString()); } public void testOrderedGet() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.get("foo")).has().exactly(1, 3, 7).inOrder(); ASSERT.that(multimap.get("google")).has().exactly(2, 6).inOrder(); ASSERT.that(multimap.get("tree")).has().exactly(0, 4).inOrder(); } public void testOrderedKeySet() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.keySet()).has().exactly("foo", "google", "tree").inOrder(); } public void testOrderedAsMapEntries() { TreeMultimap<String, Integer> multimap = createPopulate(); Iterator<Map.Entry<String, Collection<Integer>>> iterator = multimap.asMap().entrySet().iterator(); Map.Entry<String, Collection<Integer>> entry = iterator.next(); assertEquals("foo", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(1, 3, 7); entry = iterator.next(); assertEquals("google", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(2, 6); entry = iterator.next(); assertEquals("tree", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(0, 4); } public void testOrderedEntries() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.entries()).has().exactly( Maps.immutableEntry("foo", 1), Maps.immutableEntry("foo", 3), Maps.immutableEntry("foo", 7), Maps.immutableEntry("google", 2), Maps.immutableEntry("google", 6), Maps.immutableEntry("tree", 0), Maps.immutableEntry("tree", 4)).inOrder(); } public void testOrderedValues() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.values()).has().exactly( 1, 3, 7, 2, 6, 0, 4).inOrder(); } public void testMultimapConstructor() { SetMultimap<String, Integer> multimap = create(); multimap.putAll("bar", Arrays.asList(3, 1, 2)); multimap.putAll("foo", Arrays.asList(2, 3, 1, -1, 4)); TreeMultimap<String, Integer> copy = TreeMultimap.create(multimap); assertEquals(multimap, copy); } private static final Comparator<Double> KEY_COMPARATOR = Ordering.natural(); private static final Comparator<Double> VALUE_COMPARATOR = Ordering.natural().reverse().nullsFirst(); /** * Test that creating one TreeMultimap from another does not copy the * comparators from the source TreeMultimap. */ public void testCreateFromTreeMultimap() { Multimap<Double, Double> tree = TreeMultimap.create(KEY_COMPARATOR, VALUE_COMPARATOR); tree.put(1.0, 2.0); tree.put(2.0, 3.0); tree.put(3.0, 4.0); tree.put(4.0, 5.0); TreeMultimap<Double, Double> copyFromTree = TreeMultimap.create(tree); assertEquals(tree, copyFromTree); assertSame(Ordering.natural(), copyFromTree.keyComparator()); assertSame(Ordering.natural(), copyFromTree.valueComparator()); assertSame(Ordering.natural(), copyFromTree.get(1.0).comparator()); } /** * Test that creating one TreeMultimap from a non-TreeMultimap * results in natural ordering. */ public void testCreateFromHashMultimap() { Multimap<Double, Double> hash = HashMultimap.create(); hash.put(1.0, 2.0); hash.put(2.0, 3.0); hash.put(3.0, 4.0); hash.put(4.0, 5.0); TreeMultimap<Double, Double> copyFromHash = TreeMultimap.create(hash); assertEquals(hash, copyFromHash); assertEquals(Ordering.natural(), copyFromHash.keyComparator()); assertEquals(Ordering.natural(), copyFromHash.valueComparator()); } /** * Test that creating one TreeMultimap from a SortedSetMultimap uses natural * ordering. */ public void testCreateFromSortedSetMultimap() { SortedSetMultimap<Double, Double> tree = TreeMultimap.create(KEY_COMPARATOR, VALUE_COMPARATOR); tree.put(1.0, 2.0); tree.put(2.0, 3.0); tree.put(3.0, 4.0); tree.put(4.0, 5.0); SortedSetMultimap<Double, Double> sorted = Multimaps.unmodifiableSortedSetMultimap(tree); TreeMultimap<Double, Double> copyFromSorted = TreeMultimap.create(sorted); assertEquals(tree, copyFromSorted); assertSame(Ordering.natural(), copyFromSorted.keyComparator()); assertSame(Ordering.natural(), copyFromSorted.valueComparator()); assertSame(Ordering.natural(), copyFromSorted.get(1.0).comparator()); } public void testComparators() { TreeMultimap<String, Integer> multimap = TreeMultimap.create(); assertEquals(Ordering.natural(), multimap.keyComparator()); assertEquals(Ordering.natural(), multimap.valueComparator()); } public void testTreeMultimapAsMapSorted() { TreeMultimap<String, Integer> multimap = createPopulate(); SortedMap<String, Collection<Integer>> asMap = multimap.asMap(); assertEquals(Ordering.natural(), asMap.comparator()); assertEquals("foo", asMap.firstKey()); assertEquals("tree", asMap.lastKey()); Set<Integer> fooValues = ImmutableSet.of(1, 3, 7); Set<Integer> googleValues = ImmutableSet.of(2, 6); Set<Integer> treeValues = ImmutableSet.of(4, 0); assertEquals(ImmutableMap.of("google", googleValues, "tree", treeValues), asMap.tailMap("g")); assertEquals(ImmutableMap.of("google", googleValues, "foo", fooValues), asMap.headMap("h")); assertEquals(ImmutableMap.of("google", googleValues), asMap.subMap("g", "h")); } public void testTailSetClear() { TreeMultimap<String, Integer> multimap = TreeMultimap.create(); multimap.put("a", 1); multimap.put("a", 11); multimap.put("b", 2); multimap.put("c", 3); multimap.put("d", 4); multimap.put("e", 5); multimap.put("e", 55); multimap.keySet().tailSet("d").clear(); assertEquals(ImmutableSet.of("a", "b", "c"), multimap.keySet()); assertEquals(4, multimap.size()); assertEquals(4, multimap.values().size()); assertEquals(4, multimap.keys().size()); } }
Java
/* * Copyright (C) 2008 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.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.testing.AnEnum; import com.google.common.collect.testing.MapInterfaceTest; import com.google.common.collect.testing.MinimalSet; import com.google.common.collect.testing.SampleElements.Colliders; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.io.Serializable; import java.util.Collections; import java.util.EnumMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; /** * Tests for {@link ImmutableMap}. * * @author Kevin Bourrillion * @author Jesse Wilson */ @GwtCompatible(emulated = true) public class ImmutableMapTest extends TestCase { public abstract static class AbstractMapTests<K, V> extends MapInterfaceTest<K, V> { public AbstractMapTests() { super(false, false, false, false, false); } @Override protected Map<K, V> makeEmptyMap() { throw new UnsupportedOperationException(); } private static final Joiner joiner = Joiner.on(", "); @Override protected void assertMoreInvariants(Map<K, V> map) { // TODO: can these be moved to MapInterfaceTest? for (Entry<K, V> entry : map.entrySet()) { assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString()); } assertEquals("{" + joiner.join(map.entrySet()) + "}", map.toString()); assertEquals("[" + joiner.join(map.entrySet()) + "]", map.entrySet().toString()); assertEquals("[" + joiner.join(map.keySet()) + "]", map.keySet().toString()); assertEquals("[" + joiner.join(map.values()) + "]", map.values().toString()); assertEquals(MinimalSet.from(map.entrySet()), map.entrySet()); assertEquals(Sets.newHashSet(map.keySet()), map.keySet()); } } public static class MapTests extends AbstractMapTests<String, Integer> { @Override protected Map<String, Integer> makeEmptyMap() { return ImmutableMap.of(); } @Override protected Map<String, Integer> makePopulatedMap() { return ImmutableMap.of("one", 1, "two", 2, "three", 3); } @Override protected String getKeyNotInPopulatedMap() { return "minus one"; } @Override protected Integer getValueNotInPopulatedMap() { return -1; } } public static class SingletonMapTests extends AbstractMapTests<String, Integer> { @Override protected Map<String, Integer> makePopulatedMap() { return ImmutableMap.of("one", 1); } @Override protected String getKeyNotInPopulatedMap() { return "minus one"; } @Override protected Integer getValueNotInPopulatedMap() { return -1; } } public static class MapTestsWithBadHashes extends AbstractMapTests<Object, Integer> { @Override protected Map<Object, Integer> makeEmptyMap() { throw new UnsupportedOperationException(); } @Override protected Map<Object, Integer> makePopulatedMap() { Colliders colliders = new Colliders(); return ImmutableMap.of( colliders.e0, 0, colliders.e1, 1, colliders.e2, 2, colliders.e3, 3); } @Override protected Object getKeyNotInPopulatedMap() { return new Colliders().e4; } @Override protected Integer getValueNotInPopulatedMap() { return 4; } } public static class CreationTests extends TestCase { public void testEmptyBuilder() { ImmutableMap<String, Integer> map = new Builder<String, Integer>().build(); assertEquals(Collections.<String, Integer>emptyMap(), map); } public void testSingletonBuilder() { ImmutableMap<String, Integer> map = new Builder<String, Integer>() .put("one", 1) .build(); assertMapEquals(map, "one", 1); } public void testBuilder() { ImmutableMap<String, Integer> map = new Builder<String, Integer>() .put("one", 1) .put("two", 2) .put("three", 3) .put("four", 4) .put("five", 5) .build(); assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); } public void testBuilder_withImmutableEntry() { ImmutableMap<String, Integer> map = new Builder<String, Integer>() .put(Maps.immutableEntry("one", 1)) .build(); assertMapEquals(map, "one", 1); } public void testBuilder_withImmutableEntryAndNullContents() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(Maps.immutableEntry("one", (Integer) null)); fail(); } catch (NullPointerException expected) { } try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) { } } private static class StringHolder { String string; } public void testBuilder_withMutableEntry() { ImmutableMap.Builder<String, Integer> builder = new Builder<String, Integer>(); final StringHolder holder = new StringHolder(); holder.string = "one"; Entry<String, Integer> entry = new AbstractMapEntry<String, Integer>() { @Override public String getKey() { return holder.string; } @Override public Integer getValue() { return 1; } }; builder.put(entry); holder.string = "two"; assertMapEquals(builder.build(), "one", 1); } public void testBuilderPutAllWithEmptyMap() { ImmutableMap<String, Integer> map = new Builder<String, Integer>() .putAll(Collections.<String, Integer>emptyMap()) .build(); assertEquals(Collections.<String, Integer>emptyMap(), map); } public void testBuilderPutAll() { Map<String, Integer> toPut = new LinkedHashMap<String, Integer>(); toPut.put("one", 1); toPut.put("two", 2); toPut.put("three", 3); Map<String, Integer> moreToPut = new LinkedHashMap<String, Integer>(); moreToPut.put("four", 4); moreToPut.put("five", 5); ImmutableMap<String, Integer> map = new Builder<String, Integer>() .putAll(toPut) .putAll(moreToPut) .build(); assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); } public void testBuilderReuse() { Builder<String, Integer> builder = new Builder<String, Integer>(); ImmutableMap<String, Integer> mapOne = builder .put("one", 1) .put("two", 2) .build(); ImmutableMap<String, Integer> mapTwo = builder .put("three", 3) .put("four", 4) .build(); assertMapEquals(mapOne, "one", 1, "two", 2); assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4); } public void testBuilderPutNullKeyFailsAtomically() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(null, 1); fail(); } catch (NullPointerException expected) {} builder.put("foo", 2); assertMapEquals(builder.build(), "foo", 2); } public void testBuilderPutImmutableEntryWithNullKeyFailsAtomically() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) {} builder.put("foo", 2); assertMapEquals(builder.build(), "foo", 2); } // for GWT compatibility static class SimpleEntry<K, V> extends AbstractMapEntry<K, V> { public K key; public V value; SimpleEntry(K key, V value) { this.key = key; this.value = value; } @Override public K getKey() { return key; } @Override public V getValue() { return value; } } public void testBuilderPutMutableEntryWithNullKeyFailsAtomically() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(new SimpleEntry<String, Integer>(null, 1)); fail(); } catch (NullPointerException expected) {} builder.put("foo", 2); assertMapEquals(builder.build(), "foo", 2); } public void testBuilderPutNullKey() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(null, 1); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullValue() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put("one", null); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullKeyViaPutAll() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.putAll(Collections.<String, Integer>singletonMap(null, 1)); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullValueViaPutAll() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.putAll(Collections.<String, Integer>singletonMap("one", null)); fail(); } catch (NullPointerException expected) { } } public void testPuttingTheSameKeyTwiceThrowsOnBuild() { Builder<String, Integer> builder = new Builder<String, Integer>() .put("one", 1) .put("one", 1); // throwing on this line would be even better try { builder.build(); fail(); } catch (IllegalArgumentException expected) { } } public void testOf() { assertMapEquals( ImmutableMap.of("one", 1), "one", 1); assertMapEquals( ImmutableMap.of("one", 1, "two", 2), "one", 1, "two", 2); assertMapEquals( ImmutableMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3); assertMapEquals( ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4), "one", 1, "two", 2, "three", 3, "four", 4); assertMapEquals( ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); } public void testOfNullKey() { try { ImmutableMap.of(null, 1); fail(); } catch (NullPointerException expected) { } try { ImmutableMap.of("one", 1, null, 2); fail(); } catch (NullPointerException expected) { } } public void testOfNullValue() { try { ImmutableMap.of("one", null); fail(); } catch (NullPointerException expected) { } try { ImmutableMap.of("one", 1, "two", null); fail(); } catch (NullPointerException expected) { } } public void testOfWithDuplicateKey() { try { ImmutableMap.of("one", 1, "one", 1); fail(); } catch (IllegalArgumentException expected) { } } public void testCopyOfEmptyMap() { ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(Collections.<String, Integer>emptyMap()); assertEquals(Collections.<String, Integer>emptyMap(), copy); assertSame(copy, ImmutableMap.copyOf(copy)); } public void testCopyOfSingletonMap() { ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(Collections.singletonMap("one", 1)); assertMapEquals(copy, "one", 1); assertSame(copy, ImmutableMap.copyOf(copy)); } public void testCopyOf() { Map<String, Integer> original = new LinkedHashMap<String, Integer>(); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(original); assertMapEquals(copy, "one", 1, "two", 2, "three", 3); assertSame(copy, ImmutableMap.copyOf(copy)); } } public void testNullGet() { ImmutableMap<String, Integer> map = ImmutableMap.of("one", 1); assertNull(map.get(null)); } public void testAsMultimap() { ImmutableMap<String, Integer> map = ImmutableMap.of( "one", 1, "won", 1, "two", 2, "too", 2, "three", 3); ImmutableSetMultimap<String, Integer> expected = ImmutableSetMultimap.of( "one", 1, "won", 1, "two", 2, "too", 2, "three", 3); assertEquals(expected, map.asMultimap()); } public void testAsMultimapWhenEmpty() { ImmutableMap<String, Integer> map = ImmutableMap.of(); ImmutableSetMultimap<String, Integer> expected = ImmutableSetMultimap.of(); assertEquals(expected, map.asMultimap()); } public void testAsMultimapCaches() { ImmutableMap<String, Integer> map = ImmutableMap.of("one", 1); ImmutableSetMultimap<String, Integer> multimap1 = map.asMultimap(); ImmutableSetMultimap<String, Integer> multimap2 = map.asMultimap(); assertEquals(1, multimap1.asMap().size()); assertSame(multimap1, multimap2); } private static <K, V> void assertMapEquals(Map<K, V> map, Object... alternatingKeysAndValues) { assertEquals(map.size(), alternatingKeysAndValues.length / 2); int i = 0; for (Entry<K, V> entry : map.entrySet()) { assertEquals(alternatingKeysAndValues[i++], entry.getKey()); assertEquals(alternatingKeysAndValues[i++], entry.getValue()); } } private static class IntHolder implements Serializable { public int value; public IntHolder(int value) { this.value = value; } @Override public boolean equals(Object o) { return (o instanceof IntHolder) && ((IntHolder) o).value == value; } @Override public int hashCode() { return value; } private static final long serialVersionUID = 5; } public void testMutableValues() { IntHolder holderA = new IntHolder(1); IntHolder holderB = new IntHolder(2); Map<String, IntHolder> map = ImmutableMap.of("a", holderA, "b", holderB); holderA.value = 3; assertTrue(map.entrySet().contains( Maps.immutableEntry("a", new IntHolder(3)))); Map<String, Integer> intMap = ImmutableMap.of("a", 3, "b", 2); assertEquals(intMap.hashCode(), map.entrySet().hashCode()); assertEquals(intMap.hashCode(), map.hashCode()); } public void testCopyOfEnumMap() { EnumMap<AnEnum, String> map = new EnumMap<AnEnum, String>(AnEnum.class); map.put(AnEnum.B, "foo"); map.put(AnEnum.C, "bar"); assertTrue(ImmutableMap.copyOf(map) instanceof ImmutableEnumMap); } public void testEquals() { new EqualsTester() .addEqualityGroup(ImmutableList.of(), ImmutableList.of()) .addEqualityGroup(ImmutableList.of(1), ImmutableList.of(1)) .addEqualityGroup(ImmutableList.of(1, 2), ImmutableList.of(1, 2)) .addEqualityGroup(ImmutableList.of(1, 2, 3)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(100, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 200, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 300, 4, 5, 6, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 400, 5, 6, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 500, 6, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 600, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 700, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 800, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 900, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 1000, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1100, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1200)) .testEquals(); } }
Java
/* * Copyright (C) 2007 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.collect; import static java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.MinimalIterable; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Unit test for {@link ImmutableList}. * * @author Kevin Bourrillion * @author George van den Driessche * @author Jared Levy */ @GwtCompatible(emulated = true) public class ImmutableListTest extends TestCase { public static class CreationTests extends TestCase { public void testCreation_noArgs() { List<String> list = ImmutableList.of(); assertEquals(Collections.emptyList(), list); } public void testCreation_oneElement() { List<String> list = ImmutableList.of("a"); assertEquals(Collections.singletonList("a"), list); } public void testCreation_twoElements() { List<String> list = ImmutableList.of("a", "b"); assertEquals(Lists.newArrayList("a", "b"), list); } public void testCreation_threeElements() { List<String> list = ImmutableList.of("a", "b", "c"); assertEquals(Lists.newArrayList("a", "b", "c"), list); } public void testCreation_fourElements() { List<String> list = ImmutableList.of("a", "b", "c", "d"); assertEquals(Lists.newArrayList("a", "b", "c", "d"), list); } public void testCreation_fiveElements() { List<String> list = ImmutableList.of("a", "b", "c", "d", "e"); assertEquals(Lists.newArrayList("a", "b", "c", "d", "e"), list); } public void testCreation_sixElements() { List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f"); assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f"), list); } public void testCreation_sevenElements() { List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g"); assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g"), list); } public void testCreation_eightElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h"), list); } public void testCreation_nineElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h", "i"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i"), list); } public void testCreation_tenElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"), list); } public void testCreation_elevenElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"), list); } // Varargs versions public void testCreation_twelveElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"), list); } public void testCreation_thirteenElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"), list); } public void testCreation_fourteenElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"), list); } public void testCreation_singletonNull() { try { ImmutableList.of((String) null); fail(); } catch (NullPointerException expected) { } } public void testCreation_withNull() { try { ImmutableList.of("a", null, "b"); fail(); } catch (NullPointerException expected) { } } public void testCreation_generic() { List<String> a = ImmutableList.of("a"); // only verify that there is no compile warning ImmutableList.of(a, a); } public void testCreation_arrayOfArray() { String[] array = new String[] { "a" }; List<String[]> list = ImmutableList.<String[]>of(array); assertEquals(Collections.singletonList(array), list); } public void testCopyOf_emptyArray() { String[] array = new String[0]; List<String> list = ImmutableList.copyOf(array); assertEquals(Collections.emptyList(), list); } public void testCopyOf_arrayOfOneElement() { String[] array = new String[] { "a" }; List<String> list = ImmutableList.copyOf(array); assertEquals(Collections.singletonList("a"), list); } public void testCopyOf_nullArray() { try { ImmutableList.copyOf((String[]) null); fail(); } catch(NullPointerException expected) { } } public void testCopyOf_arrayContainingOnlyNull() { String[] array = new String[] { null }; try { ImmutableList.copyOf(array); fail(); } catch (NullPointerException expected) { } } public void testCopyOf_collection_empty() { // "<String>" is required to work around a javac 1.5 bug. Collection<String> c = MinimalCollection.<String>of(); List<String> list = ImmutableList.copyOf(c); assertEquals(Collections.emptyList(), list); } public void testCopyOf_collection_oneElement() { Collection<String> c = MinimalCollection.of("a"); List<String> list = ImmutableList.copyOf(c); assertEquals(Collections.singletonList("a"), list); } public void testCopyOf_collection_general() { Collection<String> c = MinimalCollection.of("a", "b", "a"); List<String> list = ImmutableList.copyOf(c); assertEquals(asList("a", "b", "a"), list); List<String> mutableList = asList("a", "b"); list = ImmutableList.copyOf(mutableList); mutableList.set(0, "c"); assertEquals(asList("a", "b"), list); } public void testCopyOf_collectionContainingNull() { Collection<String> c = MinimalCollection.of("a", null, "b"); try { ImmutableList.copyOf(c); fail(); } catch (NullPointerException expected) { } } public void testCopyOf_iterator_empty() { Iterator<String> iterator = Iterators.emptyIterator(); List<String> list = ImmutableList.copyOf(iterator); assertEquals(Collections.emptyList(), list); } public void testCopyOf_iterator_oneElement() { Iterator<String> iterator = Iterators.singletonIterator("a"); List<String> list = ImmutableList.copyOf(iterator); assertEquals(Collections.singletonList("a"), list); } public void testCopyOf_iterator_general() { Iterator<String> iterator = asList("a", "b", "a").iterator(); List<String> list = ImmutableList.copyOf(iterator); assertEquals(asList("a", "b", "a"), list); } public void testCopyOf_iteratorContainingNull() { Iterator<String> iterator = asList("a", null, "b").iterator(); try { ImmutableList.copyOf(iterator); fail(); } catch (NullPointerException expected) { } } public void testCopyOf_iteratorNull() { try { ImmutableList.copyOf((Iterator<String>) null); fail(); } catch(NullPointerException expected) { } } public void testCopyOf_concurrentlyMutating() { List<String> sample = Lists.newArrayList("a", "b", "c"); for (int delta : new int[] {-1, 0, 1}) { for (int i = 0; i < sample.size(); i++) { Collection<String> misleading = Helpers.misleadingSizeCollection(delta); List<String> expected = sample.subList(0, i); misleading.addAll(expected); assertEquals(expected, ImmutableList.copyOf(misleading)); assertEquals(expected, ImmutableList.copyOf((Iterable<String>) misleading)); } } } private static class CountingIterable implements Iterable<String> { int count = 0; @Override public Iterator<String> iterator() { count++; return asList("a", "b", "a").iterator(); } } public void testCopyOf_plainIterable() { CountingIterable iterable = new CountingIterable(); List<String> list = ImmutableList.copyOf(iterable); assertEquals(asList("a", "b", "a"), list); } public void testCopyOf_plainIterable_iteratesOnce() { CountingIterable iterable = new CountingIterable(); ImmutableList.copyOf(iterable); assertEquals(1, iterable.count); } public void testCopyOf_shortcut_empty() { Collection<String> c = ImmutableList.of(); assertSame(c, ImmutableList.copyOf(c)); } public void testCopyOf_shortcut_singleton() { Collection<String> c = ImmutableList.of("a"); assertSame(c, ImmutableList.copyOf(c)); } public void testCopyOf_shortcut_immutableList() { Collection<String> c = ImmutableList.of("a", "b", "c"); assertSame(c, ImmutableList.copyOf(c)); } public void testBuilderAddArrayHandlesNulls() { String[] elements = {"a", null, "b"}; ImmutableList.Builder<String> builder = ImmutableList.builder(); try { builder.add(elements); fail ("Expected NullPointerException"); } catch (NullPointerException expected) { } ImmutableList<String> result = builder.build(); /* * Maybe it rejects all elements, or maybe it adds "a" before failing. * Either way is fine with us. */ if (result.isEmpty()) { return; } assertTrue(ImmutableList.of("a").equals(result)); assertEquals(1, result.size()); } public void testBuilderAddCollectionHandlesNulls() { List<String> elements = Arrays.asList("a", null, "b"); ImmutableList.Builder<String> builder = ImmutableList.builder(); try { builder.addAll(elements); fail ("Expected NullPointerException"); } catch (NullPointerException expected) { } ImmutableList<String> result = builder.build(); assertEquals(ImmutableList.of("a"), result); assertEquals(1, result.size()); } } public static class BasicTests extends TestCase { public void testEquals_immutableList() { Collection<String> c = ImmutableList.of("a", "b", "c"); assertTrue(c.equals(ImmutableList.of("a", "b", "c"))); assertFalse(c.equals(ImmutableList.of("a", "c", "b"))); assertFalse(c.equals(ImmutableList.of("a", "b"))); assertFalse(c.equals(ImmutableList.of("a", "b", "c", "d"))); } public void testBuilderAdd() { ImmutableList<String> list = new ImmutableList.Builder<String>() .add("a") .add("b") .add("a") .add("c") .build(); assertEquals(asList("a", "b", "a", "c"), list); } public void testBuilderAdd_varargs() { ImmutableList<String> list = new ImmutableList.Builder<String>() .add("a", "b", "a", "c") .build(); assertEquals(asList("a", "b", "a", "c"), list); } public void testBuilderAddAll_iterable() { List<String> a = asList("a", "b"); List<String> b = asList("c", "d"); ImmutableList<String> list = new ImmutableList.Builder<String>() .addAll(a) .addAll(b) .build(); assertEquals(asList( "a", "b", "c", "d"), list); b.set(0, "f"); assertEquals(asList( "a", "b", "c", "d"), list); } public void testBuilderAddAll_iterator() { List<String> a = asList("a", "b"); List<String> b = asList("c", "d"); ImmutableList<String> list = new ImmutableList.Builder<String>() .addAll(a.iterator()) .addAll(b.iterator()) .build(); assertEquals(asList( "a", "b", "c", "d"), list); b.set(0, "f"); assertEquals(asList( "a", "b", "c", "d"), list); } public void testComplexBuilder() { List<Integer> colorElem = asList(0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF); ImmutableList.Builder<Integer> webSafeColorsBuilder = ImmutableList.builder(); for (Integer red : colorElem) { for (Integer green : colorElem) { for (Integer blue : colorElem) { webSafeColorsBuilder.add((red << 16) + (green << 8) + blue); } } } ImmutableList<Integer> webSafeColors = webSafeColorsBuilder.build(); assertEquals(216, webSafeColors.size()); Integer[] webSafeColorArray = webSafeColors.toArray(new Integer[webSafeColors.size()]); assertEquals(0x000000, (int) webSafeColorArray[0]); assertEquals(0x000033, (int) webSafeColorArray[1]); assertEquals(0x000066, (int) webSafeColorArray[2]); assertEquals(0x003300, (int) webSafeColorArray[6]); assertEquals(0x330000, (int) webSafeColorArray[36]); assertEquals(0x000066, (int) webSafeColors.get(2)); assertEquals(0x003300, (int) webSafeColors.get(6)); ImmutableList<Integer> addedColor = webSafeColorsBuilder.add(0x00BFFF).build(); assertEquals("Modifying the builder should not have changed any already" + " built sets", 216, webSafeColors.size()); assertEquals("the new array should be one bigger than webSafeColors", 217, addedColor.size()); Integer[] appendColorArray = addedColor.toArray(new Integer[addedColor.size()]); assertEquals(0x00BFFF, (int) appendColorArray[216]); } public void testBuilderAddHandlesNullsCorrectly() { ImmutableList.Builder<String> builder = ImmutableList.builder(); try { builder.add((String) null); fail("expected NullPointerException"); } catch (NullPointerException expected) { } try { builder.add((String[]) null); fail("expected NullPointerException"); } catch (NullPointerException expected) { } try { builder.add("a", null, "b"); fail("expected NullPointerException"); } catch (NullPointerException expected) { } } public void testBuilderAddAllHandlesNullsCorrectly() { ImmutableList.Builder<String> builder = ImmutableList.builder(); try { builder.addAll((Iterable<String>) null); fail("expected NullPointerException"); } catch (NullPointerException expected) { } try { builder.addAll((Iterator<String>) null); fail("expected NullPointerException"); } catch (NullPointerException expected) { } builder = ImmutableList.builder(); List<String> listWithNulls = asList("a", null, "b"); try { builder.addAll(listWithNulls); fail("expected NullPointerException"); } catch (NullPointerException expected) { } builder = ImmutableList.builder(); Iterator<String> iteratorWithNulls = asList("a", null, "b").iterator(); try { builder.addAll(iteratorWithNulls); fail("expected NullPointerException"); } catch (NullPointerException expected) { } Iterable<String> iterableWithNulls = MinimalIterable.of("a", null, "b"); try { builder.addAll(iterableWithNulls); fail("expected NullPointerException"); } catch (NullPointerException expected) { } } public void testAsList() { ImmutableList<String> list = ImmutableList.of("a", "b"); assertSame(list, list.asList()); } } }
Java
/* * Copyright (C) 2007 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.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.testing.SerializableTester.reserialize; import static com.google.common.testing.SerializableTester.reserializeAndAssert; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.collect.Ordering.ArbitraryOrdering; import com.google.common.collect.Ordering.IncomparableValueException; import com.google.common.collect.testing.Helpers; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.RandomAccess; import javax.annotation.Nullable; /** * Unit tests for {@code Ordering}. * * @author Jesse Wilson */ @GwtCompatible(emulated = true) public class OrderingTest extends TestCase { // TODO(cpovirk): some of these are inexplicably slow (20-30s) under GWT private final Ordering<Number> numberOrdering = new NumberOrdering(); public void testAllEqual() { Ordering<Object> comparator = Ordering.allEqual(); assertSame(comparator, comparator.reverse()); assertEquals(comparator.compare(null, null), 0); assertEquals(comparator.compare(new Object(), new Object()), 0); assertEquals(comparator.compare("apples", "oranges"), 0); assertSame(comparator, reserialize(comparator)); assertEquals("Ordering.allEqual()", comparator.toString()); List<String> strings = ImmutableList.of("b", "a", "d", "c"); assertEquals(strings, comparator.sortedCopy(strings)); assertEquals(strings, comparator.immutableSortedCopy(strings)); } public void testNatural() { Ordering<Integer> comparator = Ordering.natural(); Helpers.testComparator(comparator, Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE); try { comparator.compare(1, null); fail(); } catch (NullPointerException expected) {} try { comparator.compare(null, 2); fail(); } catch (NullPointerException expected) {} try { comparator.compare(null, null); fail(); } catch (NullPointerException expected) {} assertSame(comparator, reserialize(comparator)); assertEquals("Ordering.natural()", comparator.toString()); } public void testFrom() { Ordering<String> caseInsensitiveOrdering = Ordering.from(String.CASE_INSENSITIVE_ORDER); assertEquals(0, caseInsensitiveOrdering.compare("A", "a")); assertTrue(caseInsensitiveOrdering.compare("a", "B") < 0); assertTrue(caseInsensitiveOrdering.compare("B", "a") > 0); @SuppressWarnings("deprecation") // test of deprecated method Ordering<String> orderingFromOrdering = Ordering.from(Ordering.<String>natural()); new EqualsTester() .addEqualityGroup(caseInsensitiveOrdering, Ordering.from(String.CASE_INSENSITIVE_ORDER)) .addEqualityGroup(orderingFromOrdering, Ordering.natural()) .testEquals(); } public void testExplicit_none() { Comparator<Integer> c = Ordering.explicit(Collections.<Integer>emptyList()); try { c.compare(0, 0); fail(); } catch (IncomparableValueException expected) { assertEquals(0, expected.value); } reserializeAndAssert(c); } public void testExplicit_one() { Comparator<Integer> c = Ordering.explicit(0); assertEquals(0, c.compare(0, 0)); try { c.compare(0, 1); fail(); } catch (IncomparableValueException expected) { assertEquals(1, expected.value); } reserializeAndAssert(c); assertEquals("Ordering.explicit([0])", c.toString()); } public void testExplicit_two() { Comparator<Integer> c = Ordering.explicit(42, 5); assertEquals(0, c.compare(5, 5)); assertTrue(c.compare(5, 42) > 0); assertTrue(c.compare(42, 5) < 0); try { c.compare(5, 666); fail(); } catch (IncomparableValueException expected) { assertEquals(666, expected.value); } new EqualsTester() .addEqualityGroup(c, Ordering.explicit(42, 5)) .addEqualityGroup(Ordering.explicit(5, 42)) .addEqualityGroup(Ordering.explicit(42)) .testEquals(); reserializeAndAssert(c); } public void testExplicit_sortingExample() { Comparator<Integer> c = Ordering.explicit(2, 8, 6, 1, 7, 5, 3, 4, 0, 9); List<Integer> list = Arrays.asList(0, 3, 5, 6, 7, 8, 9); Collections.sort(list, c); ASSERT.that(list).has().exactly(8, 6, 7, 5, 3, 0, 9).inOrder(); reserializeAndAssert(c); } public void testExplicit_withDuplicates() { try { Ordering.explicit(1, 2, 3, 4, 2); fail(); } catch (IllegalArgumentException expected) { } } // A more limited test than the one that follows, but this one uses the // actual public API. public void testArbitrary_withoutCollisions() { List<Object> list = Lists.newArrayList(); for (int i = 0; i < 50; i++) { list.add(new Object()); } Ordering<Object> arbitrary = Ordering.arbitrary(); Collections.sort(list, arbitrary); // Now we don't care what order it's put the list in, only that // comparing any pair of elements gives the answer we expect. Helpers.testComparator(arbitrary, list); assertEquals("Ordering.arbitrary()", arbitrary.toString()); } public void testArbitrary_withCollisions() { List<Integer> list = Lists.newArrayList(); for (int i = 0; i < 50; i++) { list.add(i); } Ordering<Object> arbitrary = new ArbitraryOrdering() { @Override int identityHashCode(Object object) { return ((Integer) object) % 5; // fake tons of collisions! } }; // Don't let the elements be in such a predictable order list = shuffledCopy(list, new Random(1)); Collections.sort(list, arbitrary); // Now we don't care what order it's put the list in, only that // comparing any pair of elements gives the answer we expect. Helpers.testComparator(arbitrary, list); } public void testUsingToString() { Ordering<Object> ordering = Ordering.usingToString(); Helpers.testComparator(ordering, 1, 12, 124, 2); assertEquals("Ordering.usingToString()", ordering.toString()); assertSame(ordering, reserialize(ordering)); } // use an enum to get easy serializability private enum CharAtFunction implements Function<String, Character> { AT0(0), AT1(1), AT2(2), AT3(3), AT4(4), AT5(5), ; final int index; CharAtFunction(int index) { this.index = index; } @Override public Character apply(String string) { return string.charAt(index); } } private static Ordering<String> byCharAt(int index) { return Ordering.natural().onResultOf(CharAtFunction.values()[index]); } public void testCompound_static() { Comparator<String> comparator = Ordering.compound(ImmutableList.of( byCharAt(0), byCharAt(1), byCharAt(2), byCharAt(3), byCharAt(4), byCharAt(5))); Helpers.testComparator(comparator, ImmutableList.of( "applesauce", "apricot", "artichoke", "banality", "banana", "banquet", "tangelo", "tangerine")); reserializeAndAssert(comparator); } public void testCompound_instance() { Comparator<String> comparator = byCharAt(1).compound(byCharAt(0)); Helpers.testComparator(comparator, ImmutableList.of( "red", "yellow", "violet", "blue", "indigo", "green", "orange")); } public void testCompound_instance_generics() { Ordering<Object> objects = Ordering.explicit((Object) 1); Ordering<Number> numbers = Ordering.explicit((Number) 1); Ordering<Integer> integers = Ordering.explicit(1); // Like by like equals like Ordering<Number> a = numbers.compound(numbers); // The compound takes the more specific type of the two, regardless of order Ordering<Number> b = numbers.compound(objects); Ordering<Number> c = objects.compound(numbers); Ordering<Integer> d = numbers.compound(integers); Ordering<Integer> e = integers.compound(numbers); // This works with three levels too (IDEA falsely reports errors as noted // below. Both javac and eclipse handle these cases correctly.) Ordering<Number> f = numbers.compound(objects).compound(objects); //bad IDEA Ordering<Number> g = objects.compound(numbers).compound(objects); Ordering<Number> h = objects.compound(objects).compound(numbers); Ordering<Number> i = numbers.compound(objects.compound(objects)); Ordering<Number> j = objects.compound(numbers.compound(objects)); //bad IDEA Ordering<Number> k = objects.compound(objects.compound(numbers)); // You can also arbitrarily assign a more restricted type - not an intended // feature, exactly, but unavoidable (I think) and harmless Ordering<Integer> l = objects.compound(numbers); // This correctly doesn't work: // Ordering<Object> m = numbers.compound(objects); // Sadly, the following works in javac 1.6, but at least it fails for // eclipse, and is *correctly* highlighted red in IDEA. // Ordering<Object> n = objects.compound(numbers); } public void testReverse() { Ordering<Number> reverseOrder = numberOrdering.reverse(); Helpers.testComparator(reverseOrder, Integer.MAX_VALUE, 1, 0, -1, Integer.MIN_VALUE); new EqualsTester() .addEqualityGroup(reverseOrder, numberOrdering.reverse()) .addEqualityGroup(Ordering.natural().reverse()) .addEqualityGroup(Collections.reverseOrder()) .testEquals(); } public void testReverseOfReverseSameAsForward() { // Not guaranteed by spec, but it works, and saves us from testing // exhaustively assertSame(numberOrdering, numberOrdering.reverse().reverse()); } private enum StringLengthFunction implements Function<String, Integer> { StringLength; @Override public Integer apply(String string) { return string.length(); } } private static final Ordering<Integer> DECREASING_INTEGER = Ordering.natural().reverse(); public void testOnResultOf_natural() { Comparator<String> comparator = Ordering.natural().onResultOf(StringLengthFunction.StringLength); assertTrue(comparator.compare("to", "be") == 0); assertTrue(comparator.compare("or", "not") < 0); assertTrue(comparator.compare("that", "to") > 0); new EqualsTester() .addEqualityGroup( comparator, Ordering.natural().onResultOf(StringLengthFunction.StringLength)) .addEqualityGroup(DECREASING_INTEGER) .testEquals(); reserializeAndAssert(comparator); assertEquals("Ordering.natural().onResultOf(StringLength)", comparator.toString()); } public void testOnResultOf_chained() { Comparator<String> comparator = DECREASING_INTEGER.onResultOf( StringLengthFunction.StringLength); assertTrue(comparator.compare("to", "be") == 0); assertTrue(comparator.compare("not", "or") < 0); assertTrue(comparator.compare("to", "that") > 0); new EqualsTester() .addEqualityGroup( comparator, DECREASING_INTEGER.onResultOf(StringLengthFunction.StringLength)) .addEqualityGroup( DECREASING_INTEGER.onResultOf(Functions.constant(1))) .addEqualityGroup(Ordering.natural()) .testEquals(); reserializeAndAssert(comparator); assertEquals("Ordering.natural().reverse().onResultOf(StringLength)", comparator.toString()); } @SuppressWarnings("unchecked") // dang varargs public void testLexicographical() { Ordering<String> ordering = Ordering.natural(); Ordering<Iterable<String>> lexy = ordering.lexicographical(); ImmutableList<String> empty = ImmutableList.of(); ImmutableList<String> a = ImmutableList.of("a"); ImmutableList<String> aa = ImmutableList.of("a", "a"); ImmutableList<String> ab = ImmutableList.of("a", "b"); ImmutableList<String> b = ImmutableList.of("b"); Helpers.testComparator(lexy, empty, a, aa, ab, b); new EqualsTester() .addEqualityGroup(lexy, ordering.lexicographical()) .addEqualityGroup(numberOrdering.lexicographical()) .addEqualityGroup(Ordering.natural()) .testEquals(); } public void testNullsFirst() { Ordering<Integer> ordering = Ordering.natural().nullsFirst(); Helpers.testComparator(ordering, null, Integer.MIN_VALUE, 0, 1); new EqualsTester() .addEqualityGroup(ordering, Ordering.natural().nullsFirst()) .addEqualityGroup(numberOrdering.nullsFirst()) .addEqualityGroup(Ordering.natural()) .testEquals(); } public void testNullsLast() { Ordering<Integer> ordering = Ordering.natural().nullsLast(); Helpers.testComparator(ordering, 0, 1, Integer.MAX_VALUE, null); new EqualsTester() .addEqualityGroup(ordering, Ordering.natural().nullsLast()) .addEqualityGroup(numberOrdering.nullsLast()) .addEqualityGroup(Ordering.natural()) .testEquals(); } public void testBinarySearch() { List<Integer> ints = Lists.newArrayList(0, 2, 3, 5, 7, 9); assertEquals(4, numberOrdering.binarySearch(ints, 7)); } public void testSortedCopy() { List<Integer> unsortedInts = Collections.unmodifiableList( Arrays.asList(5, 0, 3, null, 0, 9)); List<Integer> sortedInts = numberOrdering.nullsLast().sortedCopy(unsortedInts); assertEquals(Arrays.asList(0, 0, 3, 5, 9, null), sortedInts); assertEquals(Collections.emptyList(), numberOrdering.sortedCopy(Collections.<Integer>emptyList())); } public void testImmutableSortedCopy() { ImmutableList<Integer> unsortedInts = ImmutableList.of(5, 3, 0, 9, 3); ImmutableList<Integer> sortedInts = numberOrdering.immutableSortedCopy(unsortedInts); assertEquals(Arrays.asList(0, 3, 3, 5, 9), sortedInts); assertEquals(Collections.<Integer>emptyList(), numberOrdering.immutableSortedCopy(Collections.<Integer>emptyList())); List<Integer> listWithNull = Arrays.asList(5, 3, null, 9); try { Ordering.natural().nullsFirst().immutableSortedCopy(listWithNull); fail(); } catch (NullPointerException expected) { } } public void testIsOrdered() { assertFalse(numberOrdering.isOrdered(asList(5, 3, 0, 9))); assertFalse(numberOrdering.isOrdered(asList(0, 5, 3, 9))); assertTrue(numberOrdering.isOrdered(asList(0, 3, 5, 9))); assertTrue(numberOrdering.isOrdered(asList(0, 0, 3, 3))); assertTrue(numberOrdering.isOrdered(asList(0, 3))); assertTrue(numberOrdering.isOrdered(Collections.singleton(1))); assertTrue(numberOrdering.isOrdered(Collections.<Integer>emptyList())); } public void testIsStrictlyOrdered() { assertFalse(numberOrdering.isStrictlyOrdered(asList(5, 3, 0, 9))); assertFalse(numberOrdering.isStrictlyOrdered(asList(0, 5, 3, 9))); assertTrue(numberOrdering.isStrictlyOrdered(asList(0, 3, 5, 9))); assertFalse(numberOrdering.isStrictlyOrdered(asList(0, 0, 3, 3))); assertTrue(numberOrdering.isStrictlyOrdered(asList(0, 3))); assertTrue(numberOrdering.isStrictlyOrdered(Collections.singleton(1))); assertTrue(numberOrdering.isStrictlyOrdered( Collections.<Integer>emptyList())); } public void testLeastOfIterable_empty_0() { List<Integer> result = numberOrdering.leastOf(Arrays.<Integer>asList(), 0); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterator_empty_0() { List<Integer> result = numberOrdering.leastOf( Iterators.<Integer>emptyIterator(), 0); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterable_empty_1() { List<Integer> result = numberOrdering.leastOf(Arrays.<Integer>asList(), 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterator_empty_1() { List<Integer> result = numberOrdering.leastOf( Iterators.<Integer>emptyIterator(), 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterable_simple_negativeOne() { try { numberOrdering.leastOf(Arrays.asList(3, 4, 5, -1), -1); fail(); } catch (IllegalArgumentException expected) { } } public void testLeastOfIterator_simple_negativeOne() { try { numberOrdering.leastOf(Iterators.forArray(3, 4, 5, -1), -1); fail(); } catch (IllegalArgumentException expected) { } } public void testLeastOfIterable_singleton_0() { List<Integer> result = numberOrdering.leastOf(Arrays.asList(3), 0); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterator_singleton_0() { List<Integer> result = numberOrdering.leastOf( Iterators.singletonIterator(3), 0); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterable_simple_0() { List<Integer> result = numberOrdering.leastOf(Arrays.asList(3, 4, 5, -1), 0); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterator_simple_0() { List<Integer> result = numberOrdering.leastOf( Iterators.forArray(3, 4, 5, -1), 0); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterable_simple_1() { List<Integer> result = numberOrdering.leastOf(Arrays.asList(3, 4, 5, -1), 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1), result); } public void testLeastOfIterator_simple_1() { List<Integer> result = numberOrdering.leastOf( Iterators.forArray(3, 4, 5, -1), 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1), result); } public void testLeastOfIterable_simple_nMinusOne_withNullElement() { List<Integer> list = Arrays.asList(3, null, 5, -1); List<Integer> result = Ordering.natural().nullsLast().leastOf(list, list.size() - 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 5), result); } public void testLeastOfIterator_simple_nMinusOne_withNullElement() { Iterator<Integer> itr = Iterators.forArray(3, null, 5, -1); List<Integer> result = Ordering.natural().nullsLast().leastOf(itr, 3); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 5), result); } public void testLeastOfIterable_simple_nMinusOne() { List<Integer> list = Arrays.asList(3, 4, 5, -1); List<Integer> result = numberOrdering.leastOf(list, list.size() - 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 4), result); } public void testLeastOfIterator_simple_nMinusOne() { List<Integer> list = Arrays.asList(3, 4, 5, -1); List<Integer> result = numberOrdering.leastOf(list.iterator(), list.size() - 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 4), result); } public void testLeastOfIterable_simple_n() { List<Integer> list = Arrays.asList(3, 4, 5, -1); List<Integer> result = numberOrdering.leastOf(list, list.size()); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 4, 5), result); } public void testLeastOfIterator_simple_n() { List<Integer> list = Arrays.asList(3, 4, 5, -1); List<Integer> result = numberOrdering.leastOf(list.iterator(), list.size()); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 4, 5), result); } public void testLeastOfIterable_simple_n_withNullElement() { List<Integer> list = Arrays.asList(3, 4, 5, null, -1); List<Integer> result = Ordering.natural().nullsLast().leastOf(list, list.size()); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(Arrays.asList(-1, 3, 4, 5, null), result); } public void testLeastOfIterator_simple_n_withNullElement() { List<Integer> list = Arrays.asList(3, 4, 5, null, -1); List<Integer> result = Ordering.natural().nullsLast().leastOf( list.iterator(), list.size()); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(Arrays.asList(-1, 3, 4, 5, null), result); } public void testLeastOfIterable_simple_nPlusOne() { List<Integer> list = Arrays.asList(3, 4, 5, -1); List<Integer> result = numberOrdering.leastOf(list, list.size() + 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 4, 5), result); } public void testLeastOfIterator_simple_nPlusOne() { List<Integer> list = Arrays.asList(3, 4, 5, -1); List<Integer> result = numberOrdering.leastOf(list.iterator(), list.size() + 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 4, 5), result); } public void testLeastOfIterable_ties() { Integer foo = new Integer(Integer.MAX_VALUE - 10); Integer bar = new Integer(Integer.MAX_VALUE - 10); assertNotSame(foo, bar); assertEquals(foo, bar); List<Integer> list = Arrays.asList(3, foo, bar, -1); List<Integer> result = numberOrdering.leastOf(list, list.size()); assertEquals(ImmutableList.of(-1, 3, foo, bar), result); } public void testLeastOfIterator_ties() { Integer foo = new Integer(Integer.MAX_VALUE - 10); Integer bar = new Integer(Integer.MAX_VALUE - 10); assertNotSame(foo, bar); assertEquals(foo, bar); List<Integer> list = Arrays.asList(3, foo, bar, -1); List<Integer> result = numberOrdering.leastOf(list.iterator(), list.size()); assertEquals(ImmutableList.of(-1, 3, foo, bar), result); } public void testLeastOf_reconcileAgainstSortAndSublistSmall() { runLeastOfComparison(10, 30, 2); } private static void runLeastOfComparison( int iterations, int elements, int seeds) { Random random = new Random(42); Ordering<Integer> ordering = Ordering.natural(); for (int i = 0; i < iterations; i++) { List<Integer> list = Lists.newArrayList(); for (int j = 0; j < elements; j++) { list.add(random.nextInt(10 * i + j + 1)); } for (int seed = 1; seed < seeds; seed++) { int k = random.nextInt(10 * seed); assertEquals(ordering.sortedCopy(list).subList(0, k), ordering.leastOf(list, k)); } } } public void testLeastOfIterableLargeK() { List<Integer> list = Arrays.asList(4, 2, 3, 5, 1); assertEquals(Arrays.asList(1, 2, 3, 4, 5), Ordering.natural() .leastOf(list, Integer.MAX_VALUE)); } public void testLeastOfIteratorLargeK() { List<Integer> list = Arrays.asList(4, 2, 3, 5, 1); assertEquals(Arrays.asList(1, 2, 3, 4, 5), Ordering.natural() .leastOf(list.iterator(), Integer.MAX_VALUE)); } public void testGreatestOfIterable_simple() { /* * If greatestOf() promised to be implemented as reverse().leastOf(), this * test would be enough. It doesn't... but we'll cheat and act like it does * anyway. There's a comment there to remind us to fix this if we change it. */ List<Integer> list = Arrays.asList(3, 1, 3, 2, 4, 2, 4, 3); assertEquals(Arrays.asList(4, 4, 3, 3), numberOrdering.greatestOf(list, 4)); } public void testGreatestOfIterator_simple() { /* * If greatestOf() promised to be implemented as reverse().leastOf(), this * test would be enough. It doesn't... but we'll cheat and act like it does * anyway. There's a comment there to remind us to fix this if we change it. */ List<Integer> list = Arrays.asList(3, 1, 3, 2, 4, 2, 4, 3); assertEquals(Arrays.asList(4, 4, 3, 3), numberOrdering.greatestOf(list.iterator(), 4)); } private static void assertListImmutable(List<Integer> result) { try { result.set(0, 1); fail(); } catch (UnsupportedOperationException expected) { // pass } } public void testIteratorMinAndMax() { List<Integer> ints = Lists.newArrayList(5, 3, 0, 9); assertEquals(9, (int) numberOrdering.max(ints.iterator())); assertEquals(0, (int) numberOrdering.min(ints.iterator())); // when the values are the same, the first argument should be returned Integer a = new Integer(4); Integer b = new Integer(4); ints = Lists.newArrayList(a, b, b); assertSame(a, numberOrdering.max(ints.iterator())); assertSame(a, numberOrdering.min(ints.iterator())); } public void testIteratorMinExhaustsIterator() { List<Integer> ints = Lists.newArrayList(9, 0, 3, 5); Iterator<Integer> iterator = ints.iterator(); assertEquals(0, (int) numberOrdering.min(iterator)); assertFalse(iterator.hasNext()); } public void testIteratorMaxExhaustsIterator() { List<Integer> ints = Lists.newArrayList(9, 0, 3, 5); Iterator<Integer> iterator = ints.iterator(); assertEquals(9, (int) numberOrdering.max(iterator)); assertFalse(iterator.hasNext()); } public void testIterableMinAndMax() { List<Integer> ints = Lists.newArrayList(5, 3, 0, 9); assertEquals(9, (int) numberOrdering.max(ints)); assertEquals(0, (int) numberOrdering.min(ints)); // when the values are the same, the first argument should be returned Integer a = new Integer(4); Integer b = new Integer(4); ints = Lists.newArrayList(a, b, b); assertSame(a, numberOrdering.max(ints)); assertSame(a, numberOrdering.min(ints)); } public void testVarargsMinAndMax() { // try the min and max values in all positions, since some values are proper // parameters and others are from the varargs array assertEquals(9, (int) numberOrdering.max(9, 3, 0, 5, 8)); assertEquals(9, (int) numberOrdering.max(5, 9, 0, 3, 8)); assertEquals(9, (int) numberOrdering.max(5, 3, 9, 0, 8)); assertEquals(9, (int) numberOrdering.max(5, 3, 0, 9, 8)); assertEquals(9, (int) numberOrdering.max(5, 3, 0, 8, 9)); assertEquals(0, (int) numberOrdering.min(0, 3, 5, 9, 8)); assertEquals(0, (int) numberOrdering.min(5, 0, 3, 9, 8)); assertEquals(0, (int) numberOrdering.min(5, 3, 0, 9, 8)); assertEquals(0, (int) numberOrdering.min(5, 3, 9, 0, 8)); assertEquals(0, (int) numberOrdering.min(5, 3, 0, 9, 0)); // when the values are the same, the first argument should be returned Integer a = new Integer(4); Integer b = new Integer(4); assertSame(a, numberOrdering.max(a, b, b)); assertSame(a, numberOrdering.min(a, b, b)); } public void testParameterMinAndMax() { assertEquals(5, (int) numberOrdering.max(3, 5)); assertEquals(5, (int) numberOrdering.max(5, 3)); assertEquals(3, (int) numberOrdering.min(3, 5)); assertEquals(3, (int) numberOrdering.min(5, 3)); // when the values are the same, the first argument should be returned Integer a = new Integer(4); Integer b = new Integer(4); assertSame(a, numberOrdering.max(a, b)); assertSame(a, numberOrdering.min(a, b)); } private static class NumberOrdering extends Ordering<Number> { @Override public int compare(Number a, Number b) { return ((Double) a.doubleValue()).compareTo(b.doubleValue()); } @Override public int hashCode() { return NumberOrdering.class.hashCode(); } @Override public boolean equals(Object other) { return other instanceof NumberOrdering; } private static final long serialVersionUID = 0; } /* * Now we have monster tests that create hundreds of Orderings using different * combinations of methods, then checks compare(), binarySearch() and so * forth on each one. */ // should periodically try increasing this, but it makes the test run long private static final int RECURSE_DEPTH = 2; public void testCombinationsExhaustively_startingFromNatural() { testExhaustively(Ordering.<String>natural(), "a", "b", "d"); } /** * Requires at least 3 elements in {@code strictlyOrderedElements} in order to * test the varargs version of min/max. */ private static <T> void testExhaustively( Ordering<? super T> ordering, T... strictlyOrderedElements) { checkArgument(strictlyOrderedElements.length >= 3, "strictlyOrderedElements " + "requires at least 3 elements"); List<T> list = Arrays.asList(strictlyOrderedElements); // for use calling Collection.toArray later T[] emptyArray = Platform.newArray(strictlyOrderedElements, 0); // shoot me, but I didn't want to deal with wildcards through the whole test @SuppressWarnings("unchecked") Scenario<T> starter = new Scenario<T>((Ordering) ordering, list, emptyArray); verifyScenario(starter, 0); } private static <T> void verifyScenario(Scenario<T> scenario, int level) { scenario.testCompareTo(); scenario.testIsOrdered(); scenario.testMinAndMax(); scenario.testBinarySearch(); scenario.testSortedCopy(); if (level < RECURSE_DEPTH) { for (OrderingMutation alteration : OrderingMutation.values()) { verifyScenario(alteration.mutate(scenario), level + 1); } } } /** * An aggregation of an ordering with a list (of size > 1) that should prove * to be in strictly increasing order according to that ordering. */ private static class Scenario<T> { final Ordering<T> ordering; final List<T> strictlyOrderedList; final T[] emptyArray; Scenario(Ordering<T> ordering, List<T> strictlyOrderedList, T[] emptyArray) { this.ordering = ordering; this.strictlyOrderedList = strictlyOrderedList; this.emptyArray = emptyArray; } void testCompareTo() { Helpers.testComparator(ordering, strictlyOrderedList); } void testIsOrdered() { assertTrue(ordering.isOrdered(strictlyOrderedList)); assertTrue(ordering.isStrictlyOrdered(strictlyOrderedList)); } @SuppressWarnings("unchecked") // generic arrays and unchecked cast void testMinAndMax() { List<T> shuffledList = Lists.newArrayList(strictlyOrderedList); shuffledList = shuffledCopy(shuffledList, new Random(5)); T min = strictlyOrderedList.get(0); T max = strictlyOrderedList.get(strictlyOrderedList.size() - 1); T first = shuffledList.get(0); T second = shuffledList.get(1); T third = shuffledList.get(2); T[] rest = shuffledList.subList(3, shuffledList.size()).toArray(emptyArray); assertEquals(min, ordering.min(shuffledList)); assertEquals(min, ordering.min(shuffledList.iterator())); assertEquals(min, ordering.min(first, second, third, rest)); assertEquals(min, ordering.min(min, max)); assertEquals(min, ordering.min(max, min)); assertEquals(max, ordering.max(shuffledList)); assertEquals(max, ordering.max(shuffledList.iterator())); assertEquals(max, ordering.max(first, second, third, rest)); assertEquals(max, ordering.max(min, max)); assertEquals(max, ordering.max(max, min)); } void testBinarySearch() { for (int i = 0; i < strictlyOrderedList.size(); i++) { assertEquals(i, ordering.binarySearch( strictlyOrderedList, strictlyOrderedList.get(i))); } List<T> newList = Lists.newArrayList(strictlyOrderedList); T valueNotInList = newList.remove(1); assertEquals(-2, ordering.binarySearch(newList, valueNotInList)); } void testSortedCopy() { List<T> shuffledList = Lists.newArrayList(strictlyOrderedList); shuffledList = shuffledCopy(shuffledList, new Random(5)); assertEquals(strictlyOrderedList, ordering.sortedCopy(shuffledList)); if (!strictlyOrderedList.contains(null)) { assertEquals(strictlyOrderedList, ordering.immutableSortedCopy(shuffledList)); } } } /** * A means for changing an Ordering into another Ordering. Each instance is * responsible for creating the alternate Ordering, and providing a List that * is known to be ordered, based on an input List known to be ordered * according to the input Ordering. */ private enum OrderingMutation { REVERSE { @Override <T> Scenario<?> mutate(Scenario<T> scenario) { List<T> newList = Lists.newArrayList(scenario.strictlyOrderedList); Collections.reverse(newList); return new Scenario<T>(scenario.ordering.reverse(), newList, scenario.emptyArray); } }, NULLS_FIRST { @Override <T> Scenario<?> mutate(Scenario<T> scenario) { @SuppressWarnings("unchecked") List<T> newList = Lists.newArrayList((T) null); for (T t : scenario.strictlyOrderedList) { if (t != null) { newList.add(t); } } return new Scenario<T>(scenario.ordering.nullsFirst(), newList, scenario.emptyArray); } }, NULLS_LAST { @Override <T> Scenario<?> mutate(Scenario<T> scenario) { List<T> newList = Lists.newArrayList(); for (T t : scenario.strictlyOrderedList) { if (t != null) { newList.add(t); } } newList.add(null); return new Scenario<T>(scenario.ordering.nullsLast(), newList, scenario.emptyArray); } }, ON_RESULT_OF { @Override <T> Scenario<?> mutate(final Scenario<T> scenario) { Ordering<Integer> ordering = scenario.ordering.onResultOf( new Function<Integer, T>() { @Override public T apply(@Nullable Integer from) { return scenario.strictlyOrderedList.get(from); } }); List<Integer> list = Lists.newArrayList(); for (int i = 0; i < scenario.strictlyOrderedList.size(); i++) { list.add(i); } return new Scenario<Integer>(ordering, list, new Integer[0]); } }, COMPOUND_THIS_WITH_NATURAL { @SuppressWarnings("unchecked") // raw array @Override <T> Scenario<?> mutate(Scenario<T> scenario) { List<Composite<T>> composites = Lists.newArrayList(); for (T t : scenario.strictlyOrderedList) { composites.add(new Composite<T>(t, 1)); composites.add(new Composite<T>(t, 2)); } Ordering<Composite<T>> ordering = scenario.ordering.onResultOf(Composite.<T>getValueFunction()) .compound(Ordering.natural()); return new Scenario<Composite<T>>(ordering, composites, new Composite[0]); } }, COMPOUND_NATURAL_WITH_THIS { @SuppressWarnings("unchecked") // raw array @Override <T> Scenario<?> mutate(Scenario<T> scenario) { List<Composite<T>> composites = Lists.newArrayList(); for (T t : scenario.strictlyOrderedList) { composites.add(new Composite<T>(t, 1)); } for (T t : scenario.strictlyOrderedList) { composites.add(new Composite<T>(t, 2)); } Ordering<Composite<T>> ordering = Ordering.natural().compound( scenario.ordering.onResultOf(Composite.<T>getValueFunction())); return new Scenario<Composite<T>>(ordering, composites, new Composite[0]); } }, LEXICOGRAPHICAL { @SuppressWarnings("unchecked") // dang varargs @Override <T> Scenario<?> mutate(Scenario<T> scenario) { List<Iterable<T>> words = Lists.newArrayList(); words.add(Collections.<T>emptyList()); for (T t : scenario.strictlyOrderedList) { words.add(Arrays.asList(t)); for (T s : scenario.strictlyOrderedList) { words.add(Arrays.asList(t, s)); } } return new Scenario<Iterable<T>>( scenario.ordering.lexicographical(), words, new Iterable[0]); } }, ; abstract <T> Scenario<?> mutate(Scenario<T> scenario); } /** * A dummy object we create so that we can have something meaningful to have * a compound ordering over. */ private static class Composite<T> implements Comparable<Composite<T>> { final T value; final int rank; Composite(T value, int rank) { this.value = value; this.rank = rank; } // natural order is by rank only; the test will compound() this with the // order of 't'. @Override public int compareTo(Composite<T> that) { return rank < that.rank ? -1 : rank > that.rank ? 1 : 0; } static <T> Function<Composite<T>, T> getValueFunction() { return new Function<Composite<T>, T>() { @Override public T apply(Composite<T> from) { return from.value; } }; } } private static <T> List<T> shuffledCopy(List<T> in, Random random) { List<T> mutable = newArrayList(in); List<T> out = newArrayList(); while (!mutable.isEmpty()) { out.add(mutable.remove(random.nextInt(mutable.size()))); } return out; } }
Java
/* * Copyright (C) 2007 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.collect; import static com.google.common.collect.Iterables.unmodifiableIterable; import static com.google.common.collect.Sets.newEnumSet; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.powerSet; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.IteratorTester; import com.google.common.collect.testing.MinimalIterable; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nullable; /** * Unit test for {@code Sets}. * * @author Kevin Bourrillion * @author Jared Levy */ @GwtCompatible(emulated = true) public class SetsTest extends TestCase { private static final IteratorTester.KnownOrder KNOWN_ORDER = IteratorTester.KnownOrder.KNOWN_ORDER; private static final Collection<Integer> EMPTY_COLLECTION = Arrays.<Integer>asList(); private static final Collection<Integer> SOME_COLLECTION = Arrays.asList(0, 1, 1); private static final Iterable<Integer> SOME_ITERABLE = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return SOME_COLLECTION.iterator(); } }; private static final List<Integer> LONGER_LIST = Arrays.asList(8, 6, 7, 5, 3, 0, 9); private static final Comparator<Integer> SOME_COMPARATOR = Collections.reverseOrder(); private enum SomeEnum { A, B, C, D } public void testImmutableEnumSet() { Set<SomeEnum> units = Sets.immutableEnumSet(SomeEnum.D, SomeEnum.B); ASSERT.that(units).has().exactly(SomeEnum.B, SomeEnum.D).inOrder(); try { units.remove(SomeEnum.B); fail("ImmutableEnumSet should throw an exception on remove()"); } catch (UnsupportedOperationException expected) {} try { units.add(SomeEnum.C); fail("ImmutableEnumSet should throw an exception on add()"); } catch (UnsupportedOperationException expected) {} } public void testImmutableEnumSet_fromIterable() { ImmutableSet<SomeEnum> none = Sets.immutableEnumSet(MinimalIterable.<SomeEnum>of()); ASSERT.that(none).isEmpty(); ImmutableSet<SomeEnum> one = Sets.immutableEnumSet(MinimalIterable.of(SomeEnum.B)); ASSERT.that(one).has().item(SomeEnum.B); ImmutableSet<SomeEnum> two = Sets.immutableEnumSet(MinimalIterable.of(SomeEnum.D, SomeEnum.B)); ASSERT.that(two).has().exactly(SomeEnum.B, SomeEnum.D).inOrder(); } private static byte[] prepended(byte b, byte[] array) { byte[] out = new byte[array.length + 1]; out[0] = b; System.arraycopy(array, 0, out, 1, array.length); return out; } public void testNewEnumSet_empty() { EnumSet<SomeEnum> copy = newEnumSet(Collections.<SomeEnum>emptySet(), SomeEnum.class); assertEquals(EnumSet.noneOf(SomeEnum.class), copy); } public void testNewEnumSet_enumSet() { EnumSet<SomeEnum> set = EnumSet.of(SomeEnum.A, SomeEnum.D); assertEquals(set, newEnumSet(set, SomeEnum.class)); } public void testNewEnumSet_collection() { Set<SomeEnum> set = ImmutableSet.of(SomeEnum.B, SomeEnum.C); assertEquals(set, newEnumSet(set, SomeEnum.class)); } public void testNewEnumSet_iterable() { Set<SomeEnum> set = ImmutableSet.of(SomeEnum.A, SomeEnum.B, SomeEnum.C); assertEquals(set, newEnumSet(unmodifiableIterable(set), SomeEnum.class)); } public void testNewHashSetEmpty() { HashSet<Integer> set = Sets.newHashSet(); verifySetContents(set, EMPTY_COLLECTION); } public void testNewHashSetVarArgs() { HashSet<Integer> set = Sets.newHashSet(0, 1, 1); verifySetContents(set, Arrays.asList(0, 1)); } public void testNewHashSetFromCollection() { HashSet<Integer> set = Sets.newHashSet(SOME_COLLECTION); verifySetContents(set, SOME_COLLECTION); } public void testNewHashSetFromIterable() { HashSet<Integer> set = Sets.newHashSet(SOME_ITERABLE); verifySetContents(set, SOME_ITERABLE); } public void testNewHashSetWithExpectedSizeSmall() { HashSet<Integer> set = Sets.newHashSetWithExpectedSize(0); verifySetContents(set, EMPTY_COLLECTION); } public void testNewHashSetWithExpectedSizeLarge() { HashSet<Integer> set = Sets.newHashSetWithExpectedSize(1000); verifySetContents(set, EMPTY_COLLECTION); } public void testNewHashSetFromIterator() { HashSet<Integer> set = Sets.newHashSet(SOME_COLLECTION.iterator()); verifySetContents(set, SOME_COLLECTION); } public void testNewConcurrentHashSetEmpty() { Set<Integer> set = Sets.newConcurrentHashSet(); verifySetContents(set, EMPTY_COLLECTION); } public void testNewConcurrentHashSetFromCollection() { Set<Integer> set = Sets.newConcurrentHashSet(SOME_COLLECTION); verifySetContents(set, SOME_COLLECTION); } public void testNewLinkedHashSetEmpty() { LinkedHashSet<Integer> set = Sets.newLinkedHashSet(); verifyLinkedHashSetContents(set, EMPTY_COLLECTION); } public void testNewLinkedHashSetFromCollection() { LinkedHashSet<Integer> set = Sets.newLinkedHashSet(LONGER_LIST); verifyLinkedHashSetContents(set, LONGER_LIST); } public void testNewLinkedHashSetFromIterable() { LinkedHashSet<Integer> set = Sets.newLinkedHashSet(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return LONGER_LIST.iterator(); } }); verifyLinkedHashSetContents(set, LONGER_LIST); } public void testNewLinkedHashSetWithExpectedSizeSmall() { LinkedHashSet<Integer> set = Sets.newLinkedHashSetWithExpectedSize(0); verifySetContents(set, EMPTY_COLLECTION); } public void testNewLinkedHashSetWithExpectedSizeLarge() { LinkedHashSet<Integer> set = Sets.newLinkedHashSetWithExpectedSize(1000); verifySetContents(set, EMPTY_COLLECTION); } public void testNewTreeSetEmpty() { TreeSet<Integer> set = Sets.newTreeSet(); verifySortedSetContents(set, EMPTY_COLLECTION, null); } public void testNewTreeSetEmptyDerived() { TreeSet<Derived> set = Sets.newTreeSet(); assertTrue(set.isEmpty()); set.add(new Derived("foo")); set.add(new Derived("bar")); ASSERT.that(set).has().exactly(new Derived("bar"), new Derived("foo")).inOrder(); } public void testNewTreeSetEmptyNonGeneric() { TreeSet<LegacyComparable> set = Sets.newTreeSet(); assertTrue(set.isEmpty()); set.add(new LegacyComparable("foo")); set.add(new LegacyComparable("bar")); ASSERT.that(set).has() .exactly(new LegacyComparable("bar"), new LegacyComparable("foo")).inOrder(); } public void testNewTreeSetFromCollection() { TreeSet<Integer> set = Sets.newTreeSet(SOME_COLLECTION); verifySortedSetContents(set, SOME_COLLECTION, null); } public void testNewTreeSetFromIterable() { TreeSet<Integer> set = Sets.newTreeSet(SOME_ITERABLE); verifySortedSetContents(set, SOME_ITERABLE, null); } public void testNewTreeSetFromIterableDerived() { Iterable<Derived> iterable = Arrays.asList(new Derived("foo"), new Derived("bar")); TreeSet<Derived> set = Sets.newTreeSet(iterable); ASSERT.that(set).has().exactly( new Derived("bar"), new Derived("foo")).inOrder(); } public void testNewTreeSetFromIterableNonGeneric() { Iterable<LegacyComparable> iterable = Arrays.asList(new LegacyComparable("foo"), new LegacyComparable("bar")); TreeSet<LegacyComparable> set = Sets.newTreeSet(iterable); ASSERT.that(set).has().exactly( new LegacyComparable("bar"), new LegacyComparable("foo")).inOrder(); } public void testNewTreeSetEmptyWithComparator() { TreeSet<Integer> set = Sets.newTreeSet(SOME_COMPARATOR); verifySortedSetContents(set, EMPTY_COLLECTION, SOME_COMPARATOR); } public void testNewIdentityHashSet() { Set<Integer> set = Sets.newIdentityHashSet(); Integer value1 = new Integer(12357); Integer value2 = new Integer(12357); assertTrue(set.add(value1)); assertFalse(set.contains(value2)); assertTrue(set.contains(value1)); assertTrue(set.add(value2)); assertEquals(2, set.size()); } public void testComplementOfEnumSet() { Set<SomeEnum> units = EnumSet.of(SomeEnum.B, SomeEnum.D); EnumSet<SomeEnum> otherUnits = Sets.complementOf(units); verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C)); } public void testComplementOfEnumSetWithType() { Set<SomeEnum> units = EnumSet.of(SomeEnum.B, SomeEnum.D); EnumSet<SomeEnum> otherUnits = Sets.complementOf(units, SomeEnum.class); verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C)); } public void testComplementOfRegularSet() { Set<SomeEnum> units = Sets.newHashSet(SomeEnum.B, SomeEnum.D); EnumSet<SomeEnum> otherUnits = Sets.complementOf(units); verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C)); } public void testComplementOfRegularSetWithType() { Set<SomeEnum> units = Sets.newHashSet(SomeEnum.B, SomeEnum.D); EnumSet<SomeEnum> otherUnits = Sets.complementOf(units, SomeEnum.class); verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C)); } public void testComplementOfEmptySet() { Set<SomeEnum> noUnits = Collections.emptySet(); EnumSet<SomeEnum> allUnits = Sets.complementOf(noUnits, SomeEnum.class); verifySetContents(EnumSet.allOf(SomeEnum.class), allUnits); } public void testComplementOfFullSet() { Set<SomeEnum> allUnits = Sets.newHashSet(SomeEnum.values()); EnumSet<SomeEnum> noUnits = Sets.complementOf(allUnits, SomeEnum.class); verifySetContents(noUnits, EnumSet.noneOf(SomeEnum.class)); } public void testComplementOfEmptyEnumSetWithoutType() { Set<SomeEnum> noUnits = EnumSet.noneOf(SomeEnum.class); EnumSet<SomeEnum> allUnits = Sets.complementOf(noUnits); verifySetContents(allUnits, EnumSet.allOf(SomeEnum.class)); } public void testComplementOfEmptySetWithoutTypeDoesntWork() { Set<SomeEnum> set = Collections.emptySet(); try { Sets.complementOf(set); fail(); } catch (IllegalArgumentException expected) {} } public void testNewSetFromMap() { Set<Integer> set = Sets.newSetFromMap(new HashMap<Integer, Boolean>()); set.addAll(SOME_COLLECTION); verifySetContents(set, SOME_COLLECTION); } public void testNewSetFromMapIllegal() { Map<Integer, Boolean> map = new LinkedHashMap<Integer, Boolean>(); map.put(2, true); try { Sets.newSetFromMap(map); fail(); } catch (IllegalArgumentException expected) {} } // TODO: the overwhelming number of suppressions below suggests that maybe // it's not worth having a varargs form of this method at all... /** * The 0-ary cartesian product is a single empty list. */ @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_zeroary() { ASSERT.that(Sets.cartesianProduct()).has().exactly(list()); } /** * A unary cartesian product is one list of size 1 for each element in the * input set. */ @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_unary() { ASSERT.that(Sets.cartesianProduct(set(1, 2))).has().exactly(list(1), list(2)); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary0x0() { Set<Integer> mt = emptySet(); assertEmpty(Sets.cartesianProduct(mt, mt)); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary0x1() { Set<Integer> mt = emptySet(); assertEmpty(Sets.cartesianProduct(mt, set(1))); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x0() { Set<Integer> mt = emptySet(); assertEmpty(Sets.cartesianProduct(set(1), mt)); } private static void assertEmpty(Set<? extends List<?>> set) { assertTrue(set.isEmpty()); assertEquals(0, set.size()); assertFalse(set.iterator().hasNext()); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x1() { ASSERT.that(Sets.cartesianProduct(set(1), set(2))).has().item(list(1, 2)); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x2() { ASSERT.that(Sets.cartesianProduct(set(1), set(2, 3))) .has().exactly(list(1, 2), list(1, 3)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary2x2() { ASSERT.that(Sets.cartesianProduct(set(1, 2), set(3, 4))) .has().exactly(list(1, 3), list(1, 4), list(2, 3), list(2, 4)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_2x2x2() { ASSERT.that(Sets.cartesianProduct(set(0, 1), set(0, 1), set(0, 1))).has().exactly( list(0, 0, 0), list(0, 0, 1), list(0, 1, 0), list(0, 1, 1), list(1, 0, 0), list(1, 0, 1), list(1, 1, 0), list(1, 1, 1)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_contains() { Set<List<Integer>> actual = Sets.cartesianProduct(set(1, 2), set(3, 4)); assertTrue(actual.contains(list(1, 3))); assertTrue(actual.contains(list(1, 4))); assertTrue(actual.contains(list(2, 3))); assertTrue(actual.contains(list(2, 4))); assertFalse(actual.contains(list(3, 1))); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_unrelatedTypes() { Set<Integer> x = set(1, 2); Set<String> y = set("3", "4"); List<Object> exp1 = list((Object) 1, "3"); List<Object> exp2 = list((Object) 1, "4"); List<Object> exp3 = list((Object) 2, "3"); List<Object> exp4 = list((Object) 2, "4"); ASSERT.that(Sets.<Object>cartesianProduct(x, y)) .has().exactly(exp1, exp2, exp3, exp4).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProductTooBig() { Set<Integer> set = ContiguousSet.create(Range.closed(0, 10000), DiscreteDomain.integers()); try { Sets.cartesianProduct(set, set, set, set, set); fail("Expected IAE"); } catch (IllegalArgumentException expected) {} } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_hashCode() { // Run through the same cartesian products we tested above Set<List<Integer>> degenerate = Sets.cartesianProduct(); checkHashCode(degenerate); checkHashCode(Sets.cartesianProduct(set(1, 2))); int num = Integer.MAX_VALUE / 3 * 2; // tickle overflow-related problems checkHashCode(Sets.cartesianProduct(set(1, 2, num))); Set<Integer> mt = emptySet(); checkHashCode(Sets.cartesianProduct(mt, mt)); checkHashCode(Sets.cartesianProduct(mt, set(num))); checkHashCode(Sets.cartesianProduct(set(num), mt)); checkHashCode(Sets.cartesianProduct(set(num), set(1))); checkHashCode(Sets.cartesianProduct(set(1), set(2, num))); checkHashCode(Sets.cartesianProduct(set(1, num), set(2, num - 1))); checkHashCode(Sets.cartesianProduct( set(1, num), set(2, num - 1), set(3, num + 1))); // a bigger one checkHashCode(Sets.cartesianProduct( set(1, num, num + 1), set(2), set(3, num + 2), set(4, 5, 6, 7, 8))); } public void testPowerSetEmpty() { ImmutableSet<Integer> elements = ImmutableSet.of(); Set<Set<Integer>> powerSet = powerSet(elements); assertEquals(1, powerSet.size()); assertEquals(ImmutableSet.of(ImmutableSet.of()), powerSet); assertEquals(0, powerSet.hashCode()); } public void testPowerSetContents() { ImmutableSet<Integer> elements = ImmutableSet.of(1, 2, 3); Set<Set<Integer>> powerSet = powerSet(elements); assertEquals(8, powerSet.size()); assertEquals(4 * 1 + 4 * 2 + 4 * 3, powerSet.hashCode()); Set<Set<Integer>> expected = newHashSet(); expected.add(ImmutableSet.<Integer>of()); expected.add(ImmutableSet.of(1)); expected.add(ImmutableSet.of(2)); expected.add(ImmutableSet.of(3)); expected.add(ImmutableSet.of(1, 2)); expected.add(ImmutableSet.of(1, 3)); expected.add(ImmutableSet.of(2, 3)); expected.add(ImmutableSet.of(1, 2, 3)); Set<Set<Integer>> almostPowerSet = newHashSet(expected); almostPowerSet.remove(ImmutableSet.of(1, 2, 3)); almostPowerSet.add(ImmutableSet.of(1, 2, 4)); new EqualsTester() .addEqualityGroup(expected, powerSet) .addEqualityGroup(ImmutableSet.of(1, 2, 3)) .addEqualityGroup(almostPowerSet) .testEquals(); for (Set<Integer> subset : expected) { assertTrue(powerSet.contains(subset)); } assertFalse(powerSet.contains(ImmutableSet.of(1, 2, 4))); assertFalse(powerSet.contains(singleton(null))); assertFalse(powerSet.contains(null)); assertFalse(powerSet.contains("notASet")); } public void testPowerSetIteration_manual() { ImmutableSet<Integer> elements = ImmutableSet.of(1, 2, 3); Set<Set<Integer>> powerSet = powerSet(elements); // The API doesn't promise this iteration order, but it's convenient here. Iterator<Set<Integer>> i = powerSet.iterator(); assertEquals(ImmutableSet.of(), i.next()); assertEquals(ImmutableSet.of(1), i.next()); assertEquals(ImmutableSet.of(2), i.next()); assertEquals(ImmutableSet.of(2, 1), i.next()); assertEquals(ImmutableSet.of(3), i.next()); assertEquals(ImmutableSet.of(3, 1), i.next()); assertEquals(ImmutableSet.of(3, 2), i.next()); assertEquals(ImmutableSet.of(3, 2, 1), i.next()); assertFalse(i.hasNext()); try { i.next(); fail(); } catch (NoSuchElementException expected) { } } public void testPowerSetIteration_iteratorTester_fast() { ImmutableSet<Integer> elements = ImmutableSet.of(1, 2); Set<Set<Integer>> expected = newHashSet(); expected.add(ImmutableSet.<Integer>of()); expected.add(ImmutableSet.of(1)); expected.add(ImmutableSet.of(2)); expected.add(ImmutableSet.of(1, 2)); final Set<Set<Integer>> powerSet = powerSet(elements); new IteratorTester<Set<Integer>>(4, UNMODIFIABLE, expected, KNOWN_ORDER) { @Override protected Iterator<Set<Integer>> newTargetIterator() { return powerSet.iterator(); } }.test(); } public void testPowerSetSize() { assertPowerSetSize(1); assertPowerSetSize(2, 'a'); assertPowerSetSize(4, 'a', 'b'); assertPowerSetSize(8, 'a', 'b', 'c'); assertPowerSetSize(16, 'a', 'b', 'd', 'e'); assertPowerSetSize(1 << 30, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4'); } public void testPowerSetCreationErrors() { try { powerSet(newHashSet('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5')); fail(); } catch (IllegalArgumentException expected) { } try { powerSet(singleton(null)); fail(); } catch (NullPointerException expected) { } } public void testPowerSetEqualsAndHashCode_verifyAgainstHashSet() { ImmutableList<Integer> allElements = ImmutableList.of(4233352, 3284593, 3794208, 3849533, 4013967, 2902658, 1886275, 2131109, 985872, 1843868); for (int i = 0; i < allElements.size(); i++) { Set<Integer> elements = newHashSet(allElements.subList(0, i)); Set<Set<Integer>> powerSet1 = powerSet(elements); Set<Set<Integer>> powerSet2 = powerSet(elements); new EqualsTester() .addEqualityGroup(powerSet1, powerSet2, toHashSets(powerSet1)) .addEqualityGroup(ImmutableSet.of()) .addEqualityGroup(ImmutableSet.of(9999999)) .addEqualityGroup("notASet") .testEquals(); assertEquals(toHashSets(powerSet1).hashCode(), powerSet1.hashCode()); } } /** * Test that a hash code miscomputed by "input.hashCode() * tooFarValue / 2" * is correct under our {@code hashCode} implementation. */ public void testPowerSetHashCode_inputHashCodeTimesTooFarValueIsZero() { Set<Object> sumToEighthMaxIntElements = newHashSet(objectWithHashCode(1 << 29), objectWithHashCode(0)); assertPowerSetHashCode(1 << 30, sumToEighthMaxIntElements); Set<Object> sumToQuarterMaxIntElements = newHashSet(objectWithHashCode(1 << 30), objectWithHashCode(0)); assertPowerSetHashCode(1 << 31, sumToQuarterMaxIntElements); } public void testPowerSetShowOff() { Set<Object> zero = ImmutableSet.of(); Set<Set<Object>> one = powerSet(zero); Set<Set<Set<Object>>> two = powerSet(one); Set<Set<Set<Set<Object>>>> four = powerSet(two); Set<Set<Set<Set<Set<Object>>>>> sixteen = powerSet(four); Set<Set<Set<Set<Set<Set<Object>>>>>> sixtyFiveThousandish = powerSet(sixteen); assertEquals(1 << 16, sixtyFiveThousandish.size()); assertTrue(powerSet(makeSetOfZeroToTwentyNine()) .contains(makeSetOfZeroToTwentyNine())); assertFalse(powerSet(makeSetOfZeroToTwentyNine()) .contains(ImmutableSet.of(30))); } private static Set<Integer> makeSetOfZeroToTwentyNine() { // TODO: use Range once it's publicly available Set<Integer> zeroToTwentyNine = newHashSet(); for (int i = 0; i < 30; i++) { zeroToTwentyNine.add(i); } return zeroToTwentyNine; } private static <E> Set<Set<E>> toHashSets(Set<Set<E>> powerSet) { Set<Set<E>> result = newHashSet(); for (Set<E> subset : powerSet) { result.add(new HashSet<E>(subset)); } return result; } private static Object objectWithHashCode(final int hashCode) { return new Object() { @Override public int hashCode() { return hashCode; } }; } private static void assertPowerSetHashCode(int expected, Set<?> elements) { assertEquals(expected, powerSet(elements).hashCode()); } private static void assertPowerSetSize(int i, Object... elements) { assertEquals(i, powerSet(newHashSet(elements)).size()); } private static void checkHashCode(Set<?> set) { assertEquals(Sets.newHashSet(set).hashCode(), set.hashCode()); } private static <E> Set<E> set(E... elements) { return ImmutableSet.copyOf(elements); } private static <E> List<E> list(E... elements) { return ImmutableList.copyOf(elements); } /** * Utility method to verify that the given LinkedHashSet is equal to and * hashes identically to a set constructed with the elements in the given * collection. Also verifies that the ordering in the set is the same * as the ordering of the given contents. */ private static <E> void verifyLinkedHashSetContents( LinkedHashSet<E> set, Collection<E> contents) { assertEquals("LinkedHashSet should have preserved order for iteration", new ArrayList<E>(set), new ArrayList<E>(contents)); verifySetContents(set, contents); } /** * Utility method to verify that the given SortedSet is equal to and * hashes identically to a set constructed with the elements in the * given iterable. Also verifies that the comparator is the same as the * given comparator. */ private static <E> void verifySortedSetContents( SortedSet<E> set, Iterable<E> iterable, @Nullable Comparator<E> comparator) { assertSame(comparator, set.comparator()); verifySetContents(set, iterable); } /** * Utility method that verifies that the given set is equal to and hashes * identically to a set constructed with the elements in the given iterable. */ private static <E> void verifySetContents(Set<E> set, Iterable<E> contents) { Set<E> expected = null; if (contents instanceof Set) { expected = (Set<E>) contents; } else { expected = new HashSet<E>(); for (E element : contents) { expected.add(element); } } assertEquals(expected, set); } /** * Simple base class to verify that we handle generics correctly. */ static class Base implements Comparable<Base>, Serializable { private final String s; public Base(String s) { this.s = s; } @Override public int hashCode() { // delegate to 's' return s.hashCode(); } @Override public boolean equals(Object other) { if (other == null) { return false; } else if (other instanceof Base) { return s.equals(((Base) other).s); } else { return false; } } @Override public int compareTo(Base o) { return s.compareTo(o.s); } private static final long serialVersionUID = 0; } /** * Simple derived class to verify that we handle generics correctly. */ static class Derived extends Base { public Derived(String s) { super(s); } private static final long serialVersionUID = 0; } void ensureNotDirectlyModifiable(SortedSet<Integer> unmod) { try { unmod.add(4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { unmod.remove(4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { unmod.addAll(Collections.singleton(4)); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { Iterator<Integer> iterator = unmod.iterator(); iterator.next(); iterator.remove(); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } } }
Java
/* * Copyright (C) 2007 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.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.google.TestStringMultisetGenerator; import junit.framework.TestCase; import java.util.Arrays; import java.util.List; /** * Unit test for {@link LinkedHashMultiset}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class LinkedHashMultisetTest extends TestCase { private static TestStringMultisetGenerator linkedHashMultisetGenerator() { return new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { return LinkedHashMultiset.create(asList(elements)); } @Override public List<String> order(List<String> insertionOrder) { List<String> order = Lists.newArrayList(); for (String s : insertionOrder) { int index = order.indexOf(s); if (index == -1) { order.add(s); } else { order.add(index, s); } } return order; } }; } public void testCreate() { Multiset<String> multiset = LinkedHashMultiset.create(); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); assertEquals("[foo x 2, bar]", multiset.toString()); } public void testCreateWithSize() { Multiset<String> multiset = LinkedHashMultiset.create(50); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); assertEquals("[foo x 2, bar]", multiset.toString()); } public void testCreateFromIterable() { Multiset<String> multiset = LinkedHashMultiset.create(Arrays.asList("foo", "bar", "foo")); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); assertEquals("[foo x 2, bar]", multiset.toString()); } public void testToString() { Multiset<String> ms = LinkedHashMultiset.create(); ms.add("a", 3); ms.add("c", 1); ms.add("b", 2); assertEquals("[a x 3, c, b x 2]", ms.toString()); } public void testLosesPlaceInLine() throws Exception { Multiset<String> ms = LinkedHashMultiset.create(); ms.add("a"); ms.add("b", 2); ms.add("c"); ASSERT.that(ms.elementSet()).has().exactly("a", "b", "c").inOrder(); ms.remove("b"); ASSERT.that(ms.elementSet()).has().exactly("a", "b", "c").inOrder(); ms.add("b"); ASSERT.that(ms.elementSet()).has().exactly("a", "b", "c").inOrder(); ms.remove("b", 2); ms.add("b"); ASSERT.that(ms.elementSet()).has().exactly("a", "c", "b").inOrder(); } }
Java
/* * Copyright (C) 2007 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableSet.Builder; import com.google.common.testing.EqualsTester; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; /** * Unit test for {@link ImmutableSet}. * * @author Kevin Bourrillion * @author Jared Levy * @author Nick Kralevich */ @GwtCompatible(emulated = true) public class ImmutableSetTest extends AbstractImmutableSetTest { @Override protected Set<String> of() { return ImmutableSet.of(); } @Override protected Set<String> of(String e) { return ImmutableSet.of(e); } @Override protected Set<String> of(String e1, String e2) { return ImmutableSet.of(e1, e2); } @Override protected Set<String> of(String e1, String e2, String e3) { return ImmutableSet.of(e1, e2, e3); } @Override protected Set<String> of( String e1, String e2, String e3, String e4) { return ImmutableSet.of(e1, e2, e3, e4); } @Override protected Set<String> of( String e1, String e2, String e3, String e4, String e5) { return ImmutableSet.of(e1, e2, e3, e4, e5); } @Override protected Set<String> of(String e1, String e2, String e3, String e4, String e5, String e6, String... rest) { return ImmutableSet.of(e1, e2, e3, e4, e5, e6, rest); } @Override protected Set<String> copyOf(String[] elements) { return ImmutableSet.copyOf(elements); } @Override protected Set<String> copyOf(Collection<String> elements) { return ImmutableSet.copyOf(elements); } @Override protected Set<String> copyOf(Iterable<String> elements) { return ImmutableSet.copyOf(elements); } @Override protected Set<String> copyOf(Iterator<String> elements) { return ImmutableSet.copyOf(elements); } public void testCreation_allDuplicates() { ImmutableSet<String> set = ImmutableSet.copyOf(Lists.newArrayList("a", "a")); assertTrue(set instanceof SingletonImmutableSet); assertEquals(Lists.newArrayList("a"), Lists.newArrayList(set)); } public void testCreation_oneDuplicate() { // now we'll get the varargs overload ImmutableSet<String> set = ImmutableSet.of( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "a"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"), Lists.newArrayList(set)); } public void testCreation_manyDuplicates() { // now we'll get the varargs overload ImmutableSet<String> set = ImmutableSet.of( "a", "b", "c", "c", "c", "c", "b", "b", "a", "a", "c", "c", "c", "a"); ASSERT.that(set).has().exactly("a", "b", "c").inOrder(); } public void testCreation_arrayOfArray() { String[] array = new String[] { "a" }; Set<String[]> set = ImmutableSet.<String[]>of(array); assertEquals(Collections.singleton(array), set); } public void testCopyOf_copiesImmutableSortedSet() { ImmutableSortedSet<String> sortedSet = ImmutableSortedSet.of("a"); ImmutableSet<String> copy = ImmutableSet.copyOf(sortedSet); assertNotSame(sortedSet, copy); } @Override <E extends Comparable<E>> Builder<E> builder() { return ImmutableSet.builder(); } @Override int getComplexBuilderSetLastElement() { return LAST_COLOR_ADDED; } public void testEquals() { new EqualsTester() .addEqualityGroup(ImmutableSet.of(), ImmutableSet.of()) .addEqualityGroup(ImmutableSet.of(1), ImmutableSet.of(1), ImmutableSet.of(1, 1)) .addEqualityGroup(ImmutableSet.of(1, 2, 1), ImmutableSet.of(2, 1, 1)) .testEquals(); } }
Java
/* * Copyright (C) 2011 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.collect; import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import static com.google.common.collect.DiscreteDomain.integers; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Set; /** * @author Gregory Kick */ @GwtCompatible(emulated = true) public class ContiguousSetTest extends TestCase { private static DiscreteDomain<Integer> NOT_EQUAL_TO_INTEGERS = new DiscreteDomain<Integer>() { @Override public Integer next(Integer value) { return integers().next(value); } @Override public Integer previous(Integer value) { return integers().previous(value); } @Override public long distance(Integer start, Integer end) { return integers().distance(start, end); } @Override public Integer minValue() { return integers().minValue(); } @Override public Integer maxValue() { return integers().maxValue(); } }; public void testEquals() { new EqualsTester() .addEqualityGroup( ContiguousSet.create(Range.closed(1, 3), integers()), ContiguousSet.create(Range.closedOpen(1, 4), integers()), ContiguousSet.create(Range.openClosed(0, 3), integers()), ContiguousSet.create(Range.open(0, 4), integers()), ContiguousSet.create(Range.closed(1, 3), NOT_EQUAL_TO_INTEGERS), ContiguousSet.create(Range.closedOpen(1, 4), NOT_EQUAL_TO_INTEGERS), ContiguousSet.create(Range.openClosed(0, 3), NOT_EQUAL_TO_INTEGERS), ContiguousSet.create(Range.open(0, 4), NOT_EQUAL_TO_INTEGERS), ImmutableSortedSet.of(1, 2, 3)) .testEquals(); // not testing hashCode for these because it takes forever to compute assertEquals( ContiguousSet.create(Range.closed(Integer.MIN_VALUE, Integer.MAX_VALUE), integers()), ContiguousSet.create(Range.<Integer>all(), integers())); assertEquals( ContiguousSet.create(Range.closed(Integer.MIN_VALUE, Integer.MAX_VALUE), integers()), ContiguousSet.create(Range.atLeast(Integer.MIN_VALUE), integers())); assertEquals( ContiguousSet.create(Range.closed(Integer.MIN_VALUE, Integer.MAX_VALUE), integers()), ContiguousSet.create(Range.atMost(Integer.MAX_VALUE), integers())); } public void testCreate_noMin() { Range<Integer> range = Range.lessThan(0); try { ContiguousSet.create(range, RangeTest.UNBOUNDED_DOMAIN); fail(); } catch (IllegalArgumentException expected) {} } public void testCreate_noMax() { Range<Integer> range = Range.greaterThan(0); try { ContiguousSet.create(range, RangeTest.UNBOUNDED_DOMAIN); fail(); } catch (IllegalArgumentException expected) {} } public void testCreate_empty() { assertEquals(ImmutableSet.of(), ContiguousSet.create(Range.closedOpen(1, 1), integers())); assertEquals(ImmutableSet.of(), ContiguousSet.create(Range.openClosed(5, 5), integers())); assertEquals(ImmutableSet.of(), ContiguousSet.create(Range.lessThan(Integer.MIN_VALUE), integers())); assertEquals(ImmutableSet.of(), ContiguousSet.create(Range.greaterThan(Integer.MAX_VALUE), integers())); } public void testHeadSet() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); ASSERT.that(set.headSet(1)).isEmpty(); ASSERT.that(set.headSet(2)).has().item(1); ASSERT.that(set.headSet(3)).has().exactly(1, 2).inOrder(); ASSERT.that(set.headSet(4)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.headSet(Integer.MAX_VALUE)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.headSet(1, true)).has().item(1); ASSERT.that(set.headSet(2, true)).has().exactly(1, 2).inOrder(); ASSERT.that(set.headSet(3, true)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.headSet(4, true)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.headSet(Integer.MAX_VALUE, true)).has().exactly(1, 2, 3).inOrder(); } public void testHeadSet_tooSmall() { ASSERT.that(ContiguousSet.create(Range.closed(1, 3), integers()).headSet(0)).isEmpty(); } public void testTailSet() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); ASSERT.that(set.tailSet(Integer.MIN_VALUE)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.tailSet(1)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.tailSet(2)).has().exactly(2, 3).inOrder(); ASSERT.that(set.tailSet(3)).has().item(3); ASSERT.that(set.tailSet(Integer.MIN_VALUE, false)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.tailSet(1, false)).has().exactly(2, 3).inOrder(); ASSERT.that(set.tailSet(2, false)).has().item(3); ASSERT.that(set.tailSet(3, false)).isEmpty(); } public void testTailSet_tooLarge() { ASSERT.that(ContiguousSet.create(Range.closed(1, 3), integers()).tailSet(4)).isEmpty(); } public void testSubSet() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); ASSERT.that(set.subSet(1, 4)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.subSet(2, 4)).has().exactly(2, 3).inOrder(); ASSERT.that(set.subSet(3, 4)).has().item(3); ASSERT.that(set.subSet(3, 3)).isEmpty(); ASSERT.that(set.subSet(2, 3)).has().item(2); ASSERT.that(set.subSet(1, 3)).has().exactly(1, 2).inOrder(); ASSERT.that(set.subSet(1, 2)).has().item(1); ASSERT.that(set.subSet(2, 2)).isEmpty(); ASSERT.that(set.subSet(Integer.MIN_VALUE, Integer.MAX_VALUE)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.subSet(1, true, 3, true)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.subSet(1, false, 3, true)).has().exactly(2, 3).inOrder(); ASSERT.that(set.subSet(1, true, 3, false)).has().exactly(1, 2).inOrder(); ASSERT.that(set.subSet(1, false, 3, false)).has().item(2); } public void testSubSet_outOfOrder() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); try { set.subSet(3, 2); fail(); } catch (IllegalArgumentException expected) {} } public void testSubSet_tooLarge() { ASSERT.that(ContiguousSet.create(Range.closed(1, 3), integers()).subSet(4, 6)).isEmpty(); } public void testSubSet_tooSmall() { ASSERT.that(ContiguousSet.create(Range.closed(1, 3), integers()).subSet(-1, 0)).isEmpty(); } public void testFirst() { assertEquals(1, ContiguousSet.create(Range.closed(1, 3), integers()).first().intValue()); assertEquals(1, ContiguousSet.create(Range.open(0, 4), integers()).first().intValue()); assertEquals(Integer.MIN_VALUE, ContiguousSet.create(Range.<Integer>all(), integers()).first().intValue()); } public void testLast() { assertEquals(3, ContiguousSet.create(Range.closed(1, 3), integers()).last().intValue()); assertEquals(3, ContiguousSet.create(Range.open(0, 4), integers()).last().intValue()); assertEquals(Integer.MAX_VALUE, ContiguousSet.create(Range.<Integer>all(), integers()).last().intValue()); } public void testContains() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); assertFalse(set.contains(0)); assertTrue(set.contains(1)); assertTrue(set.contains(2)); assertTrue(set.contains(3)); assertFalse(set.contains(4)); set = ContiguousSet.create(Range.open(0, 4), integers()); assertFalse(set.contains(0)); assertTrue(set.contains(1)); assertTrue(set.contains(2)); assertTrue(set.contains(3)); assertFalse(set.contains(4)); assertFalse(set.contains("blah")); } public void testContainsAll() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); for (Set<Integer> subset : Sets.powerSet(ImmutableSet.of(1, 2, 3))) { assertTrue(set.containsAll(subset)); } for (Set<Integer> subset : Sets.powerSet(ImmutableSet.of(1, 2, 3))) { assertFalse(set.containsAll(Sets.union(subset, ImmutableSet.of(9)))); } assertFalse(set.containsAll(ImmutableSet.of("blah"))); } public void testRange() { assertEquals(Range.closed(1, 3), ContiguousSet.create(Range.closed(1, 3), integers()).range()); assertEquals(Range.closed(1, 3), ContiguousSet.create(Range.closedOpen(1, 4), integers()).range()); assertEquals(Range.closed(1, 3), ContiguousSet.create(Range.open(0, 4), integers()).range()); assertEquals(Range.closed(1, 3), ContiguousSet.create(Range.openClosed(0, 3), integers()).range()); assertEquals(Range.openClosed(0, 3), ContiguousSet.create(Range.closed(1, 3), integers()).range(OPEN, CLOSED)); assertEquals(Range.openClosed(0, 3), ContiguousSet.create(Range.closedOpen(1, 4), integers()).range(OPEN, CLOSED)); assertEquals(Range.openClosed(0, 3), ContiguousSet.create(Range.open(0, 4), integers()).range(OPEN, CLOSED)); assertEquals(Range.openClosed(0, 3), ContiguousSet.create(Range.openClosed(0, 3), integers()).range(OPEN, CLOSED)); assertEquals(Range.open(0, 4), ContiguousSet.create(Range.closed(1, 3), integers()).range(OPEN, OPEN)); assertEquals(Range.open(0, 4), ContiguousSet.create(Range.closedOpen(1, 4), integers()).range(OPEN, OPEN)); assertEquals(Range.open(0, 4), ContiguousSet.create(Range.open(0, 4), integers()).range(OPEN, OPEN)); assertEquals(Range.open(0, 4), ContiguousSet.create(Range.openClosed(0, 3), integers()).range(OPEN, OPEN)); assertEquals(Range.closedOpen(1, 4), ContiguousSet.create(Range.closed(1, 3), integers()).range(CLOSED, OPEN)); assertEquals(Range.closedOpen(1, 4), ContiguousSet.create(Range.closedOpen(1, 4), integers()).range(CLOSED, OPEN)); assertEquals(Range.closedOpen(1, 4), ContiguousSet.create(Range.open(0, 4), integers()).range(CLOSED, OPEN)); assertEquals(Range.closedOpen(1, 4), ContiguousSet.create(Range.openClosed(0, 3), integers()).range(CLOSED, OPEN)); } public void testRange_unboundedRange() { assertEquals(Range.closed(Integer.MIN_VALUE, Integer.MAX_VALUE), ContiguousSet.create(Range.<Integer>all(), integers()).range()); assertEquals(Range.atLeast(Integer.MIN_VALUE), ContiguousSet.create(Range.<Integer>all(), integers()).range(CLOSED, OPEN)); assertEquals(Range.all(), ContiguousSet.create(Range.<Integer>all(), integers()).range(OPEN, OPEN)); assertEquals(Range.atMost(Integer.MAX_VALUE), ContiguousSet.create(Range.<Integer>all(), integers()).range(OPEN, CLOSED)); } public void testIntersection_empty() { ContiguousSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); ContiguousSet<Integer> emptySet = ContiguousSet.create(Range.closedOpen(2, 2), integers()); assertEquals(ImmutableSet.of(), set.intersection(emptySet)); assertEquals(ImmutableSet.of(), emptySet.intersection(set)); assertEquals(ImmutableSet.of(), ContiguousSet.create(Range.closed(-5, -1), integers()).intersection( ContiguousSet.create(Range.open(3, 64), integers()))); } public void testIntersection() { ContiguousSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); assertEquals(ImmutableSet.of(1, 2, 3), ContiguousSet.create(Range.open(-1, 4), integers()).intersection(set)); assertEquals(ImmutableSet.of(1, 2, 3), set.intersection(ContiguousSet.create(Range.open(-1, 4), integers()))); } }
Java
/* * Copyright (C) 2007 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.collect; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.io.Serializable; import java.util.Iterator; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; /** * Unit test for {@link AbstractMultiset}. * * @author Kevin Bourrillion * @author Louis Wasserman */ @SuppressWarnings("serial") // No serialization is used in this test @GwtCompatible(emulated = true) public class SimpleAbstractMultisetTest extends TestCase { public void testFastAddAllMultiset() { final AtomicInteger addCalls = new AtomicInteger(); Multiset<String> multiset = new NoRemoveMultiset<String>() { @Override public int add(String element, int occurrences) { addCalls.incrementAndGet(); return super.add(element, occurrences); } }; ImmutableMultiset<String> adds = new ImmutableMultiset.Builder<String>().addCopies("x", 10).build(); multiset.addAll(adds); assertEquals(addCalls.get(), 1); } public void testRemoveUnsupported() { Multiset<String> multiset = new NoRemoveMultiset<String>(); multiset.add("a"); try { multiset.remove("a"); fail(); } catch (UnsupportedOperationException expected) {} assertTrue(multiset.contains("a")); } private static class NoRemoveMultiset<E> extends AbstractMultiset<E> implements Serializable { final Map<E, Integer> backingMap = Maps.newHashMap(); @Override public int add(@Nullable E element, int occurrences) { checkArgument(occurrences >= 0); Integer frequency = backingMap.get(element); if (frequency == null) { frequency = 0; } if (occurrences == 0) { return frequency; } checkArgument(occurrences <= Integer.MAX_VALUE - frequency); backingMap.put(element, frequency + occurrences); return frequency; } @Override Iterator<Entry<E>> entryIterator() { final Iterator<Map.Entry<E, Integer>> backingEntries = backingMap.entrySet().iterator(); return new UnmodifiableIterator<Multiset.Entry<E>>() { @Override public boolean hasNext() { return backingEntries.hasNext(); } @Override public Multiset.Entry<E> next() { final Map.Entry<E, Integer> mapEntry = backingEntries.next(); return new Multisets.AbstractEntry<E>() { @Override public E getElement() { return mapEntry.getKey(); } @Override public int getCount() { Integer frequency = backingMap.get(getElement()); return (frequency == null) ? 0 : frequency; } }; } }; } @Override int distinctElements() { return backingMap.size(); } } }
Java
/* * Copyright (C) 2007 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.collect; import static com.google.common.collect.testing.Helpers.nefariousMapEntry; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Supplier; import junit.framework.TestCase; import java.io.Serializable; import java.util.AbstractMap; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import java.util.SortedSet; /** * Tests for {@code MapConstraints}. * * @author Mike Bostock * @author Jared Levy */ @GwtCompatible(emulated = true) public class MapConstraintsTest extends TestCase { private static final String TEST_KEY = "test"; private static final Integer TEST_VALUE = 42; static final class TestKeyException extends IllegalArgumentException { private static final long serialVersionUID = 0; } static final class TestValueException extends IllegalArgumentException { private static final long serialVersionUID = 0; } static final MapConstraint<String, Integer> TEST_CONSTRAINT = new TestConstraint(); private static final class TestConstraint implements MapConstraint<String, Integer>, Serializable { @Override public void checkKeyValue(String key, Integer value) { if (TEST_KEY.equals(key)) { throw new TestKeyException(); } if (TEST_VALUE.equals(value)) { throw new TestValueException(); } } private static final long serialVersionUID = 0; } public void testNotNull() { MapConstraint<Object, Object> constraint = MapConstraints.notNull(); constraint.checkKeyValue("foo", 1); assertEquals("Not null", constraint.toString()); try { constraint.checkKeyValue(null, 1); fail("NullPointerException expected"); } catch (NullPointerException expected) {} try { constraint.checkKeyValue("foo", null); fail("NullPointerException expected"); } catch (NullPointerException expected) {} try { constraint.checkKeyValue(null, null); fail("NullPointerException expected"); } catch (NullPointerException expected) {} } public void testConstrainedMapLegal() { Map<String, Integer> map = Maps.newLinkedHashMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap( map, TEST_CONSTRAINT); map.put(TEST_KEY, TEST_VALUE); constrained.put("foo", 1); map.putAll(ImmutableMap.of("bar", 2)); constrained.putAll(ImmutableMap.of("baz", 3)); assertTrue(map.equals(constrained)); assertTrue(constrained.equals(map)); assertEquals(map.entrySet(), constrained.entrySet()); assertEquals(map.keySet(), constrained.keySet()); assertEquals(HashMultiset.create(map.values()), HashMultiset.create(constrained.values())); assertFalse(map.values() instanceof Serializable); assertEquals(map.toString(), constrained.toString()); assertEquals(map.hashCode(), constrained.hashCode()); ASSERT.that(map.entrySet()).has().exactly( Maps.immutableEntry(TEST_KEY, TEST_VALUE), Maps.immutableEntry("foo", 1), Maps.immutableEntry("bar", 2), Maps.immutableEntry("baz", 3)).inOrder(); } public void testConstrainedMapIllegal() { Map<String, Integer> map = Maps.newLinkedHashMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap( map, TEST_CONSTRAINT); try { constrained.put(TEST_KEY, TEST_VALUE); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.put("baz", TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.put(TEST_KEY, 3); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.putAll(ImmutableMap.of("baz", 3, TEST_KEY, 4)); fail("TestKeyException expected"); } catch (TestKeyException expected) {} assertEquals(Collections.emptySet(), map.entrySet()); assertEquals(Collections.emptySet(), constrained.entrySet()); } public void testConstrainedBiMapLegal() { BiMap<String, Integer> map = new AbstractBiMap<String, Integer>( Maps.<String, Integer>newLinkedHashMap(), Maps.<Integer, String>newLinkedHashMap()) {}; BiMap<String, Integer> constrained = MapConstraints.constrainedBiMap( map, TEST_CONSTRAINT); map.put(TEST_KEY, TEST_VALUE); constrained.put("foo", 1); map.putAll(ImmutableMap.of("bar", 2)); constrained.putAll(ImmutableMap.of("baz", 3)); assertTrue(map.equals(constrained)); assertTrue(constrained.equals(map)); assertEquals(map.entrySet(), constrained.entrySet()); assertEquals(map.keySet(), constrained.keySet()); assertEquals(map.values(), constrained.values()); assertEquals(map.toString(), constrained.toString()); assertEquals(map.hashCode(), constrained.hashCode()); ASSERT.that(map.entrySet()).has().exactly( Maps.immutableEntry(TEST_KEY, TEST_VALUE), Maps.immutableEntry("foo", 1), Maps.immutableEntry("bar", 2), Maps.immutableEntry("baz", 3)).inOrder(); } public void testConstrainedBiMapIllegal() { BiMap<String, Integer> map = new AbstractBiMap<String, Integer>( Maps.<String, Integer>newLinkedHashMap(), Maps.<Integer, String>newLinkedHashMap()) {}; BiMap<String, Integer> constrained = MapConstraints.constrainedBiMap( map, TEST_CONSTRAINT); try { constrained.put(TEST_KEY, TEST_VALUE); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.put("baz", TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.put(TEST_KEY, 3); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.putAll(ImmutableMap.of("baz", 3, TEST_KEY, 4)); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.forcePut(TEST_KEY, 3); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.inverse().forcePut(TEST_VALUE, "baz"); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.inverse().forcePut(3, TEST_KEY); fail("TestKeyException expected"); } catch (TestKeyException expected) {} assertEquals(Collections.emptySet(), map.entrySet()); assertEquals(Collections.emptySet(), constrained.entrySet()); } public void testConstrainedMultimapLegal() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap( multimap, TEST_CONSTRAINT); multimap.put(TEST_KEY, TEST_VALUE); constrained.put("foo", 1); multimap.get("bar").add(2); constrained.get("baz").add(3); multimap.get("qux").addAll(Arrays.asList(4)); constrained.get("zig").addAll(Arrays.asList(5)); multimap.putAll("zag", Arrays.asList(6)); constrained.putAll("bee", Arrays.asList(7)); multimap.putAll(new ImmutableMultimap.Builder<String, Integer>() .put("bim", 8).build()); constrained.putAll(new ImmutableMultimap.Builder<String, Integer>() .put("bop", 9).build()); multimap.putAll(new ImmutableMultimap.Builder<String, Integer>() .put("dig", 10).build()); constrained.putAll(new ImmutableMultimap.Builder<String, Integer>() .put("dag", 11).build()); assertTrue(multimap.equals(constrained)); assertTrue(constrained.equals(multimap)); ASSERT.that(ImmutableList.copyOf(multimap.entries())) .is(ImmutableList.copyOf(constrained.entries())); ASSERT.that(constrained.asMap().get("foo")).has().item(1); assertNull(constrained.asMap().get("missing")); assertEquals(multimap.asMap(), constrained.asMap()); assertEquals(multimap.values(), constrained.values()); assertEquals(multimap.keys(), constrained.keys()); assertEquals(multimap.keySet(), constrained.keySet()); assertEquals(multimap.toString(), constrained.toString()); assertEquals(multimap.hashCode(), constrained.hashCode()); ASSERT.that(multimap.entries()).has().exactly( Maps.immutableEntry(TEST_KEY, TEST_VALUE), Maps.immutableEntry("foo", 1), Maps.immutableEntry("bar", 2), Maps.immutableEntry("baz", 3), Maps.immutableEntry("qux", 4), Maps.immutableEntry("zig", 5), Maps.immutableEntry("zag", 6), Maps.immutableEntry("bee", 7), Maps.immutableEntry("bim", 8), Maps.immutableEntry("bop", 9), Maps.immutableEntry("dig", 10), Maps.immutableEntry("dag", 11)).inOrder(); assertFalse(constrained.asMap().values() instanceof Serializable); Iterator<Collection<Integer>> iterator = constrained.asMap().values().iterator(); iterator.next(); iterator.next().add(12); assertTrue(multimap.containsEntry("foo", 12)); } public void testConstrainedTypePreservingList() { ListMultimap<String, Integer> multimap = MapConstraints.constrainedListMultimap( LinkedListMultimap.<String, Integer>create(), TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, Collection<Integer>> entry = multimap.asMap().entrySet().iterator().next(); assertTrue(entry.getValue() instanceof List); assertFalse(multimap.entries() instanceof Set); assertFalse(multimap.get("foo") instanceof RandomAccess); } public void testConstrainedTypePreservingRandomAccessList() { ListMultimap<String, Integer> multimap = MapConstraints.constrainedListMultimap( ArrayListMultimap.<String, Integer>create(), TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, Collection<Integer>> entry = multimap.asMap().entrySet().iterator().next(); assertTrue(entry.getValue() instanceof List); assertFalse(multimap.entries() instanceof Set); assertTrue(multimap.get("foo") instanceof RandomAccess); } public void testConstrainedTypePreservingSet() { SetMultimap<String, Integer> multimap = MapConstraints.constrainedSetMultimap( LinkedHashMultimap.<String, Integer>create(), TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, Collection<Integer>> entry = multimap.asMap().entrySet().iterator().next(); assertTrue(entry.getValue() instanceof Set); } public void testConstrainedTypePreservingSortedSet() { Comparator<Integer> comparator = Collections.reverseOrder(); SortedSetMultimap<String, Integer> delegate = TreeMultimap.create(Ordering.<String>natural(), comparator); SortedSetMultimap<String, Integer> multimap = MapConstraints.constrainedSortedSetMultimap(delegate, TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, Collection<Integer>> entry = multimap.asMap().entrySet().iterator().next(); assertTrue(entry.getValue() instanceof SortedSet); assertSame(comparator, multimap.valueComparator()); assertSame(comparator, multimap.get("foo").comparator()); } @SuppressWarnings("unchecked") public void testConstrainedMultimapIllegal() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap( multimap, TEST_CONSTRAINT); try { constrained.put(TEST_KEY, 1); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.put("foo", TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.put(TEST_KEY, TEST_VALUE); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.get(TEST_KEY).add(1); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.get("foo").add(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.get(TEST_KEY).add(TEST_VALUE); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.get(TEST_KEY).addAll(Arrays.asList(1)); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.get("foo").addAll(Arrays.asList(1, TEST_VALUE)); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.get(TEST_KEY).addAll(Arrays.asList(1, TEST_VALUE)); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.putAll(TEST_KEY, Arrays.asList(1)); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.putAll("foo", Arrays.asList(1, TEST_VALUE)); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.putAll(TEST_KEY, Arrays.asList(1, TEST_VALUE)); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.putAll(new ImmutableMultimap.Builder<String, Integer>() .put(TEST_KEY, 2).put("foo", 1).build()); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.putAll(new ImmutableMultimap.Builder<String, Integer>() .put("bar", TEST_VALUE).put("foo", 1).build()); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.putAll(new ImmutableMultimap.Builder<String, Integer>() .put(TEST_KEY, TEST_VALUE).put("foo", 1).build()); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.entries().add(Maps.immutableEntry(TEST_KEY, 1)); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { constrained.entries().addAll(Arrays.asList( Maps.immutableEntry("foo", 1), Maps.immutableEntry(TEST_KEY, 2))); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} assertTrue(multimap.isEmpty()); assertTrue(constrained.isEmpty()); constrained.put("foo", 1); try { constrained.asMap().get("foo").add(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.asMap().values().iterator().next().add(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { ((Collection<Integer>) constrained.asMap().values().toArray()[0]) .add(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} ASSERT.that(ImmutableList.copyOf(multimap.entries())) .is(ImmutableList.copyOf(constrained.entries())); assertEquals(multimap.asMap(), constrained.asMap()); assertEquals(multimap.values(), constrained.values()); assertEquals(multimap.keys(), constrained.keys()); assertEquals(multimap.keySet(), constrained.keySet()); assertEquals(multimap.toString(), constrained.toString()); assertEquals(multimap.hashCode(), constrained.hashCode()); } private static class QueueSupplier implements Supplier<Queue<Integer>> { @Override public Queue<Integer> get() { return new LinkedList<Integer>(); } } public void testConstrainedMultimapQueue() { Multimap<String, Integer> multimap = Multimaps.newMultimap( new HashMap<String, Collection<Integer>>(), new QueueSupplier()); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap( multimap, TEST_CONSTRAINT); constrained.put("foo", 1); assertTrue(constrained.get("foo").contains(1)); assertTrue(multimap.get("foo").contains(1)); try { constrained.put(TEST_KEY, 1); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.put("foo", TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.get("foo").add(TEST_VALUE); fail("TestKeyException expected"); } catch (TestValueException expected) {} try { constrained.get(TEST_KEY).add(1); fail("TestValueException expected"); } catch (TestKeyException expected) {} assertEquals(1, constrained.size()); assertEquals(1, multimap.size()); } public void testMapEntrySetToArray() { Map<String, Integer> map = Maps.newLinkedHashMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap(map, TEST_CONSTRAINT); map.put("foo", 1); @SuppressWarnings("unchecked") Map.Entry<String, Integer> entry = (Map.Entry) constrained.entrySet().toArray()[0]; try { entry.setValue(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} assertFalse(map.containsValue(TEST_VALUE)); } public void testMapEntrySetContainsNefariousEntry() { Map<String, Integer> map = Maps.newTreeMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap(map, TEST_CONSTRAINT); map.put("foo", 1); Map.Entry<String, Integer> nefariousEntry = nefariousMapEntry(TEST_KEY, TEST_VALUE); Set<Map.Entry<String, Integer>> entries = constrained.entrySet(); assertFalse(entries.contains(nefariousEntry)); assertFalse(map.containsValue(TEST_VALUE)); assertFalse(entries.containsAll(Collections.singleton(nefariousEntry))); assertFalse(map.containsValue(TEST_VALUE)); } public void testMultimapAsMapEntriesToArray() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap(multimap, TEST_CONSTRAINT); multimap.put("foo", 1); @SuppressWarnings("unchecked") Map.Entry<String, Collection<Integer>> entry = (Map.Entry<String, Collection<Integer>>) constrained.asMap().entrySet().toArray()[0]; try { entry.setValue(Collections.<Integer>emptySet()); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { entry.getValue().add(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} assertFalse(multimap.containsValue(TEST_VALUE)); } public void testMultimapAsMapValuesToArray() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap(multimap, TEST_CONSTRAINT); multimap.put("foo", 1); @SuppressWarnings("unchecked") Collection<Integer> collection = (Collection<Integer>) constrained.asMap().values().toArray()[0]; try { collection.add(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} assertFalse(multimap.containsValue(TEST_VALUE)); } public void testMultimapEntriesContainsNefariousEntry() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap(multimap, TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, Integer> nefariousEntry = nefariousMapEntry(TEST_KEY, TEST_VALUE); Collection<Map.Entry<String, Integer>> entries = constrained.entries(); assertFalse(entries.contains(nefariousEntry)); assertFalse(multimap.containsValue(TEST_VALUE)); assertFalse(entries.containsAll(Collections.singleton(nefariousEntry))); assertFalse(multimap.containsValue(TEST_VALUE)); } public void testMultimapEntriesRemoveNefariousEntry() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap(multimap, TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, Integer> nefariousEntry = nefariousMapEntry(TEST_KEY, TEST_VALUE); Collection<Map.Entry<String, Integer>> entries = constrained.entries(); assertFalse(entries.remove(nefariousEntry)); assertFalse(multimap.containsValue(TEST_VALUE)); assertFalse(entries.removeAll(Collections.singleton(nefariousEntry))); assertFalse(multimap.containsValue(TEST_VALUE)); } public void testMultimapAsMapEntriesContainsNefariousEntry() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap(multimap, TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, ? extends Collection<Integer>> nefariousEntry = nefariousMapEntry(TEST_KEY, Collections.singleton(TEST_VALUE)); Set<Map.Entry<String, Collection<Integer>>> entries = constrained.asMap().entrySet(); assertFalse(entries.contains(nefariousEntry)); assertFalse(multimap.containsValue(TEST_VALUE)); assertFalse(entries.containsAll(Collections.singleton(nefariousEntry))); assertFalse(multimap.containsValue(TEST_VALUE)); } public void testMultimapAsMapEntriesRemoveNefariousEntry() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap(multimap, TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, ? extends Collection<Integer>> nefariousEntry = nefariousMapEntry(TEST_KEY, Collections.singleton(TEST_VALUE)); Set<Map.Entry<String, Collection<Integer>>> entries = constrained.asMap().entrySet(); assertFalse(entries.remove(nefariousEntry)); assertFalse(multimap.containsValue(TEST_VALUE)); assertFalse(entries.removeAll(Collections.singleton(nefariousEntry))); assertFalse(multimap.containsValue(TEST_VALUE)); } public void testNefariousMapPutAll() { Map<String, Integer> map = Maps.newLinkedHashMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap( map, TEST_CONSTRAINT); Map<String, Integer> onceIterable = onceIterableMap("foo", 1); constrained.putAll(onceIterable); assertEquals((Integer) 1, constrained.get("foo")); } public void testNefariousMultimapPutAllIterable() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap( multimap, TEST_CONSTRAINT); Collection<Integer> onceIterable = ConstraintsTest.onceIterableCollection(1); constrained.putAll("foo", onceIterable); assertEquals(ImmutableList.of(1), constrained.get("foo")); } public void testNefariousMultimapPutAllMultimap() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap( multimap, TEST_CONSTRAINT); Multimap<String, Integer> onceIterable = Multimaps.forMap(onceIterableMap("foo", 1)); constrained.putAll(onceIterable); assertEquals(ImmutableList.of(1), constrained.get("foo")); } public void testNefariousMultimapGetAddAll() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap( multimap, TEST_CONSTRAINT); Collection<Integer> onceIterable = ConstraintsTest.onceIterableCollection(1); constrained.get("foo").addAll(onceIterable); assertEquals(ImmutableList.of(1), constrained.get("foo")); } /** * Returns a "nefarious" map, which permits only one call to its views' * iterator() methods. This verifies that the constrained map uses a * defensive copy instead of potentially checking the elements in one snapshot * and adding the elements from another. * * @param key the key to be contained in the map * @param value the value to be contained in the map */ static <K, V> Map<K, V> onceIterableMap(K key, V value) { final Map.Entry<K, V> entry = Maps.immutableEntry(key, value); return new AbstractMap<K, V>() { boolean iteratorCalled; @Override public int size() { /* * We could make the map empty, but that seems more likely to trigger * special cases (so maybe we should test both empty and nonempty...). */ return 1; } @Override public Set<Entry<K, V>> entrySet() { return new ForwardingSet<Entry<K, V>>() { @Override protected Set<Entry<K, V>> delegate() { return Collections.singleton(entry); } @Override public Iterator<Entry<K, V>> iterator() { assertFalse("Expected only one call to iterator()", iteratorCalled); iteratorCalled = true; return super.iterator(); } }; } @Override public Set<K> keySet() { throw new UnsupportedOperationException(); } @Override public Collection<V> values() { throw new UnsupportedOperationException(); } }; } }
Java
/* * Copyright (C) 2008 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.collect; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.HashSet; import java.util.Set; /** * Unit tests for {@link Sets#union}, {@link Sets#intersection} and * {@link Sets#difference}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class SetOperationsTest extends TestCase { public static class MoreTests extends TestCase { Set<String> friends; Set<String> enemies; @Override public void setUp() { friends = Sets.newHashSet("Tom", "Joe", "Dave"); enemies = Sets.newHashSet("Dick", "Harry", "Tom"); } public void testUnion() { Set<String> all = Sets.union(friends, enemies); assertEquals(5, all.size()); ImmutableSet<String> immut = Sets.union(friends, enemies).immutableCopy(); HashSet<String> mut = Sets.union(friends, enemies).copyInto(new HashSet<String>()); enemies.add("Buck"); assertEquals(6, all.size()); assertEquals(5, immut.size()); assertEquals(5, mut.size()); } public void testIntersection() { Set<String> friends = Sets.newHashSet("Tom", "Joe", "Dave"); Set<String> enemies = Sets.newHashSet("Dick", "Harry", "Tom"); Set<String> frenemies = Sets.intersection(friends, enemies); assertEquals(1, frenemies.size()); ImmutableSet<String> immut = Sets.intersection(friends, enemies).immutableCopy(); HashSet<String> mut = Sets.intersection(friends, enemies).copyInto(new HashSet<String>()); enemies.add("Joe"); assertEquals(2, frenemies.size()); assertEquals(1, immut.size()); assertEquals(1, mut.size()); } public void testDifference() { Set<String> friends = Sets.newHashSet("Tom", "Joe", "Dave"); Set<String> enemies = Sets.newHashSet("Dick", "Harry", "Tom"); Set<String> goodFriends = Sets.difference(friends, enemies); assertEquals(2, goodFriends.size()); ImmutableSet<String> immut = Sets.difference(friends, enemies).immutableCopy(); HashSet<String> mut = Sets.difference(friends, enemies).copyInto(new HashSet<String>()); enemies.add("Dave"); assertEquals(1, goodFriends.size()); assertEquals(2, immut.size()); assertEquals(2, mut.size()); } public void testSymmetricDifference() { Set<String> friends = Sets.newHashSet("Tom", "Joe", "Dave"); Set<String> enemies = Sets.newHashSet("Dick", "Harry", "Tom"); Set<String> symmetricDifferenceFriendsFirst = Sets.symmetricDifference( friends, enemies); assertEquals(4, symmetricDifferenceFriendsFirst.size()); Set<String> symmetricDifferenceEnemiesFirst = Sets.symmetricDifference( enemies, friends); assertEquals(4, symmetricDifferenceEnemiesFirst.size()); assertEquals(symmetricDifferenceFriendsFirst, symmetricDifferenceEnemiesFirst); ImmutableSet<String> immut = Sets.symmetricDifference(friends, enemies).immutableCopy(); HashSet<String> mut = Sets.symmetricDifference(friends, enemies) .copyInto(new HashSet<String>()); enemies.add("Dave"); assertEquals(3, symmetricDifferenceFriendsFirst.size()); assertEquals(4, immut.size()); assertEquals(4, mut.size()); immut = Sets.symmetricDifference(enemies, friends).immutableCopy(); mut = Sets.symmetricDifference(enemies, friends). copyInto(new HashSet<String>()); friends.add("Harry"); assertEquals(2, symmetricDifferenceEnemiesFirst.size()); assertEquals(3, immut.size()); assertEquals(3, mut.size()); } } }
Java
/* * Copyright (C) 2009 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableSetMultimap.Builder; import com.google.common.collect.testing.google.UnmodifiableCollectionTests; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collections; import java.util.Map.Entry; /** * Tests for {@link ImmutableSetMultimap}. * * @author Mike Ward */ @GwtCompatible(emulated = true) public class ImmutableSetMultimapTest extends TestCase { public void testBuilder_withImmutableEntry() { ImmutableSetMultimap<String, Integer> multimap = new Builder<String, Integer>() .put(Maps.immutableEntry("one", 1)) .build(); assertEquals(ImmutableSet.of(1), multimap.get("one")); } public void testBuilder_withImmutableEntryAndNullContents() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(Maps.immutableEntry("one", (Integer) null)); fail(); } catch (NullPointerException expected) { } try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) { } } private static class StringHolder { String string; } public void testBuilder_withMutableEntry() { ImmutableSetMultimap.Builder<String, Integer> builder = new Builder<String, Integer>(); final StringHolder holder = new StringHolder(); holder.string = "one"; Entry<String, Integer> entry = new AbstractMapEntry<String, Integer>() { @Override public String getKey() { return holder.string; } @Override public Integer getValue() { return 1; } }; builder.put(entry); holder.string = "two"; assertEquals(ImmutableSet.of(1), builder.build().get("one")); } public void testBuilderPutAllIterable() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.putAll("foo", Arrays.asList(1, 2, 3)); builder.putAll("bar", Arrays.asList(4, 5)); builder.putAll("foo", Arrays.asList(6, 7)); Multimap<String, Integer> multimap = builder.build(); assertEquals(ImmutableSet.of(1, 2, 3, 6, 7), multimap.get("foo")); assertEquals(ImmutableSet.of(4, 5), multimap.get("bar")); assertEquals(7, multimap.size()); } public void testBuilderPutAllVarargs() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.putAll("foo", 1, 2, 3); builder.putAll("bar", 4, 5); builder.putAll("foo", 6, 7); Multimap<String, Integer> multimap = builder.build(); assertEquals(ImmutableSet.of(1, 2, 3, 6, 7), multimap.get("foo")); assertEquals(ImmutableSet.of(4, 5), multimap.get("bar")); assertEquals(7, multimap.size()); } public void testBuilderPutAllMultimap() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put("foo", 1); toPut.put("bar", 4); toPut.put("foo", 2); toPut.put("foo", 3); Multimap<String, Integer> moreToPut = LinkedListMultimap.create(); moreToPut.put("foo", 6); moreToPut.put("bar", 5); moreToPut.put("foo", 7); ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.putAll(toPut); builder.putAll(moreToPut); Multimap<String, Integer> multimap = builder.build(); assertEquals(ImmutableSet.of(1, 2, 3, 6, 7), multimap.get("foo")); assertEquals(ImmutableSet.of(4, 5), multimap.get("bar")); assertEquals(7, multimap.size()); } public void testBuilderPutAllWithDuplicates() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.putAll("foo", 1, 2, 3); builder.putAll("bar", 4, 5); builder.putAll("foo", 1, 6, 7); ImmutableSetMultimap<String, Integer> multimap = builder.build(); assertEquals(7, multimap.size()); } public void testBuilderPutWithDuplicates() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.putAll("foo", 1, 2, 3); builder.putAll("bar", 4, 5); builder.put("foo", 1); ImmutableSetMultimap<String, Integer> multimap = builder.build(); assertEquals(5, multimap.size()); } public void testBuilderPutAllMultimapWithDuplicates() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put("foo", 1); toPut.put("bar", 4); toPut.put("foo", 2); toPut.put("foo", 1); toPut.put("bar", 5); ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.putAll(toPut); ImmutableSetMultimap<String, Integer> multimap = builder.build(); assertEquals(4, multimap.size()); } public void testBuilderPutNullKey() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put("foo", null); ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); try { builder.put(null, 1); fail(); } catch (NullPointerException expected) {} try { builder.putAll(null, Arrays.asList(1, 2, 3)); fail(); } catch (NullPointerException expected) {} try { builder.putAll(null, 1, 2, 3); fail(); } catch (NullPointerException expected) {} try { builder.putAll(toPut); fail(); } catch (NullPointerException expected) {} } public void testBuilderPutNullValue() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put(null, 1); ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); try { builder.put("foo", null); fail(); } catch (NullPointerException expected) {} try { builder.putAll("foo", Arrays.asList(1, null, 3)); fail(); } catch (NullPointerException expected) {} try { builder.putAll("foo", 4, null, 6); fail(); } catch (NullPointerException expected) {} try { builder.putAll(toPut); fail(); } catch (NullPointerException expected) {} } public void testBuilderOrderKeysBy() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.put("b", 3); builder.put("d", 2); builder.put("a", 5); builder.orderKeysBy(Collections.reverseOrder()); builder.put("c", 4); builder.put("a", 2); builder.put("b", 6); ImmutableSetMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); ASSERT.that(multimap.values()).has().exactly(2, 4, 3, 6, 5, 2).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("b")).has().exactly(3, 6).inOrder(); assertFalse(multimap.get("a") instanceof ImmutableSortedSet); assertFalse(multimap.get("x") instanceof ImmutableSortedSet); assertFalse(multimap.asMap().get("a") instanceof ImmutableSortedSet); } public void testBuilderOrderKeysByDuplicates() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.put("bb", 3); builder.put("d", 2); builder.put("a", 5); builder.orderKeysBy(new Ordering<String>() { @Override public int compare(String left, String right) { return left.length() - right.length(); } }); builder.put("cc", 4); builder.put("a", 2); builder.put("bb", 6); ImmutableSetMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("d", "a", "bb", "cc").inOrder(); ASSERT.that(multimap.values()).has().exactly(2, 5, 2, 3, 6, 4).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("bb")).has().exactly(3, 6).inOrder(); assertFalse(multimap.get("a") instanceof ImmutableSortedSet); assertFalse(multimap.get("x") instanceof ImmutableSortedSet); assertFalse(multimap.asMap().get("a") instanceof ImmutableSortedSet); } public void testBuilderOrderValuesBy() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.put("b", 3); builder.put("d", 2); builder.put("a", 5); builder.orderValuesBy(Collections.reverseOrder()); builder.put("c", 4); builder.put("a", 2); builder.put("b", 6); ImmutableSetMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("b", "d", "a", "c").inOrder(); ASSERT.that(multimap.values()).has().exactly(6, 3, 2, 5, 2, 4).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("b")).has().exactly(6, 3).inOrder(); assertTrue(multimap.get("a") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.get("a")).comparator()); assertTrue(multimap.get("x") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.get("x")).comparator()); assertTrue(multimap.asMap().get("a") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.asMap().get("a")).comparator()); } public void testBuilderOrderKeysAndValuesBy() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.put("b", 3); builder.put("d", 2); builder.put("a", 5); builder.orderKeysBy(Collections.reverseOrder()); builder.orderValuesBy(Collections.reverseOrder()); builder.put("c", 4); builder.put("a", 2); builder.put("b", 6); ImmutableSetMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); ASSERT.that(multimap.values()).has().exactly(2, 4, 6, 3, 5, 2).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("b")).has().exactly(6, 3).inOrder(); assertTrue(multimap.get("a") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.get("a")).comparator()); assertTrue(multimap.get("x") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.get("x")).comparator()); assertTrue(multimap.asMap().get("a") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.asMap().get("a")).comparator()); } public void testCopyOf() { HashMultimap<String, Integer> input = HashMultimap.create(); input.put("foo", 1); input.put("bar", 2); input.put("foo", 3); Multimap<String, Integer> multimap = ImmutableSetMultimap.copyOf(input); assertEquals(multimap, input); assertEquals(input, multimap); } public void testCopyOfWithDuplicates() { ArrayListMultimap<Object, Object> input = ArrayListMultimap.create(); input.put("foo", 1); input.put("bar", 2); input.put("foo", 3); input.put("foo", 1); ImmutableSetMultimap<Object, Object> copy = ImmutableSetMultimap.copyOf(input); assertEquals(3, copy.size()); } public void testCopyOfEmpty() { HashMultimap<String, Integer> input = HashMultimap.create(); Multimap<String, Integer> multimap = ImmutableSetMultimap.copyOf(input); assertEquals(multimap, input); assertEquals(input, multimap); } public void testCopyOfImmutableSetMultimap() { Multimap<String, Integer> multimap = createMultimap(); assertSame(multimap, ImmutableSetMultimap.copyOf(multimap)); } public void testCopyOfNullKey() { HashMultimap<String, Integer> input = HashMultimap.create(); input.put(null, 1); try { ImmutableSetMultimap.copyOf(input); fail(); } catch (NullPointerException expected) {} } public void testCopyOfNullValue() { HashMultimap<String, Integer> input = HashMultimap.create(); input.putAll("foo", Arrays.asList(1, null, 3)); try { ImmutableSetMultimap.copyOf(input); fail(); } catch (NullPointerException expected) {} } public void testEmptyMultimapReads() { Multimap<String, Integer> multimap = ImmutableSetMultimap.of(); assertFalse(multimap.containsKey("foo")); assertFalse(multimap.containsValue(1)); assertFalse(multimap.containsEntry("foo", 1)); assertTrue(multimap.entries().isEmpty()); assertTrue(multimap.equals(HashMultimap.create())); assertEquals(Collections.emptySet(), multimap.get("foo")); assertEquals(0, multimap.hashCode()); assertTrue(multimap.isEmpty()); assertEquals(HashMultiset.create(), multimap.keys()); assertEquals(Collections.emptySet(), multimap.keySet()); assertEquals(0, multimap.size()); assertTrue(multimap.values().isEmpty()); assertEquals("{}", multimap.toString()); } public void testEmptyMultimapWrites() { Multimap<String, Integer> multimap = ImmutableSetMultimap.of(); UnmodifiableCollectionTests.assertMultimapIsUnmodifiable( multimap, "foo", 1); } public void testMultimapReads() { Multimap<String, Integer> multimap = createMultimap(); assertTrue(multimap.containsKey("foo")); assertFalse(multimap.containsKey("cat")); assertTrue(multimap.containsValue(1)); assertFalse(multimap.containsValue(5)); assertTrue(multimap.containsEntry("foo", 1)); assertFalse(multimap.containsEntry("cat", 1)); assertFalse(multimap.containsEntry("foo", 5)); assertFalse(multimap.entries().isEmpty()); assertEquals(3, multimap.size()); assertFalse(multimap.isEmpty()); assertEquals("{foo=[1, 3], bar=[2]}", multimap.toString()); } public void testMultimapWrites() { Multimap<String, Integer> multimap = createMultimap(); UnmodifiableCollectionTests.assertMultimapIsUnmodifiable( multimap, "bar", 2); } public void testMultimapEquals() { Multimap<String, Integer> multimap = createMultimap(); Multimap<String, Integer> hashMultimap = HashMultimap.create(); hashMultimap.putAll("foo", Arrays.asList(1, 3)); hashMultimap.put("bar", 2); new EqualsTester() .addEqualityGroup( multimap, createMultimap(), hashMultimap, ImmutableSetMultimap.<String, Integer>builder() .put("bar", 2).put("foo", 1).put("foo", 3).build(), ImmutableSetMultimap.<String, Integer>builder() .put("bar", 2).put("foo", 3).put("foo", 1).build()) .addEqualityGroup(ImmutableSetMultimap.<String, Integer>builder() .put("foo", 2).put("foo", 3).put("foo", 1).build()) .addEqualityGroup(ImmutableSetMultimap.<String, Integer>builder() .put("bar", 2).put("foo", 3).build()) .testEquals(); } public void testOf() { assertMultimapEquals( ImmutableSetMultimap.of("one", 1), "one", 1); assertMultimapEquals( ImmutableSetMultimap.of("one", 1, "two", 2), "one", 1, "two", 2); assertMultimapEquals( ImmutableSetMultimap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3); assertMultimapEquals( ImmutableSetMultimap.of("one", 1, "two", 2, "three", 3, "four", 4), "one", 1, "two", 2, "three", 3, "four", 4); assertMultimapEquals( ImmutableSetMultimap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); } public void testInverse() { assertEquals( ImmutableSetMultimap.<Integer, String>of(), ImmutableSetMultimap.<String, Integer>of().inverse()); assertEquals( ImmutableSetMultimap.of(1, "one"), ImmutableSetMultimap.of("one", 1).inverse()); assertEquals( ImmutableSetMultimap.of(1, "one", 2, "two"), ImmutableSetMultimap.of("one", 1, "two", 2).inverse()); assertEquals( ImmutableSetMultimap.of('o', "of", 'f', "of", 't', "to", 'o', "to"), ImmutableSetMultimap.of("of", 'o', "of", 'f', "to", 't', "to", 'o').inverse()); } public void testInverseMinimizesWork() { ImmutableSetMultimap<String, Character> multimap = ImmutableSetMultimap.of("of", 'o', "of", 'f', "to", 't', "to", 'o'); assertSame(multimap.inverse(), multimap.inverse()); assertSame(multimap, multimap.inverse().inverse()); } private static <K, V> void assertMultimapEquals(Multimap<K, V> multimap, Object... alternatingKeysAndValues) { assertEquals(multimap.size(), alternatingKeysAndValues.length / 2); int i = 0; for (Entry<K, V> entry : multimap.entries()) { assertEquals(alternatingKeysAndValues[i++], entry.getKey()); assertEquals(alternatingKeysAndValues[i++], entry.getValue()); } } private ImmutableSetMultimap<String, Integer> createMultimap() { return ImmutableSetMultimap.<String, Integer>builder() .put("foo", 1).put("bar", 2).put("foo", 3).build(); } }
Java
/* * Copyright (C) 2007 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.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.RandomAccess; /** * Tests for {@code LinkedListMultimap}. * * @author Mike Bostock */ @GwtCompatible(emulated = true) public class LinkedListMultimapTest extends TestCase { protected LinkedListMultimap<String, Integer> create() { return LinkedListMultimap.create(); } /** * Confirm that get() returns a List that doesn't implement RandomAccess. */ public void testGetRandomAccess() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); assertFalse(multimap.get("foo") instanceof RandomAccess); assertFalse(multimap.get("bar") instanceof RandomAccess); } /** * Confirm that removeAll() returns a List that implements RandomAccess, even * though get() doesn't. */ public void testRemoveAllRandomAccess() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); assertTrue(multimap.removeAll("foo") instanceof RandomAccess); assertTrue(multimap.removeAll("bar") instanceof RandomAccess); } /** * Confirm that replaceValues() returns a List that implements RandomAccess, * even though get() doesn't. */ public void testReplaceValuesRandomAccess() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); assertTrue(multimap.replaceValues("foo", Arrays.asList(2, 4)) instanceof RandomAccess); assertTrue(multimap.replaceValues("bar", Arrays.asList(2, 4)) instanceof RandomAccess); } public void testCreateFromMultimap() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 3); multimap.put("foo", 2); LinkedListMultimap<String, Integer> copy = LinkedListMultimap.create(multimap); assertEquals(multimap, copy); ASSERT.that(copy.entries()).has().exactlyAs(multimap.entries()).inOrder(); } public void testCreateFromSize() { LinkedListMultimap<String, Integer> multimap = LinkedListMultimap.create(20); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("foo", 3); assertEquals(ImmutableList.of(1, 3), multimap.get("foo")); } public void testCreateFromIllegalSize() { try { LinkedListMultimap.create(-20); fail(); } catch (IllegalArgumentException expected) {} } public void testLinkedGetAdd() { LinkedListMultimap<String, Integer> map = create(); map.put("bar", 1); Collection<Integer> foos = map.get("foo"); foos.add(2); foos.add(3); map.put("bar", 4); map.put("foo", 5); assertEquals("{bar=[1, 4], foo=[2, 3, 5]}", map.toString()); assertEquals("[bar=1, foo=2, foo=3, bar=4, foo=5]", map.entries().toString()); } public void testLinkedGetInsert() { ListMultimap<String, Integer> map = create(); map.put("bar", 1); List<Integer> foos = map.get("foo"); foos.add(2); foos.add(0, 3); map.put("bar", 4); map.put("foo", 5); assertEquals("{bar=[1, 4], foo=[3, 2, 5]}", map.toString()); assertEquals("[bar=1, foo=3, foo=2, bar=4, foo=5]", map.entries().toString()); } public void testLinkedPutInOrder() { Multimap<String, Integer> map = create(); map.put("foo", 1); map.put("bar", 2); map.put("bar", 3); assertEquals("{foo=[1], bar=[2, 3]}", map.toString()); assertEquals("[foo=1, bar=2, bar=3]", map.entries().toString()); } public void testLinkedPutOutOfOrder() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); assertEquals("{bar=[1, 3], foo=[2]}", map.toString()); assertEquals("[bar=1, foo=2, bar=3]", map.entries().toString()); } public void testLinkedPutAllMultimap() { Multimap<String, Integer> src = create(); src.put("bar", 1); src.put("foo", 2); src.put("bar", 3); Multimap<String, Integer> dst = create(); dst.putAll(src); assertEquals("{bar=[1, 3], foo=[2]}", dst.toString()); assertEquals("[bar=1, foo=2, bar=3]", src.entries().toString()); } public void testLinkedReplaceValues() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); map.put("bar", 4); assertEquals("{bar=[1, 3, 4], foo=[2]}", map.toString()); map.replaceValues("bar", asList(1, 2)); assertEquals("[bar=1, foo=2, bar=2]", map.entries().toString()); assertEquals("{bar=[1, 2], foo=[2]}", map.toString()); } public void testLinkedClear() { ListMultimap<String, Integer> map = create(); map.put("foo", 1); map.put("foo", 2); map.put("bar", 3); List<Integer> foos = map.get("foo"); Collection<Integer> values = map.values(); assertEquals(asList(1, 2), foos); ASSERT.that(values).has().exactly(1, 2, 3).inOrder(); map.clear(); assertEquals(Collections.emptyList(), foos); ASSERT.that(values).isEmpty(); assertEquals("[]", map.entries().toString()); assertEquals("{}", map.toString()); } public void testLinkedKeySet() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); map.put("bar", 4); assertEquals("[bar, foo]", map.keySet().toString()); map.keySet().remove("bar"); assertEquals("{foo=[2]}", map.toString()); } public void testLinkedKeys() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); map.put("bar", 4); assertEquals("[bar=1, foo=2, bar=3, bar=4]", map.entries().toString()); ASSERT.that(map.keys()).has().exactly("bar", "foo", "bar", "bar").inOrder(); map.keys().remove("bar"); // bar is no longer the first key! assertEquals("{foo=[2], bar=[3, 4]}", map.toString()); } public void testLinkedValues() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); map.put("bar", 4); assertEquals("[1, 2, 3, 4]", map.values().toString()); map.values().remove(2); assertEquals("{bar=[1, 3, 4]}", map.toString()); } public void testLinkedEntries() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); Iterator<Map.Entry<String, Integer>> entries = map.entries().iterator(); Map.Entry<String, Integer> entry = entries.next(); assertEquals("bar", entry.getKey()); assertEquals(1, (int) entry.getValue()); entry = entries.next(); assertEquals("foo", entry.getKey()); assertEquals(2, (int) entry.getValue()); entry.setValue(4); entry = entries.next(); assertEquals("bar", entry.getKey()); assertEquals(3, (int) entry.getValue()); assertFalse(entries.hasNext()); entries.remove(); assertEquals("{bar=[1], foo=[4]}", map.toString()); } public void testLinkedAsMapEntries() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); Iterator<Map.Entry<String, Collection<Integer>>> entries = map.asMap().entrySet().iterator(); Map.Entry<String, Collection<Integer>> entry = entries.next(); assertEquals("bar", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(1, 3).inOrder(); try { entry.setValue(Arrays.<Integer>asList()); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} entries.remove(); // clear entry = entries.next(); assertEquals("foo", entry.getKey()); ASSERT.that(entry.getValue()).has().item(2); assertFalse(entries.hasNext()); assertEquals("{foo=[2]}", map.toString()); } public void testEntriesAfterMultimapUpdate() { ListMultimap<String, Integer> multimap = create(); multimap.put("foo", 2); multimap.put("bar", 3); Collection<Map.Entry<String, Integer>> entries = multimap.entries(); Iterator<Map.Entry<String, Integer>> iterator = entries.iterator(); Map.Entry<String, Integer> entrya = iterator.next(); Map.Entry<String, Integer> entryb = iterator.next(); assertEquals(2, (int) multimap.get("foo").set(0, 4)); assertFalse(multimap.containsEntry("foo", 2)); assertTrue(multimap.containsEntry("foo", 4)); assertTrue(multimap.containsEntry("bar", 3)); assertEquals(4, (int) entrya.getValue()); assertEquals(3, (int) entryb.getValue()); assertTrue(multimap.put("foo", 5)); assertTrue(multimap.containsEntry("foo", 5)); assertTrue(multimap.containsEntry("foo", 4)); assertTrue(multimap.containsEntry("bar", 3)); assertEquals(4, (int) entrya.getValue()); assertEquals(3, (int) entryb.getValue()); } public void testEquals() { new EqualsTester() .addEqualityGroup( LinkedListMultimap.create(), LinkedListMultimap.create(), LinkedListMultimap.create(1)) .testEquals(); } }
Java
/* * Copyright (C) 2011 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.collect; import com.google.common.annotations.GwtCompatible; /** * Variant of {@link SerializableTester} that does not require the reserialized object's class to be * identical to the original. * * @author Chris Povirk */ /* * The whole thing is really @GwtIncompatible, but GwtJUnitConvertedTestModule doesn't have a * parameter for non-GWT, non-test files, and it didn't seem worth adding one for this unusual case. */ @GwtCompatible(emulated = true) final class LenientSerializableTester { /* * TODO(cpovirk): move this to c.g.c.testing if we allow for c.g.c.annotations dependencies so * that it can be GWTified? */ private LenientSerializableTester() {} }
Java
/* * Copyright (C) 2009 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.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSortedMap.Builder; import com.google.common.collect.testing.SortedMapInterfaceTest; import junit.framework.TestCase; import java.io.Serializable; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; /** * Tests for {@link ImmutableSortedMap}. * * @author Kevin Bourrillion * @author Jesse Wilson * @author Jared Levy */ @GwtCompatible(emulated = true) public class ImmutableSortedMapTest extends TestCase { // TODO: Avoid duplicating code in ImmutableMapTest public abstract static class AbstractMapTests<K, V> extends SortedMapInterfaceTest<K, V> { public AbstractMapTests() { super(false, false, false, false, false); } @Override protected SortedMap<K, V> makeEmptyMap() { throw new UnsupportedOperationException(); } private static final Joiner joiner = Joiner.on(", "); @Override protected void assertMoreInvariants(Map<K, V> map) { // TODO: can these be moved to MapInterfaceTest? for (Entry<K, V> entry : map.entrySet()) { assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString()); } assertEquals("{" + joiner.join(map.entrySet()) + "}", map.toString()); assertEquals("[" + joiner.join(map.entrySet()) + "]", map.entrySet().toString()); assertEquals("[" + joiner.join(map.keySet()) + "]", map.keySet().toString()); assertEquals("[" + joiner.join(map.values()) + "]", map.values().toString()); assertEquals(Sets.newHashSet(map.entrySet()), map.entrySet()); assertEquals(Sets.newHashSet(map.keySet()), map.keySet()); } } public static class MapTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makeEmptyMap() { return ImmutableSortedMap.of(); } @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("one", 1, "two", 2, "three", 3); } @Override protected String getKeyNotInPopulatedMap() { return "minus one"; } @Override protected Integer getValueNotInPopulatedMap() { return -1; } } public static class SingletonMapTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("one", 1); } @Override protected String getKeyNotInPopulatedMap() { return "minus one"; } @Override protected Integer getValueNotInPopulatedMap() { return -1; } } public static class HeadMapTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5) .headMap("d"); } @Override protected String getKeyNotInPopulatedMap() { return "d"; } @Override protected Integer getValueNotInPopulatedMap() { return 4; } } public static class HeadMapInclusiveTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5) .headMap("c", true); } @Override protected String getKeyNotInPopulatedMap() { return "d"; } @Override protected Integer getValueNotInPopulatedMap() { return 4; } } public static class TailMapTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5) .tailMap("b"); } @Override protected String getKeyNotInPopulatedMap() { return "a"; } @Override protected Integer getValueNotInPopulatedMap() { return 1; } } public static class TailExclusiveMapTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5) .tailMap("a", false); } @Override protected String getKeyNotInPopulatedMap() { return "a"; } @Override protected Integer getValueNotInPopulatedMap() { return 1; } } public static class SubMapTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5) .subMap("b", "d"); } @Override protected String getKeyNotInPopulatedMap() { return "a"; } @Override protected Integer getValueNotInPopulatedMap() { return 4; } } public static class CreationTests extends TestCase { public void testEmptyBuilder() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>naturalOrder().build(); assertEquals(Collections.<String, Integer>emptyMap(), map); } public void testSingletonBuilder() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>naturalOrder() .put("one", 1) .build(); assertMapEquals(map, "one", 1); } public void testBuilder() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>naturalOrder() .put("one", 1) .put("two", 2) .put("three", 3) .put("four", 4) .put("five", 5) .build(); assertMapEquals(map, "five", 5, "four", 4, "one", 1, "three", 3, "two", 2); } public void testBuilder_withImmutableEntry() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>naturalOrder() .put(Maps.immutableEntry("one", 1)) .build(); assertMapEquals(map, "one", 1); } public void testBuilder_withImmutableEntryAndNullContents() { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); try { builder.put(Maps.immutableEntry("one", (Integer) null)); fail(); } catch (NullPointerException expected) { } try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) { } } private static class StringHolder { String string; } public void testBuilder_withMutableEntry() { ImmutableSortedMap.Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); final StringHolder holder = new StringHolder(); holder.string = "one"; Entry<String, Integer> entry = new AbstractMapEntry<String, Integer>() { @Override public String getKey() { return holder.string; } @Override public Integer getValue() { return 1; } }; builder.put(entry); holder.string = "two"; assertMapEquals(builder.build(), "one", 1); } public void testBuilderPutAllWithEmptyMap() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>naturalOrder() .putAll(Collections.<String, Integer>emptyMap()) .build(); assertEquals(Collections.<String, Integer>emptyMap(), map); } public void testBuilderPutAll() { Map<String, Integer> toPut = new LinkedHashMap<String, Integer>(); toPut.put("one", 1); toPut.put("two", 2); toPut.put("three", 3); Map<String, Integer> moreToPut = new LinkedHashMap<String, Integer>(); moreToPut.put("four", 4); moreToPut.put("five", 5); ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>naturalOrder() .putAll(toPut) .putAll(moreToPut) .build(); assertMapEquals(map, "five", 5, "four", 4, "one", 1, "three", 3, "two", 2); } public void testBuilderReuse() { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); ImmutableSortedMap<String, Integer> mapOne = builder .put("one", 1) .put("two", 2) .build(); ImmutableSortedMap<String, Integer> mapTwo = builder .put("three", 3) .put("four", 4) .build(); assertMapEquals(mapOne, "one", 1, "two", 2); assertMapEquals(mapTwo, "four", 4, "one", 1, "three", 3, "two", 2); } public void testBuilderPutNullKey() { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); try { builder.put(null, 1); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullValue() { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); try { builder.put("one", null); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullKeyViaPutAll() { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); try { builder.putAll(Collections.<String, Integer>singletonMap(null, 1)); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullValueViaPutAll() { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); try { builder.putAll(Collections.<String, Integer>singletonMap("one", null)); fail(); } catch (NullPointerException expected) { } } public void testPuttingTheSameKeyTwiceThrowsOnBuild() { Builder<String, Integer> builder = ImmutableSortedMap.<String, Integer>naturalOrder() .put("one", 1) .put("one", 2); // throwing on this line would be even better try { builder.build(); fail(); } catch (IllegalArgumentException expected) { } } public void testOf() { assertMapEquals( ImmutableSortedMap.of("one", 1), "one", 1); assertMapEquals( ImmutableSortedMap.of("one", 1, "two", 2), "one", 1, "two", 2); assertMapEquals( ImmutableSortedMap.of("one", 1, "two", 2, "three", 3), "one", 1, "three", 3, "two", 2); assertMapEquals( ImmutableSortedMap.of("one", 1, "two", 2, "three", 3, "four", 4), "four", 4, "one", 1, "three", 3, "two", 2); assertMapEquals( ImmutableSortedMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5), "five", 5, "four", 4, "one", 1, "three", 3, "two", 2); } public void testOfNullKey() { Integer n = null; try { ImmutableSortedMap.of(n, 1); fail(); } catch (NullPointerException expected) { } try { ImmutableSortedMap.of("one", 1, null, 2); fail(); } catch (NullPointerException expected) { } } public void testOfNullValue() { try { ImmutableSortedMap.of("one", null); fail(); } catch (NullPointerException expected) { } try { ImmutableSortedMap.of("one", 1, "two", null); fail(); } catch (NullPointerException expected) { } } public void testOfWithDuplicateKey() { try { ImmutableSortedMap.of("one", 1, "one", 1); fail(); } catch (IllegalArgumentException expected) { } } public void testCopyOfEmptyMap() { ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(Collections.<String, Integer>emptyMap()); assertEquals(Collections.<String, Integer>emptyMap(), copy); assertSame(copy, ImmutableSortedMap.copyOf(copy)); assertSame(Ordering.natural(), copy.comparator()); } public void testCopyOfSingletonMap() { ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(Collections.singletonMap("one", 1)); assertMapEquals(copy, "one", 1); assertSame(copy, ImmutableSortedMap.copyOf(copy)); assertSame(Ordering.natural(), copy.comparator()); } public void testCopyOf() { Map<String, Integer> original = new LinkedHashMap<String, Integer>(); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original); assertMapEquals(copy, "one", 1, "three", 3, "two", 2); assertSame(copy, ImmutableSortedMap.copyOf(copy)); assertSame(Ordering.natural(), copy.comparator()); } public void testCopyOfExplicitComparator() { Comparator<String> comparator = Ordering.natural().reverse(); Map<String, Integer> original = new LinkedHashMap<String, Integer>(); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original, comparator); assertMapEquals(copy, "two", 2, "three", 3, "one", 1); assertSame(copy, ImmutableSortedMap.copyOf(copy, comparator)); assertSame(comparator, copy.comparator()); } public void testCopyOfImmutableSortedSetDifferentComparator() { Comparator<String> comparator = Ordering.natural().reverse(); Map<String, Integer> original = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3); ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original, comparator); assertMapEquals(copy, "two", 2, "three", 3, "one", 1); assertSame(copy, ImmutableSortedMap.copyOf(copy, comparator)); assertSame(comparator, copy.comparator()); } public void testCopyOfSortedNatural() { SortedMap<String, Integer> original = Maps.newTreeMap(); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOfSorted(original); assertMapEquals(copy, "one", 1, "three", 3, "two", 2); assertSame(copy, ImmutableSortedMap.copyOfSorted(copy)); assertSame(Ordering.natural(), copy.comparator()); } public void testCopyOfSortedExplicit() { Comparator<String> comparator = Ordering.natural().reverse(); SortedMap<String, Integer> original = Maps.newTreeMap(comparator); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOfSorted(original); assertMapEquals(copy, "two", 2, "three", 3, "one", 1); assertSame(copy, ImmutableSortedMap.copyOfSorted(copy)); assertSame(comparator, copy.comparator()); } private static class IntegerDiv10 implements Comparable<IntegerDiv10> { final int value; IntegerDiv10(int value) { this.value = value; } @Override public int compareTo(IntegerDiv10 o) { return value / 10 - o.value / 10; } @Override public String toString() { return Integer.toString(value); } } public void testCopyOfDuplicateKey() { Map<IntegerDiv10, String> original = ImmutableMap.of( new IntegerDiv10(3), "three", new IntegerDiv10(20), "twenty", new IntegerDiv10(11), "eleven", new IntegerDiv10(35), "thirty five", new IntegerDiv10(12), "twelve" ); try { ImmutableSortedMap.copyOf(original); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testImmutableMapCopyOfImmutableSortedMap() { IntegerDiv10 three = new IntegerDiv10(3); IntegerDiv10 eleven = new IntegerDiv10(11); IntegerDiv10 twelve = new IntegerDiv10(12); IntegerDiv10 twenty = new IntegerDiv10(20); Map<IntegerDiv10, String> original = ImmutableSortedMap.of( three, "three", eleven, "eleven", twenty, "twenty"); Map<IntegerDiv10, String> copy = ImmutableMap.copyOf(original); assertTrue(original.containsKey(twelve)); assertFalse(copy.containsKey(twelve)); } public void testBuilderReverseOrder() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>reverseOrder() .put("one", 1) .put("two", 2) .put("three", 3) .put("four", 4) .put("five", 5) .build(); assertMapEquals(map, "two", 2, "three", 3, "one", 1, "four", 4, "five", 5); assertEquals(Ordering.natural().reverse(), map.comparator()); } public void testBuilderComparator() { Comparator<String> comparator = Ordering.natural().reverse(); ImmutableSortedMap<String, Integer> map = new ImmutableSortedMap.Builder<String, Integer>(comparator) .put("one", 1) .put("two", 2) .put("three", 3) .put("four", 4) .put("five", 5) .build(); assertMapEquals(map, "two", 2, "three", 3, "one", 1, "four", 4, "five", 5); assertSame(comparator, map.comparator()); } } public void testNullGet() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.of("one", 1); assertNull(map.get(null)); } private static <K, V> void assertMapEquals(Map<K, V> map, Object... alternatingKeysAndValues) { assertEquals(map.size(), alternatingKeysAndValues.length / 2); int i = 0; for (Entry<K, V> entry : map.entrySet()) { assertEquals(alternatingKeysAndValues[i++], entry.getKey()); assertEquals(alternatingKeysAndValues[i++], entry.getValue()); } } private static class IntHolder implements Serializable { public int value; public IntHolder(int value) { this.value = value; } @Override public boolean equals(Object o) { return (o instanceof IntHolder) && ((IntHolder) o).value == value; } @Override public int hashCode() { return value; } private static final long serialVersionUID = 5; } public void testMutableValues() { IntHolder holderA = new IntHolder(1); IntHolder holderB = new IntHolder(2); Map<String, IntHolder> map = ImmutableSortedMap.of("a", holderA, "b", holderB); holderA.value = 3; assertTrue(map.entrySet().contains(Maps.immutableEntry("a", new IntHolder(3)))); Map<String, Integer> intMap = ImmutableSortedMap.of("a", 3, "b", 2); assertEquals(intMap.hashCode(), map.entrySet().hashCode()); assertEquals(intMap.hashCode(), map.hashCode()); } @SuppressWarnings("unchecked") // varargs public void testHeadMapInclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).headMap("three", true); ASSERT.that(map.entrySet()).has().exactly( Maps.immutableEntry("one", 1), Maps.immutableEntry("three", 3)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testHeadMapExclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).headMap("three", false); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("one", 1)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testTailMapInclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).tailMap("three", true); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("three", 3), Maps.immutableEntry("two", 2)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testTailMapExclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).tailMap("three", false); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("two", 2)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testSubMapExclusiveExclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).subMap("one", false, "two", false); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("three", 3)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testSubMapInclusiveExclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).subMap("one", true, "two", false); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("one", 1), Maps.immutableEntry("three", 3)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testSubMapExclusiveInclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).subMap("one", false, "two", true); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("three", 3), Maps.immutableEntry("two", 2)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testSubMapInclusiveInclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).subMap("one", true, "two", true); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("one", 1), Maps.immutableEntry("three", 3), Maps.immutableEntry("two", 2)).inOrder(); } private static class SelfComparableExample implements Comparable<SelfComparableExample> { @Override public int compareTo(SelfComparableExample o) { return 0; } } public void testBuilderGenerics_SelfComparable() { ImmutableSortedMap.Builder<SelfComparableExample, Object> natural = ImmutableSortedMap.naturalOrder(); ImmutableSortedMap.Builder<SelfComparableExample, Object> reverse = ImmutableSortedMap.reverseOrder(); } private static class SuperComparableExample extends SelfComparableExample {} public void testBuilderGenerics_SuperComparable() { ImmutableSortedMap.Builder<SuperComparableExample, Object> natural = ImmutableSortedMap.naturalOrder(); ImmutableSortedMap.Builder<SuperComparableExample, Object> reverse = ImmutableSortedMap.reverseOrder(); } }
Java
/* * Copyright (C) 2008 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.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.google.UnmodifiableCollectionTests; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * Tests for {@link ImmutableMultiset}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class ImmutableMultisetTest extends TestCase { public void testCreation_noArgs() { Multiset<String> multiset = ImmutableMultiset.of(); assertTrue(multiset.isEmpty()); } public void testCreation_oneElement() { Multiset<String> multiset = ImmutableMultiset.of("a"); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCreation_twoElements() { Multiset<String> multiset = ImmutableMultiset.of("a", "b"); assertEquals(HashMultiset.create(asList("a", "b")), multiset); } public void testCreation_threeElements() { Multiset<String> multiset = ImmutableMultiset.of("a", "b", "c"); assertEquals(HashMultiset.create(asList("a", "b", "c")), multiset); } public void testCreation_fourElements() { Multiset<String> multiset = ImmutableMultiset.of("a", "b", "c", "d"); assertEquals(HashMultiset.create(asList("a", "b", "c", "d")), multiset); } public void testCreation_fiveElements() { Multiset<String> multiset = ImmutableMultiset.of("a", "b", "c", "d", "e"); assertEquals(HashMultiset.create(asList("a", "b", "c", "d", "e")), multiset); } public void testCreation_sixElements() { Multiset<String> multiset = ImmutableMultiset.of( "a", "b", "c", "d", "e", "f"); assertEquals(HashMultiset.create(asList("a", "b", "c", "d", "e", "f")), multiset); } public void testCreation_sevenElements() { Multiset<String> multiset = ImmutableMultiset.of( "a", "b", "c", "d", "e", "f", "g"); assertEquals( HashMultiset.create(asList("a", "b", "c", "d", "e", "f", "g")), multiset); } public void testCreation_emptyArray() { String[] array = new String[0]; Multiset<String> multiset = ImmutableMultiset.copyOf(array); assertTrue(multiset.isEmpty()); } public void testCreation_arrayOfOneElement() { String[] array = new String[] { "a" }; Multiset<String> multiset = ImmutableMultiset.copyOf(array); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCreation_arrayOfArray() { String[] array = new String[] { "a" }; Multiset<String[]> multiset = ImmutableMultiset.<String[]>of(array); Multiset<String[]> expected = HashMultiset.create(); expected.add(array); assertEquals(expected, multiset); } public void testCreation_arrayContainingOnlyNull() { String[] array = new String[] { null }; try { ImmutableMultiset.copyOf(array); fail(); } catch (NullPointerException expected) {} } public void testCopyOf_collection_empty() { // "<String>" is required to work around a javac 1.5 bug. Collection<String> c = MinimalCollection.<String>of(); Multiset<String> multiset = ImmutableMultiset.copyOf(c); assertTrue(multiset.isEmpty()); } public void testCopyOf_collection_oneElement() { Collection<String> c = MinimalCollection.of("a"); Multiset<String> multiset = ImmutableMultiset.copyOf(c); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCopyOf_collection_general() { Collection<String> c = MinimalCollection.of("a", "b", "a"); Multiset<String> multiset = ImmutableMultiset.copyOf(c); assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset); } public void testCopyOf_collectionContainingNull() { Collection<String> c = MinimalCollection.of("a", null, "b"); try { ImmutableMultiset.copyOf(c); fail(); } catch (NullPointerException expected) {} } public void testCopyOf_multiset_empty() { Multiset<String> c = HashMultiset.create(); Multiset<String> multiset = ImmutableMultiset.copyOf(c); assertTrue(multiset.isEmpty()); } public void testCopyOf_multiset_oneElement() { Multiset<String> c = HashMultiset.create(asList("a")); Multiset<String> multiset = ImmutableMultiset.copyOf(c); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCopyOf_multiset_general() { Multiset<String> c = HashMultiset.create(asList("a", "b", "a")); Multiset<String> multiset = ImmutableMultiset.copyOf(c); assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset); } public void testCopyOf_multisetContainingNull() { Multiset<String> c = HashMultiset.create(asList("a", null, "b")); try { ImmutableMultiset.copyOf(c); fail(); } catch (NullPointerException expected) {} } public void testCopyOf_iterator_empty() { Iterator<String> iterator = Iterators.emptyIterator(); Multiset<String> multiset = ImmutableMultiset.copyOf(iterator); assertTrue(multiset.isEmpty()); } public void testCopyOf_iterator_oneElement() { Iterator<String> iterator = Iterators.singletonIterator("a"); Multiset<String> multiset = ImmutableMultiset.copyOf(iterator); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCopyOf_iterator_general() { Iterator<String> iterator = asList("a", "b", "a").iterator(); Multiset<String> multiset = ImmutableMultiset.copyOf(iterator); assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset); } public void testCopyOf_iteratorContainingNull() { Iterator<String> iterator = asList("a", null, "b").iterator(); try { ImmutableMultiset.copyOf(iterator); fail(); } catch (NullPointerException expected) {} } private static class CountingIterable implements Iterable<String> { int count = 0; @Override public Iterator<String> iterator() { count++; return asList("a", "b", "a").iterator(); } } public void testCopyOf_plainIterable() { CountingIterable iterable = new CountingIterable(); Multiset<String> multiset = ImmutableMultiset.copyOf(iterable); assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset); assertEquals(1, iterable.count); } public void testCopyOf_shortcut_empty() { Collection<String> c = ImmutableMultiset.of(); assertSame(c, ImmutableMultiset.copyOf(c)); } public void testCopyOf_shortcut_singleton() { Collection<String> c = ImmutableMultiset.of("a"); assertSame(c, ImmutableMultiset.copyOf(c)); } public void testCopyOf_shortcut_immutableMultiset() { Collection<String> c = ImmutableMultiset.of("a", "b", "c"); assertSame(c, ImmutableMultiset.copyOf(c)); } public void testBuilderAdd() { ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>() .add("a") .add("b") .add("a") .add("c") .build(); assertEquals(HashMultiset.create(asList("a", "b", "a", "c")), multiset); } public void testBuilderAddAll() { List<String> a = asList("a", "b"); List<String> b = asList("c", "d"); ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>() .addAll(a) .addAll(b) .build(); assertEquals(HashMultiset.create(asList("a", "b", "c", "d")), multiset); } public void testBuilderAddAllMultiset() { Multiset<String> a = HashMultiset.create(asList("a", "b", "b")); Multiset<String> b = HashMultiset.create(asList("c", "b")); ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>() .addAll(a) .addAll(b) .build(); assertEquals( HashMultiset.create(asList("a", "b", "b", "b", "c")), multiset); } public void testBuilderAddAllIterator() { Iterator<String> iterator = asList("a", "b", "a", "c").iterator(); ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>() .addAll(iterator) .build(); assertEquals(HashMultiset.create(asList("a", "b", "a", "c")), multiset); } public void testBuilderAddCopies() { ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>() .addCopies("a", 2) .addCopies("b", 3) .addCopies("c", 0) .build(); assertEquals( HashMultiset.create(asList("a", "a", "b", "b", "b")), multiset); } public void testBuilderSetCount() { ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>() .add("a") .setCount("a", 2) .setCount("b", 3) .build(); assertEquals( HashMultiset.create(asList("a", "a", "b", "b", "b")), multiset); } public void testBuilderAddHandlesNullsCorrectly() { ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder(); try { builder.add((String) null); fail("expected NullPointerException"); } catch (NullPointerException expected) {} } public void testBuilderAddAllHandlesNullsCorrectly() { ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder(); try { builder.addAll((Collection<String>) null); fail("expected NullPointerException"); } catch (NullPointerException expected) {} builder = ImmutableMultiset.builder(); List<String> listWithNulls = asList("a", null, "b"); try { builder.addAll(listWithNulls); fail("expected NullPointerException"); } catch (NullPointerException expected) {} builder = ImmutableMultiset.builder(); Multiset<String> multisetWithNull = LinkedHashMultiset.create(asList("a", null, "b")); try { builder.addAll(multisetWithNull); fail("expected NullPointerException"); } catch (NullPointerException expected) {} } public void testBuilderAddCopiesHandlesNullsCorrectly() { ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder(); try { builder.addCopies(null, 2); fail("expected NullPointerException"); } catch (NullPointerException expected) {} } public void testBuilderAddCopiesIllegal() { ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder(); try { builder.addCopies("a", -2); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } public void testBuilderSetCountHandlesNullsCorrectly() { ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder(); try { builder.setCount(null, 2); fail("expected NullPointerException"); } catch (NullPointerException expected) {} } public void testBuilderSetCountIllegal() { ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder(); try { builder.setCount("a", -2); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } public void testEquals_immutableMultiset() { Collection<String> c = ImmutableMultiset.of("a", "b", "a"); assertEquals(c, ImmutableMultiset.of("a", "b", "a")); assertEquals(c, ImmutableMultiset.of("a", "a", "b")); ASSERT.that(c).isNotEqualTo(ImmutableMultiset.of("a", "b")); ASSERT.that(c).isNotEqualTo(ImmutableMultiset.of("a", "b", "c", "d")); } public void testIterationOrder() { Collection<String> c = ImmutableMultiset.of("a", "b", "a"); ASSERT.that(c).has().exactly("a", "a", "b").inOrder(); } public void testMultisetWrites() { Multiset<String> multiset = ImmutableMultiset.of("a", "b", "a"); UnmodifiableCollectionTests.assertMultisetIsUnmodifiable(multiset, "test"); } public void testAsList() { ImmutableMultiset<String> multiset = ImmutableMultiset.of("a", "a", "b", "b", "b"); ImmutableList<String> list = multiset.asList(); assertEquals(ImmutableList.of("a", "a", "b", "b", "b"), list); assertEquals(2, list.indexOf("b")); assertEquals(4, list.lastIndexOf("b")); } public void testEquals() { new EqualsTester() .addEqualityGroup(ImmutableMultiset.of(), ImmutableMultiset.of()) .addEqualityGroup(ImmutableMultiset.of(1), ImmutableMultiset.of(1)) .addEqualityGroup(ImmutableMultiset.of(1, 1), ImmutableMultiset.of(1, 1)) .addEqualityGroup(ImmutableMultiset.of(1, 2, 1), ImmutableMultiset.of(2, 1, 1)) .testEquals(); } }
Java
/* * Copyright (C) 2007 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.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.google.TestStringBiMapGenerator; import junit.framework.TestCase; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Tests for {@link HashBiMap}. * * @author Mike Bostock */ @GwtCompatible(emulated = true) public class HashBiMapTest extends TestCase { public static final class HashBiMapGenerator extends TestStringBiMapGenerator { @Override protected BiMap<String, String> create(Entry<String, String>[] entries) { BiMap<String, String> result = HashBiMap.create(); for (Entry<String, String> entry : entries) { result.put(entry.getKey(), entry.getValue()); } return result; } } public void testMapConstructor() { /* Test with non-empty Map. */ Map<String, String> map = ImmutableMap.of( "canada", "dollar", "chile", "peso", "switzerland", "franc"); HashBiMap<String, String> bimap = HashBiMap.create(map); assertEquals("dollar", bimap.get("canada")); assertEquals("canada", bimap.inverse().get("dollar")); } private static final int N = 1000; public void testBashIt() throws Exception { BiMap<Integer, Integer> bimap = HashBiMap.create(N); BiMap<Integer, Integer> inverse = bimap.inverse(); for (int i = 0; i < N; i++) { assertNull(bimap.put(2 * i, 2 * i + 1)); } for (int i = 0; i < N; i++) { assertEquals(2 * i + 1, (int) bimap.get(2 * i)); } for (int i = 0; i < N; i++) { assertEquals(2 * i, (int) inverse.get(2 * i + 1)); } for (int i = 0; i < N; i++) { int oldValue = bimap.get(2 * i); assertEquals(2 * i + 1, (int) bimap.put(2 * i, oldValue - 2)); } for (int i = 0; i < N; i++) { assertEquals(2 * i - 1, (int) bimap.get(2 * i)); } for (int i = 0; i < N; i++) { assertEquals(2 * i, (int) inverse.get(2 * i - 1)); } Set<Entry<Integer, Integer>> entries = bimap.entrySet(); for (Entry<Integer, Integer> entry : entries) { entry.setValue(entry.getValue() + 2 * N); } for (int i = 0; i < N; i++) { assertEquals(2 * N + 2 * i - 1, (int) bimap.get(2 * i)); } } public void testBiMapEntrySetIteratorRemove() { BiMap<Integer, String> map = HashBiMap.create(); map.put(1, "one"); Set<Map.Entry<Integer, String>> entries = map.entrySet(); Iterator<Map.Entry<Integer, String>> iterator = entries.iterator(); Map.Entry<Integer, String> entry = iterator.next(); entry.setValue("two"); // changes the iterator's current entry value assertEquals("two", map.get(1)); assertEquals(Integer.valueOf(1), map.inverse().get("two")); iterator.remove(); // removes the updated entry assertTrue(map.isEmpty()); } }
Java
/* * Copyright (C) 2008 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.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.MinimalIterable; import junit.framework.TestCase; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Base class for {@link ImmutableSet} and {@link ImmutableSortedSet} tests. * * @author Kevin Bourrillion * @author Jared Levy */ @GwtCompatible(emulated = true) public abstract class AbstractImmutableSetTest extends TestCase { protected abstract Set<String> of(); protected abstract Set<String> of(String e); protected abstract Set<String> of(String e1, String e2); protected abstract Set<String> of(String e1, String e2, String e3); protected abstract Set<String> of(String e1, String e2, String e3, String e4); protected abstract Set<String> of(String e1, String e2, String e3, String e4, String e5); protected abstract Set<String> of(String e1, String e2, String e3, String e4, String e5, String e6, String... rest); protected abstract Set<String> copyOf(String[] elements); protected abstract Set<String> copyOf(Collection<String> elements); protected abstract Set<String> copyOf(Iterable<String> elements); protected abstract Set<String> copyOf(Iterator<String> elements); public void testCreation_noArgs() { Set<String> set = of(); assertEquals(Collections.<String>emptySet(), set); assertSame(of(), set); } public void testCreation_oneElement() { Set<String> set = of("a"); assertEquals(Collections.singleton("a"), set); } public void testCreation_twoElements() { Set<String> set = of("a", "b"); assertEquals(Sets.newHashSet("a", "b"), set); } public void testCreation_threeElements() { Set<String> set = of("a", "b", "c"); assertEquals(Sets.newHashSet("a", "b", "c"), set); } public void testCreation_fourElements() { Set<String> set = of("a", "b", "c", "d"); assertEquals(Sets.newHashSet("a", "b", "c", "d"), set); } public void testCreation_fiveElements() { Set<String> set = of("a", "b", "c", "d", "e"); assertEquals(Sets.newHashSet("a", "b", "c", "d", "e"), set); } public void testCreation_sixElements() { Set<String> set = of("a", "b", "c", "d", "e", "f"); assertEquals(Sets.newHashSet("a", "b", "c", "d", "e", "f"), set); } public void testCreation_sevenElements() { Set<String> set = of("a", "b", "c", "d", "e", "f", "g"); assertEquals(Sets.newHashSet("a", "b", "c", "d", "e", "f", "g"), set); } public void testCreation_eightElements() { Set<String> set = of("a", "b", "c", "d", "e", "f", "g", "h"); assertEquals(Sets.newHashSet("a", "b", "c", "d", "e", "f", "g", "h"), set); } public void testCopyOf_emptyArray() { String[] array = new String[0]; Set<String> set = copyOf(array); assertEquals(Collections.<String>emptySet(), set); assertSame(of(), set); } public void testCopyOf_arrayOfOneElement() { String[] array = new String[] { "a" }; Set<String> set = copyOf(array); assertEquals(Collections.singleton("a"), set); } public void testCopyOf_nullArray() { try { copyOf((String[]) null); fail(); } catch(NullPointerException expected) { } } public void testCopyOf_arrayContainingOnlyNull() { String[] array = new String[] { null }; try { copyOf(array); fail(); } catch (NullPointerException expected) { } } public void testCopyOf_collection_empty() { // "<String>" is required to work around a javac 1.5 bug. Collection<String> c = MinimalCollection.<String>of(); Set<String> set = copyOf(c); assertEquals(Collections.<String>emptySet(), set); assertSame(of(), set); } public void testCopyOf_collection_oneElement() { Collection<String> c = MinimalCollection.of("a"); Set<String> set = copyOf(c); assertEquals(Collections.singleton("a"), set); } public void testCopyOf_collection_oneElementRepeated() { Collection<String> c = MinimalCollection.of("a", "a", "a"); Set<String> set = copyOf(c); assertEquals(Collections.singleton("a"), set); } public void testCopyOf_collection_general() { Collection<String> c = MinimalCollection.of("a", "b", "a"); Set<String> set = copyOf(c); assertEquals(2, set.size()); assertTrue(set.contains("a")); assertTrue(set.contains("b")); } public void testCopyOf_collectionContainingNull() { Collection<String> c = MinimalCollection.of("a", null, "b"); try { copyOf(c); fail(); } catch (NullPointerException expected) { } } public void testCopyOf_iterator_empty() { Iterator<String> iterator = Iterators.emptyIterator(); Set<String> set = copyOf(iterator); assertEquals(Collections.<String>emptySet(), set); assertSame(of(), set); } public void testCopyOf_iterator_oneElement() { Iterator<String> iterator = Iterators.singletonIterator("a"); Set<String> set = copyOf(iterator); assertEquals(Collections.singleton("a"), set); } public void testCopyOf_iterator_oneElementRepeated() { Iterator<String> iterator = Iterators.forArray("a", "a", "a"); Set<String> set = copyOf(iterator); assertEquals(Collections.singleton("a"), set); } public void testCopyOf_iterator_general() { Iterator<String> iterator = Iterators.forArray("a", "b", "a"); Set<String> set = copyOf(iterator); assertEquals(2, set.size()); assertTrue(set.contains("a")); assertTrue(set.contains("b")); } public void testCopyOf_iteratorContainingNull() { Iterator<String> c = Iterators.forArray("a", null, "b"); try { copyOf(c); fail(); } catch (NullPointerException expected) { } } private static class CountingIterable implements Iterable<String> { int count = 0; @Override public Iterator<String> iterator() { count++; return Iterators.forArray("a", "b", "a"); } } public void testCopyOf_plainIterable() { CountingIterable iterable = new CountingIterable(); Set<String> set = copyOf(iterable); assertEquals(2, set.size()); assertTrue(set.contains("a")); assertTrue(set.contains("b")); } public void testCopyOf_plainIterable_iteratesOnce() { CountingIterable iterable = new CountingIterable(); copyOf(iterable); assertEquals(1, iterable.count); } public void testCopyOf_shortcut_empty() { Collection<String> c = of(); assertEquals(Collections.<String>emptySet(), copyOf(c)); assertSame(c, copyOf(c)); } public void testCopyOf_shortcut_singleton() { Collection<String> c = of("a"); assertEquals(Collections.singleton("a"), copyOf(c)); assertSame(c, copyOf(c)); } public void testCopyOf_shortcut_sameType() { Collection<String> c = of("a", "b", "c"); assertSame(c, copyOf(c)); } public void testToString() { Set<String> set = of("a", "b", "c", "d", "e", "f", "g"); assertEquals("[a, b, c, d, e, f, g]", set.toString()); } public void testContainsAll_sameType() { Collection<String> c = of("a", "b", "c"); assertFalse(c.containsAll(of("a", "b", "c", "d"))); assertFalse(c.containsAll(of("a", "d"))); assertTrue(c.containsAll(of("a", "c"))); assertTrue(c.containsAll(of("a", "b", "c"))); } public void testEquals_sameType() { Collection<String> c = of("a", "b", "c"); assertTrue(c.equals(of("a", "b", "c"))); assertFalse(c.equals(of("a", "b", "d"))); } abstract <E extends Comparable<E>> ImmutableSet.Builder<E> builder(); public void testBuilderWithNonDuplicateElements() { ImmutableSet<String> set = this.<String>builder() .add("a") .add("b", "c") .add("d", "e", "f") .add("g", "h", "i", "j") .build(); ASSERT.that(set).has().exactly( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j").inOrder(); } public void testReuseBuilderWithNonDuplicateElements() { ImmutableSet.Builder<String> builder = this.<String>builder() .add("a") .add("b"); ASSERT.that(builder.build()).has().exactly("a", "b").inOrder(); builder.add("c", "d"); ASSERT.that(builder.build()).has().exactly("a", "b", "c", "d").inOrder(); } public void testBuilderWithDuplicateElements() { ImmutableSet<String> set = this.<String>builder() .add("a") .add("a", "a") .add("a", "a", "a") .add("a", "a", "a", "a") .build(); assertTrue(set.contains("a")); assertFalse(set.contains("b")); assertEquals(1, set.size()); } public void testReuseBuilderWithDuplicateElements() { ImmutableSet.Builder<String> builder = this.<String>builder() .add("a") .add("a", "a") .add("b"); ASSERT.that(builder.build()).has().exactly("a", "b").inOrder(); builder.add("a", "b", "c", "c"); ASSERT.that(builder.build()).has().exactly("a", "b", "c").inOrder(); } public void testBuilderAddAll() { List<String> a = asList("a", "b", "c"); List<String> b = asList("c", "d", "e"); ImmutableSet<String> set = this.<String>builder() .addAll(a) .addAll(b) .build(); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e").inOrder(); } static final int LAST_COLOR_ADDED = 0x00BFFF; public void testComplexBuilder() { List<Integer> colorElem = asList(0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF); // javac won't compile this without "this.<Integer>" ImmutableSet.Builder<Integer> webSafeColorsBuilder = this.<Integer>builder(); for (Integer red : colorElem) { for (Integer green : colorElem) { for (Integer blue : colorElem) { webSafeColorsBuilder.add((red << 16) + (green << 8) + blue); } } } ImmutableSet<Integer> webSafeColors = webSafeColorsBuilder.build(); assertEquals(216, webSafeColors.size()); Integer[] webSafeColorArray = webSafeColors.toArray(new Integer[webSafeColors.size()]); assertEquals(0x000000, (int) webSafeColorArray[0]); assertEquals(0x000033, (int) webSafeColorArray[1]); assertEquals(0x000066, (int) webSafeColorArray[2]); assertEquals(0x003300, (int) webSafeColorArray[6]); assertEquals(0x330000, (int) webSafeColorArray[36]); ImmutableSet<Integer> addedColor = webSafeColorsBuilder.add(LAST_COLOR_ADDED).build(); assertEquals( "Modifying the builder should not have changed any already built sets", 216, webSafeColors.size()); assertEquals("the new array should be one bigger than webSafeColors", 217, addedColor.size()); Integer[] appendColorArray = addedColor.toArray(new Integer[addedColor.size()]); assertEquals( getComplexBuilderSetLastElement(), (int) appendColorArray[216]); } abstract int getComplexBuilderSetLastElement(); public void testBuilderAddHandlesNullsCorrectly() { ImmutableSet.Builder<String> builder = this.<String>builder(); try { builder.add((String) null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } builder = this.<String>builder(); try { builder.add((String[]) null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } builder = this.<String>builder(); try { builder.add("a", (String) null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } builder = this.<String>builder(); try { builder.add("a", "b", (String) null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } builder = this.<String>builder(); try { builder.add("a", "b", "c", null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } builder = this.<String>builder(); try { builder.add("a", "b", null, "c"); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } } public void testBuilderAddAllHandlesNullsCorrectly() { ImmutableSet.Builder<String> builder = this.<String>builder(); try { builder.addAll((Iterable<String>) null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } try { builder.addAll((Iterator<String>) null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } builder = this.<String>builder(); List<String> listWithNulls = asList("a", null, "b"); try { builder.addAll(listWithNulls); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } Iterable<String> iterableWithNulls = MinimalIterable.of("a", null, "b"); try { builder.addAll(iterableWithNulls); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } } }
Java
/* * Copyright (C) 2007 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.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.AbstractCollection; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.RandomAccess; import java.util.Set; import java.util.SortedSet; /** * Tests for {@code Constraints}. * * @author Mike Bostock * @author Jared Levy */ @GwtCompatible(emulated = true) public class ConstraintsTest extends TestCase { private static final String TEST_ELEMENT = "test"; private static final class TestElementException extends IllegalArgumentException { private static final long serialVersionUID = 0; } private static final Constraint<String> TEST_CONSTRAINT = new Constraint<String>() { @Override public String checkElement(String element) { if (TEST_ELEMENT.equals(element)) { throw new TestElementException(); } return element; } }; public void testNotNull() { Constraint<? super String> constraint = Constraints.notNull(); assertSame(TEST_ELEMENT, constraint.checkElement(TEST_ELEMENT)); try { constraint.checkElement(null); fail("NullPointerException expected"); } catch (NullPointerException expected) {} assertEquals("Not null", constraint.toString()); } public void testConstrainedCollectionLegal() { Collection<String> collection = Lists.newArrayList("foo", "bar"); Collection<String> constrained = Constraints.constrainedCollection( collection, TEST_CONSTRAINT); collection.add(TEST_ELEMENT); constrained.add("qux"); constrained.addAll(asList("cat", "dog")); /* equals and hashCode aren't defined for Collection */ ASSERT.that(collection).has() .exactly("foo", "bar", TEST_ELEMENT, "qux", "cat", "dog").inOrder(); ASSERT.that(constrained).has() .exactly("foo", "bar", TEST_ELEMENT, "qux", "cat", "dog").inOrder(); } public void testConstrainedCollectionIllegal() { Collection<String> collection = Lists.newArrayList("foo", "bar"); Collection<String> constrained = Constraints.constrainedCollection( collection, TEST_CONSTRAINT); try { constrained.add(TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.addAll(asList("baz", TEST_ELEMENT)); fail("TestElementException expected"); } catch (TestElementException expected) {} ASSERT.that(constrained).has().exactly("foo", "bar").inOrder(); ASSERT.that(collection).has().exactly("foo", "bar").inOrder(); } public void testConstrainedSetLegal() { Set<String> set = Sets.newLinkedHashSet(asList("foo", "bar")); Set<String> constrained = Constraints.constrainedSet(set, TEST_CONSTRAINT); set.add(TEST_ELEMENT); constrained.add("qux"); constrained.addAll(asList("cat", "dog")); assertTrue(set.equals(constrained)); assertTrue(constrained.equals(set)); assertEquals(set.toString(), constrained.toString()); assertEquals(set.hashCode(), constrained.hashCode()); ASSERT.that(set).has().exactly("foo", "bar", TEST_ELEMENT, "qux", "cat", "dog").inOrder(); ASSERT.that(constrained).has() .exactly("foo", "bar", TEST_ELEMENT, "qux", "cat", "dog").inOrder(); } public void testConstrainedSetIllegal() { Set<String> set = Sets.newLinkedHashSet(asList("foo", "bar")); Set<String> constrained = Constraints.constrainedSet(set, TEST_CONSTRAINT); try { constrained.add(TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.addAll(asList("baz", TEST_ELEMENT)); fail("TestElementException expected"); } catch (TestElementException expected) {} ASSERT.that(constrained).has().exactly("foo", "bar").inOrder(); ASSERT.that(set).has().exactly("foo", "bar").inOrder(); } public void testConstrainedSortedSetLegal() { SortedSet<String> sortedSet = Sets.newTreeSet(asList("foo", "bar")); SortedSet<String> constrained = Constraints.constrainedSortedSet( sortedSet, TEST_CONSTRAINT); sortedSet.add(TEST_ELEMENT); constrained.add("qux"); constrained.addAll(asList("cat", "dog")); assertTrue(sortedSet.equals(constrained)); assertTrue(constrained.equals(sortedSet)); assertEquals(sortedSet.toString(), constrained.toString()); assertEquals(sortedSet.hashCode(), constrained.hashCode()); ASSERT.that(sortedSet).has().exactly("bar", "cat", "dog", "foo", "qux", TEST_ELEMENT).inOrder(); ASSERT.that(constrained).has() .exactly("bar", "cat", "dog", "foo", "qux", TEST_ELEMENT).inOrder(); assertNull(constrained.comparator()); assertEquals("bar", constrained.first()); assertEquals(TEST_ELEMENT, constrained.last()); } public void testConstrainedSortedSetIllegal() { SortedSet<String> sortedSet = Sets.newTreeSet(asList("foo", "bar")); SortedSet<String> constrained = Constraints.constrainedSortedSet( sortedSet, TEST_CONSTRAINT); try { constrained.add(TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.subSet("bar", "foo").add(TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.headSet("bar").add(TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.tailSet("foo").add(TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.addAll(asList("baz", TEST_ELEMENT)); fail("TestElementException expected"); } catch (TestElementException expected) {} ASSERT.that(constrained).has().exactly("bar", "foo").inOrder(); ASSERT.that(sortedSet).has().exactly("bar", "foo").inOrder(); } public void testConstrainedListLegal() { List<String> list = Lists.newArrayList("foo", "bar"); List<String> constrained = Constraints.constrainedList( list, TEST_CONSTRAINT); list.add(TEST_ELEMENT); constrained.add("qux"); constrained.addAll(asList("cat", "dog")); constrained.add(1, "cow"); constrained.addAll(4, asList("box", "fan")); constrained.set(2, "baz"); assertTrue(list.equals(constrained)); assertTrue(constrained.equals(list)); assertEquals(list.toString(), constrained.toString()); assertEquals(list.hashCode(), constrained.hashCode()); ASSERT.that(list).has().exactly( "foo", "cow", "baz", TEST_ELEMENT, "box", "fan", "qux", "cat", "dog").inOrder(); ASSERT.that(constrained).has().exactly( "foo", "cow", "baz", TEST_ELEMENT, "box", "fan", "qux", "cat", "dog").inOrder(); ListIterator<String> iterator = constrained.listIterator(); iterator.next(); iterator.set("sun"); constrained.listIterator(2).add("sky"); ASSERT.that(list).has().exactly( "sun", "cow", "sky", "baz", TEST_ELEMENT, "box", "fan", "qux", "cat", "dog").inOrder(); ASSERT.that(constrained).has().exactly( "sun", "cow", "sky", "baz", TEST_ELEMENT, "box", "fan", "qux", "cat", "dog").inOrder(); assertTrue(constrained instanceof RandomAccess); } public void testConstrainedListRandomAccessFalse() { List<String> list = Lists.newLinkedList(asList("foo", "bar")); List<String> constrained = Constraints.constrainedList( list, TEST_CONSTRAINT); list.add(TEST_ELEMENT); constrained.add("qux"); assertFalse(constrained instanceof RandomAccess); } public void testConstrainedListIllegal() { List<String> list = Lists.newArrayList("foo", "bar"); List<String> constrained = Constraints.constrainedList( list, TEST_CONSTRAINT); try { constrained.add(TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.listIterator().add(TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.listIterator(1).add(TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.listIterator().set(TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.listIterator(1).set(TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.subList(0, 1).add(TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.add(1, TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.set(1, TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.addAll(asList("baz", TEST_ELEMENT)); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.addAll(1, asList("baz", TEST_ELEMENT)); fail("TestElementException expected"); } catch (TestElementException expected) {} ASSERT.that(constrained).has().exactly("foo", "bar").inOrder(); ASSERT.that(list).has().exactly("foo", "bar").inOrder(); } public void testConstrainedMultisetLegal() { Multiset<String> multiset = HashMultiset.create(asList("foo", "bar")); Multiset<String> constrained = Constraints.constrainedMultiset( multiset, TEST_CONSTRAINT); multiset.add(TEST_ELEMENT); constrained.add("qux"); constrained.addAll(asList("cat", "dog")); constrained.add("cow", 2); assertTrue(multiset.equals(constrained)); assertTrue(constrained.equals(multiset)); assertEquals(multiset.toString(), constrained.toString()); assertEquals(multiset.hashCode(), constrained.hashCode()); ASSERT.that(multiset).has().exactly( "foo", "bar", TEST_ELEMENT, "qux", "cat", "dog", "cow", "cow"); ASSERT.that(constrained).has().exactly( "foo", "bar", TEST_ELEMENT, "qux", "cat", "dog", "cow", "cow"); assertEquals(1, constrained.count("foo")); assertEquals(1, constrained.remove("foo", 3)); assertEquals(2, constrained.setCount("cow", 0)); ASSERT.that(multiset).has().exactly("bar", TEST_ELEMENT, "qux", "cat", "dog"); ASSERT.that(constrained).has().exactly("bar", TEST_ELEMENT, "qux", "cat", "dog"); } public void testConstrainedMultisetIllegal() { Multiset<String> multiset = HashMultiset.create(asList("foo", "bar")); Multiset<String> constrained = Constraints.constrainedMultiset( multiset, TEST_CONSTRAINT); try { constrained.add(TEST_ELEMENT); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.add(TEST_ELEMENT, 2); fail("TestElementException expected"); } catch (TestElementException expected) {} try { constrained.addAll(asList("baz", TEST_ELEMENT)); fail("TestElementException expected"); } catch (TestElementException expected) {} ASSERT.that(constrained).has().exactly("foo", "bar"); ASSERT.that(multiset).has().exactly("foo", "bar"); } public void testNefariousAddAll() { List<String> list = Lists.newArrayList("foo", "bar"); List<String> constrained = Constraints.constrainedList( list, TEST_CONSTRAINT); Collection<String> onceIterable = onceIterableCollection("baz"); constrained.addAll(onceIterable); ASSERT.that(constrained).has().exactly("foo", "bar", "baz").inOrder(); ASSERT.that(list).has().exactly("foo", "bar", "baz").inOrder(); } /** * Returns a "nefarious" collection, which permits only one call to * iterator(). This verifies that the constrained collection uses a defensive * copy instead of potentially checking the elements in one snapshot and * adding the elements from another. * * @param element the element to be contained in the collection */ static <E> Collection<E> onceIterableCollection(final E element) { return new AbstractCollection<E>() { boolean iteratorCalled; @Override public int size() { /* * We could make the collection empty, but that seems more likely to * trigger special cases (so maybe we should test both empty and * nonempty...). */ return 1; } @Override public Iterator<E> iterator() { assertFalse("Expected only one call to iterator()", iteratorCalled); iteratorCalled = true; return Collections.singleton(element).iterator(); } }; } }
Java
/* * Copyright (C) 2007 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.collect; import static java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AnEnum; import com.google.common.collect.testing.google.TestEnumMultisetGenerator; import junit.framework.TestCase; import java.util.Collection; import java.util.EnumSet; import java.util.Set; /** * Tests for an {@link EnumMultiset}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class EnumMultisetTest extends TestCase { private static TestEnumMultisetGenerator enumMultisetGenerator() { return new TestEnumMultisetGenerator() { @Override protected Multiset<AnEnum> create(AnEnum[] elements) { return (elements.length == 0) ? EnumMultiset.create(AnEnum.class) : EnumMultiset.create(asList(elements)); } }; } private static enum Color { BLUE, RED, YELLOW, GREEN, WHITE } public void testClassCreate() { Multiset<Color> ms = EnumMultiset.create(Color.class); ms.add(Color.RED); ms.add(Color.YELLOW); ms.add(Color.RED); assertEquals(0, ms.count(Color.BLUE)); assertEquals(1, ms.count(Color.YELLOW)); assertEquals(2, ms.count(Color.RED)); } public void testCollectionCreate() { Multiset<Color> ms = EnumMultiset.create( asList(Color.RED, Color.YELLOW, Color.RED)); assertEquals(0, ms.count(Color.BLUE)); assertEquals(1, ms.count(Color.YELLOW)); assertEquals(2, ms.count(Color.RED)); } public void testIllegalCreate() { Collection<Color> empty = EnumSet.noneOf(Color.class); try { EnumMultiset.create(empty); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateEmptyWithClass() { Multiset<Color> ms = EnumMultiset.create(ImmutableList.<Color>of(), Color.class); ms.add(Color.RED); } public void testCreateEmptyWithoutClassFails() { try { Multiset<Color> ms = EnumMultiset.create(ImmutableList.<Color> of()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testToString() { Multiset<Color> ms = EnumMultiset.create(Color.class); ms.add(Color.BLUE, 3); ms.add(Color.YELLOW, 1); ms.add(Color.RED, 2); assertEquals("[BLUE x 3, RED x 2, YELLOW]", ms.toString()); } public void testEntrySet() { Multiset<Color> ms = EnumMultiset.create(Color.class); ms.add(Color.BLUE, 3); ms.add(Color.YELLOW, 1); ms.add(Color.RED, 2); Set<Object> uniqueEntries = Sets.newIdentityHashSet(); uniqueEntries.addAll(ms.entrySet()); assertEquals(3, uniqueEntries.size()); } }
Java
/* * Copyright (C) 2008 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.testing; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.EnumSet; import java.util.concurrent.TimeUnit; /** * Unit test for {@link FakeTicker}. * * @author Jige Yu */ @GwtCompatible(emulated = true) public class FakeTickerTest extends TestCase { public void testAdvance() { FakeTicker ticker = new FakeTicker(); assertEquals(0, ticker.read()); assertSame(ticker, ticker.advance(10)); assertEquals(10, ticker.read()); ticker.advance(1, TimeUnit.MILLISECONDS); assertEquals(1000010L, ticker.read()); } public void testAutoIncrementStep_returnsSameInstance() { FakeTicker ticker = new FakeTicker(); assertSame(ticker, ticker.setAutoIncrementStep(10, TimeUnit.NANOSECONDS)); } public void testAutoIncrementStep_nanos() { FakeTicker ticker = new FakeTicker().setAutoIncrementStep(10, TimeUnit.NANOSECONDS); assertEquals(0, ticker.read()); assertEquals(10, ticker.read()); assertEquals(20, ticker.read()); } public void testAutoIncrementStep_millis() { FakeTicker ticker = new FakeTicker().setAutoIncrementStep(1, TimeUnit.MILLISECONDS); assertEquals(0, ticker.read()); assertEquals(1000000, ticker.read()); assertEquals(2000000, ticker.read()); } public void testAutoIncrementStep_seconds() { FakeTicker ticker = new FakeTicker().setAutoIncrementStep(3, TimeUnit.SECONDS); assertEquals(0, ticker.read()); assertEquals(3000000000L, ticker.read()); assertEquals(6000000000L, ticker.read()); } public void testAutoIncrementStep_resetToZero() { FakeTicker ticker = new FakeTicker().setAutoIncrementStep(10, TimeUnit.NANOSECONDS); assertEquals(0, ticker.read()); assertEquals(10, ticker.read()); assertEquals(20, ticker.read()); for (TimeUnit timeUnit : EnumSet.allOf(TimeUnit.class)) { ticker.setAutoIncrementStep(0, timeUnit); assertEquals( "Expected no auto-increment when setting autoIncrementStep to 0 " + timeUnit, 30, ticker.read()); } } public void testAutoIncrement_negative() { FakeTicker ticker = new FakeTicker(); try { ticker.setAutoIncrementStep(-1, TimeUnit.NANOSECONDS); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } }
Java
/* * Copyright (C) 2011 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.testing; import static com.google.common.base.Preconditions.checkNotNull; /** * Methods factored out so that they can be emulated differently in GWT. * * @author Chris Povirk */ final class Platform { /** * Serializes and deserializes the specified object (a no-op under GWT). */ @SuppressWarnings("unchecked") static <T> T reserialize(T object) { return checkNotNull(object); } private Platform() {} }
Java