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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.NoSuchElementException; /** * A generic JUnit test which tests {@code remove()} operations on a queue. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Jared Levy */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" public class QueueRemoveTester<E> extends AbstractQueueTester<E> { @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testRemove_empty() { try { getQueue().remove(); fail("emptyQueue.remove() should throw"); } catch (NoSuchElementException expected) {} expectUnchanged(); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ONE) public void testRemove_size1() { assertEquals("size1Queue.remove() should return first element", samples.e0, getQueue().remove()); expectMissing(samples.e0); } @CollectionFeature.Require({KNOWN_ORDER, SUPPORTS_REMOVE}) @CollectionSize.Require(SEVERAL) public void testRemove_sizeMany() { assertEquals("sizeManyQueue.remove() should return first element", samples.e0, getQueue().remove()); expectMissing(samples.e0); } }
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.testers; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.testing.SerializableTester; /** * Basic reserialization test for collection types that must preserve {@code equals()} behavior * when reserialized. (Sets and Lists, but not bare Collections.) * * @author Louis Wasserman */ public class CollectionSerializationEqualTester<E> extends AbstractCollectionTester<E> { @CollectionFeature.Require(SERIALIZABLE) public void testReserialize() { assertEquals( actualContents(), SerializableTester.reserialize(actualContents())); } }
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.collect.testing.Helpers; import com.google.common.collect.testing.MinimalSet; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.Collection; import java.util.Set; /** * Tests {@link java.util.Set#equals}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ public class SetEqualsTester<E> extends AbstractSetTester<E> { public void testEquals_otherSetWithSameElements() { assertTrue( "A Set should equal any other Set containing the same elements.", getSet().equals(MinimalSet.from(getSampleElements()))); } @CollectionSize.Require(absent = CollectionSize.ZERO) public void testEquals_otherSetWithDifferentElements() { Collection<E> elements = getSampleElements(getNumElements() - 1); elements.add(getSubjectGenerator().samples().e3); assertFalse( "A Set should not equal another Set containing different elements.", getSet().equals(MinimalSet.from(elements)) ); } @CollectionSize.Require(absent = CollectionSize.ZERO) @CollectionFeature.Require(ALLOWS_NULL_VALUES) public void testEquals_containingNull() { Collection<E> elements = getSampleElements(getNumElements() - 1); elements.add(null); collection = getSubjectGenerator().create(elements.toArray()); assertTrue("A Set should equal any other Set containing the same elements," + " even if some elements are null.", getSet().equals(MinimalSet.from(elements))); } @CollectionSize.Require(absent = CollectionSize.ZERO) public void testEquals_otherContainsNull() { Collection<E> elements = getSampleElements(getNumElements() - 1); elements.add(null); Set<E> other = MinimalSet.from(elements); assertFalse( "Two Sets should not be equal if exactly one of them contains null.", getSet().equals(other)); } @CollectionSize.Require(absent = CollectionSize.ZERO) public void testEquals_smallerSet() { Collection<E> fewerElements = getSampleElements(getNumElements() - 1); assertFalse("Sets of different sizes should not be equal.", getSet().equals(MinimalSet.from(fewerElements))); } public void testEquals_largerSet() { Collection<E> moreElements = getSampleElements(getNumElements() + 1); assertFalse("Sets of different sizes should not be equal.", getSet().equals(MinimalSet.from(moreElements))); } public void testEquals_list() { assertFalse("A List should never equal a Set.", getSet().equals(Helpers.copyToList(getSet()))); } }
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_QUERIES; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; /** * A generic JUnit test which tests {@code get} operations on a map. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion * @author Chris Povirk */ public class MapGetTester<K, V> extends AbstractMapTester<K, V> { @CollectionSize.Require(absent = ZERO) public void testGet_yes() { assertEquals("get(present) should return the associated value", samples.e0.getValue(), get(samples.e0.getKey())); } public void testGet_no() { assertNull("get(notPresent) should return null", get(samples.e3.getKey())); } @CollectionFeature.Require(ALLOWS_NULL_QUERIES) public void testGet_nullNotContainedButAllowed() { assertNull("get(null) should return null", get(null)); } @CollectionFeature.Require(absent = ALLOWS_NULL_QUERIES) public void testGet_nullNotContainedAndUnsupported() { try { assertNull("get(null) should return null or throw", get(null)); } catch (NullPointerException tolerated) { } } @MapFeature.Require(ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testGet_nonNullWhenNullContained() { initMapWithNullKey(); assertNull("get(notPresent) should return null", get(samples.e3.getKey())); } @MapFeature.Require(ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testGet_nullContained() { initMapWithNullKey(); assertEquals("get(null) should return the associated value", getValueForNullKey(), get(null)); } public void testGet_wrongType() { try { assertNull("get(wrongType) should return null or throw", getMap().get(WrongType.VALUE)); } catch (ClassCastException tolerated) { } } }
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.REJECTS_DUPLICATES_AT_CREATION; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; 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 list. Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ public class ListCreationTester<E> extends AbstractListTester<E> { @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates() { E[] array = createSamplesArray(); array[1] = samples.e0; collection = getSubjectGenerator().create(array); expectContents(array); } }
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.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_REMOVE_WITH_INDEX; 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 java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; /** * A generic JUnit test which tests {@code remove(int)} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ public class ListRemoveAtIndexTester<E> extends AbstractListTester<E> { @ListFeature.Require(absent = SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testRemoveAtIndex_unsupported() { try { getList().remove(0); fail("remove(i) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) public void testRemoveAtIndex_negative() { try { getList().remove(-1); fail("remove(-1) should throw"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) public void testRemoveAtIndex_tooLarge() { try { getList().remove(getNumElements()); fail("remove(size) should throw"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testRemoveAtIndex_first() { runRemoveTest(0); } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = {ZERO, ONE}) public void testRemoveAtIndex_middle() { runRemoveTest(getNumElements() / 2); } @CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION) @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testRemoveAtIndexConcurrentWithIteration() { try { Iterator<E> iterator = collection.iterator(); getList().remove(getNumElements() / 2); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testRemoveAtIndex_last() { runRemoveTest(getNumElements() - 1); } private void runRemoveTest(int index) { assertEquals(Platform.format( "remove(%d) should return the element at index %d", index, index), getList().get(index), getList().remove(index)); List<E> expected = Helpers.copyToList(createSamplesArray()); expected.remove(index); expectContents(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 com.google.common.collect.testing.AbstractMapTester; /** * A generic JUnit test which tests {@code size()} operations on a map. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ public class MapSizeTester<K, V> extends AbstractMapTester<K, V> { public void testSize() { assertEquals("size():", getNumElements(), getMap().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.testing.testers; 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 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.Collection; import java.util.Map; /** * Tests {@link java.util.Map#hashCode}. * * <p>This class is GWT compatible. * * @author George van den Driessche * @author Chris Povirk */ public class MapHashCodeTester<K, V> extends AbstractMapTester<K, V> { public void testHashCode() { int expectedHashCode = 0; for (Map.Entry<K, V> entry : getSampleEntries()) { expectedHashCode += hash(entry); } assertEquals( "A Map's hashCode() should be the sum of those of its entries.", expectedHashCode, getMap().hashCode()); } @CollectionSize.Require(absent = CollectionSize.ZERO) @MapFeature.Require(ALLOWS_NULL_KEYS) public void testHashCode_containingNullKey() { Map.Entry<K, V> entryWithNull = entry(null, samples.e3.getValue()); runEntryWithNullTest(entryWithNull); } @CollectionSize.Require(absent = CollectionSize.ZERO) @MapFeature.Require(ALLOWS_NULL_VALUES) public void testHashCode_containingNullValue() { Map.Entry<K, V> entryWithNull = entry(samples.e3.getKey(), null); runEntryWithNullTest(entryWithNull); } private void runEntryWithNullTest(Map.Entry<K, V> entryWithNull) { Collection<Map.Entry<K, V>> entries = getSampleEntries(getNumEntries() - 1); entries.add(entryWithNull); int expectedHashCode = 0; for (Map.Entry<K, V> entry : entries) { expectedHashCode += hash(entry); } resetContainer(getSubjectGenerator().create(entries.toArray())); assertEquals( "A Map's hashCode() should be the sum of those of its entries (where " + "a null element in an entry counts as having a hash of zero).", expectedHashCode, getMap().hashCode()); } private static int hash(Map.Entry<?, ?> e) { return (e.getKey() == null ? 0 : e.getKey().hashCode()) ^ (e.getValue() == null ? 0 : e.getValue().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.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code peek()} operations on a queue. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Jared Levy */ public class QueuePeekTester<E> extends AbstractQueueTester<E> { @CollectionSize.Require(ZERO) public void testPeek_empty() { assertNull("emptyQueue.peek() should return null", getQueue().peek()); expectUnchanged(); } @CollectionSize.Require(ONE) public void testPeek_size1() { assertEquals("size1Queue.peek() should return first element", samples.e0, getQueue().peek()); expectUnchanged(); } @CollectionFeature.Require(KNOWN_ORDER) @CollectionSize.Require(SEVERAL) public void testPeek_sizeMany() { assertEquals("sizeManyQueue.peek() should return first element", samples.e0, getQueue().peek()); expectUnchanged(); } }
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 java.lang.reflect.Method; /** * Tests {@link java.util.List#hashCode}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ public class ListHashCodeTester<E> extends AbstractListTester<E> { public void testHashCode() { int expectedHashCode = 1; for (E element : getSampleElements()) { expectedHashCode = 31 * expectedHashCode + ((element == null) ? 0 : element.hashCode()); } assertEquals( "A List's hashCode() should be computed from those of its elements.", expectedHashCode, getList().hashCode()); } /** * Returns the {@link Method} instance for {@link #testHashCode()} so that * list tests on unhashable objects can suppress it with * {@code FeatureSpecificTestSuiteBuilder.suppressing()}. */ public static Method getHashCodeMethod() { return Platform.getMethod(ListHashCodeTester.class, "testHashCode"); } }
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.CollectionFeature.NON_STANDARD_TOSTRING; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code toString()} operations on a * collection. Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ public class CollectionToStringTester<E> extends AbstractCollectionTester<E> { public void testToString_minimal() { assertNotNull("toString() should not return null", collection.toString()); } @CollectionSize.Require(ZERO) @CollectionFeature.Require(absent = NON_STANDARD_TOSTRING) public void testToString_size0() { assertEquals("emptyCollection.toString should return []", "[]", collection.toString()); } @CollectionSize.Require(ONE) @CollectionFeature.Require(absent = NON_STANDARD_TOSTRING) public void testToString_size1() { assertEquals("size1Collection.toString should return [{element}]", "[" + samples.e0 + "]", collection.toString()); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require( value = KNOWN_ORDER, absent = NON_STANDARD_TOSTRING) public void testToString_sizeSeveral() { String expected = Helpers.copyToList(getOrderedElements()).toString(); assertEquals("collection.toString() incorrect", expected, collection.toString()); } }
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; /** * A generic JUnit test which tests {@code get()} operations on a list. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ public class ListGetTester<E> extends AbstractListTester<E> { public void testGet_valid() { // This calls get() on each index and checks the result: expectContents(createSamplesArray()); } public void testGet_negative() { try { getList().get(-1); fail("get(-1) should throw"); } catch (IndexOutOfBoundsException expected) { } } public void testGet_tooLarge() { try { getList().get(getNumElements()); fail("get(size) should throw"); } 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.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code lastIndexOf()} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ public class ListLastIndexOfTester<E> extends AbstractListIndexOfTester<E> { @Override protected int find(Object o) { return getList().lastIndexOf(o); } @Override protected String getMethodName() { return "lastIndexOf"; } @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testLastIndexOf_duplicate() { E[] array = createSamplesArray(); array[getNumElements() / 2] = samples.e0; collection = getSubjectGenerator().create(array); assertEquals( "lastIndexOf(duplicate) should return index of last occurrence", getNumElements() / 2, getList().lastIndexOf(samples.e0)); } }
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; /** * A non-empty tester for {@link java.util.Iterator}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ public final class ExampleIteratorTester<E> extends AbstractTester<TestIteratorGenerator<E>> { public void testSomethingAboutIterators() { assertTrue(true); } }
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.testing; /** * Simple derived class to verify that we handle generics correctly. * * @author Kevin Bourrillion */ public class DerivedComparable extends BaseComparable { public DerivedComparable(String s) { super(s); } 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.testing; import com.google.common.collect.testing.SampleElements.Strings; import java.util.List; /** * TODO: javadoc. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ public abstract class TestStringListGenerator implements TestListGenerator<String> { @Override public SampleElements<String> samples() { return new Strings(); } @Override public List<String> create(Object... elements) { String[] array = new String[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (String) e; } return create(array); } /** * Creates a new collection containing the given elements; implement this * method instead of {@link #create(Object...)}. */ protected abstract List<String> create(String[] elements); @Override public String[] createArray(int length) { return new String[length]; } /** Returns the original element list, unchanged. */ @Override public List<String> order(List<String> insertionOrder) { return insertionOrder; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import static com.google.common.collect.testing.Helpers.copyToList; 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.ONE; 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.BoundType; import com.google.common.collect.Iterators; import com.google.common.collect.Multiset; import com.google.common.collect.Multiset.Entry; import com.google.common.collect.Multisets; import com.google.common.collect.SortedMultiset; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; /** * Tester for navigation of SortedMultisets. * * @author Louis Wasserman */ @GwtCompatible public class MultisetNavigationTester<E> extends AbstractMultisetTester<E> { private SortedMultiset<E> sortedMultiset; private List<E> entries; private Entry<E> a; private Entry<E> b; private Entry<E> c; /** * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ static <T> SortedMultiset<T> cast(Multiset<T> iterable) { return (SortedMultiset<T>) iterable; } @Override public void setUp() throws Exception { super.setUp(); sortedMultiset = cast(getMultiset()); entries = copyToList(getSubjectGenerator().getSampleElements( getSubjectGenerator().getCollectionSize().getNumElements())); Collections.sort(entries, sortedMultiset.comparator()); // some tests assume SEVERAL == 3 if (entries.size() >= 1) { a = Multisets.immutableEntry(entries.get(0), sortedMultiset.count(entries.get(0))); if (entries.size() >= 3) { b = Multisets.immutableEntry(entries.get(1), sortedMultiset.count(entries.get(1))); c = Multisets.immutableEntry(entries.get(2), sortedMultiset.count(entries.get(2))); } } } /** * Resets the contents of sortedMultiset to have entries a, c, for the navigation tests. */ @SuppressWarnings("unchecked") // Needed to stop Eclipse whining private void resetWithHole() { List<E> container = new ArrayList<E>(); container.addAll(Collections.nCopies(a.getCount(), a.getElement())); container.addAll(Collections.nCopies(c.getCount(), c.getElement())); super.resetContainer(getSubjectGenerator().create(container.toArray())); sortedMultiset = (SortedMultiset<E>) getMultiset(); } @CollectionSize.Require(ZERO) public void testEmptyMultisetFirst() { assertNull(sortedMultiset.firstEntry()); try { sortedMultiset.elementSet().first(); fail(); } catch (NoSuchElementException e) {} } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testEmptyMultisetPollFirst() { assertNull(sortedMultiset.pollFirstEntry()); } @CollectionSize.Require(ZERO) public void testEmptyMultisetNearby() { for (BoundType type : BoundType.values()) { assertNull(sortedMultiset.headMultiset(samples.e0, type).lastEntry()); assertNull(sortedMultiset.tailMultiset(samples.e0, type).firstEntry()); } } @CollectionSize.Require(ZERO) public void testEmptyMultisetLast() { assertNull(sortedMultiset.lastEntry()); try { assertNull(sortedMultiset.elementSet().last()); fail(); } catch (NoSuchElementException e) {} } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testEmptyMultisetPollLast() { assertNull(sortedMultiset.pollLastEntry()); } @CollectionSize.Require(ONE) public void testSingletonMultisetFirst() { assertEquals(a, sortedMultiset.firstEntry()); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ONE) public void testSingletonMultisetPollFirst() { assertEquals(a, sortedMultiset.pollFirstEntry()); assertTrue(sortedMultiset.isEmpty()); } @CollectionSize.Require(ONE) public void testSingletonMultisetNearby() { assertNull(sortedMultiset.headMultiset(samples.e0, OPEN).lastEntry()); assertNull(sortedMultiset.tailMultiset(samples.e0, OPEN).lastEntry()); assertEquals(a, sortedMultiset.headMultiset(samples.e0, CLOSED).lastEntry()); assertEquals(a, sortedMultiset.tailMultiset(samples.e0, CLOSED).firstEntry()); } @CollectionSize.Require(ONE) public void testSingletonMultisetLast() { assertEquals(a, sortedMultiset.lastEntry()); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ONE) public void testSingletonMultisetPollLast() { assertEquals(a, sortedMultiset.pollLastEntry()); assertTrue(sortedMultiset.isEmpty()); } @CollectionSize.Require(SEVERAL) public void testFirst() { assertEquals(a, sortedMultiset.firstEntry()); } @SuppressWarnings("unchecked") @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(SEVERAL) public void testPollFirst() { assertEquals(a, sortedMultiset.pollFirstEntry()); assertEquals(Arrays.asList(b, c), copyToList(sortedMultiset.entrySet())); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testPollFirstUnsupported() { try { sortedMultiset.pollFirstEntry(); fail(); } catch (UnsupportedOperationException e) {} } @CollectionSize.Require(SEVERAL) public void testLower() { resetWithHole(); assertEquals(null, sortedMultiset.headMultiset(a.getElement(), OPEN).lastEntry()); assertEquals(a, sortedMultiset.headMultiset(b.getElement(), OPEN).lastEntry()); assertEquals(a, sortedMultiset.headMultiset(c.getElement(), OPEN).lastEntry()); } @CollectionSize.Require(SEVERAL) public void testFloor() { resetWithHole(); assertEquals(a, sortedMultiset.headMultiset(a.getElement(), CLOSED).lastEntry()); assertEquals(a, sortedMultiset.headMultiset(b.getElement(), CLOSED).lastEntry()); assertEquals(c, sortedMultiset.headMultiset(c.getElement(), CLOSED).lastEntry()); } @CollectionSize.Require(SEVERAL) public void testCeiling() { resetWithHole(); assertEquals(a, sortedMultiset.tailMultiset(a.getElement(), CLOSED).firstEntry()); assertEquals(c, sortedMultiset.tailMultiset(b.getElement(), CLOSED).firstEntry()); assertEquals(c, sortedMultiset.tailMultiset(c.getElement(), CLOSED).firstEntry()); } @CollectionSize.Require(SEVERAL) public void testHigher() { resetWithHole(); assertEquals(c, sortedMultiset.tailMultiset(a.getElement(), OPEN).firstEntry()); assertEquals(c, sortedMultiset.tailMultiset(b.getElement(), OPEN).firstEntry()); assertEquals(null, sortedMultiset.tailMultiset(c.getElement(), OPEN).firstEntry()); } @CollectionSize.Require(SEVERAL) public void testLast() { assertEquals(c, sortedMultiset.lastEntry()); } @SuppressWarnings("unchecked") @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(SEVERAL) public void testPollLast() { assertEquals(c, sortedMultiset.pollLastEntry()); assertEquals(Arrays.asList(a, b), copyToList(sortedMultiset.entrySet())); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(SEVERAL) public void testPollLastUnsupported() { try { sortedMultiset.pollLastEntry(); fail(); } catch (UnsupportedOperationException e) {} } @CollectionSize.Require(SEVERAL) public void testDescendingNavigation() { List<Entry<E>> ascending = new ArrayList<Entry<E>>(); Iterators.addAll(ascending, sortedMultiset.entrySet().iterator()); List<Entry<E>> descending = new ArrayList<Entry<E>>(); Iterators.addAll(descending, sortedMultiset.descendingMultiset().entrySet().iterator()); Collections.reverse(descending); assertEquals(ascending, descending); } void expectAddFailure(SortedMultiset<E> multiset, Entry<E> entry) { try { multiset.add(entry.getElement(), entry.getCount()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} try { multiset.add(entry.getElement()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} try { multiset.addAll(Collections.singletonList(entry.getElement())); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } void expectRemoveZero(SortedMultiset<E> multiset, Entry<E> entry) { assertEquals(0, multiset.remove(entry.getElement(), entry.getCount())); assertFalse(multiset.remove(entry.getElement())); assertFalse(multiset.elementSet().remove(entry.getElement())); } void expectSetCountFailure(SortedMultiset<E> multiset, Entry<E> entry) { try { multiset.setCount(entry.getElement(), multiset.count(entry.getElement())); } catch (IllegalArgumentException acceptable) {} try { multiset.setCount(entry.getElement(), multiset.count(entry.getElement()) + 1); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } @CollectionSize.Require(ONE) @CollectionFeature.Require(SUPPORTS_ADD) public void testAddOutOfTailBoundsOne() { expectAddFailure(sortedMultiset.tailMultiset(a.getElement(), OPEN), a); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_ADD) public void testAddOutOfTailBoundsSeveral() { expectAddFailure(sortedMultiset.tailMultiset(a.getElement(), OPEN), a); expectAddFailure(sortedMultiset.tailMultiset(b.getElement(), CLOSED), a); expectAddFailure(sortedMultiset.tailMultiset(b.getElement(), OPEN), a); expectAddFailure(sortedMultiset.tailMultiset(b.getElement(), OPEN), b); expectAddFailure(sortedMultiset.tailMultiset(c.getElement(), CLOSED), a); expectAddFailure(sortedMultiset.tailMultiset(c.getElement(), CLOSED), b); expectAddFailure(sortedMultiset.tailMultiset(c.getElement(), OPEN), a); expectAddFailure(sortedMultiset.tailMultiset(c.getElement(), OPEN), b); expectAddFailure(sortedMultiset.tailMultiset(c.getElement(), OPEN), c); } @CollectionSize.Require(ONE) @CollectionFeature.Require(SUPPORTS_ADD) public void testAddOutOfHeadBoundsOne() { expectAddFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), a); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_ADD) public void testAddOutOfHeadBoundsSeveral() { expectAddFailure(sortedMultiset.headMultiset(c.getElement(), OPEN), c); expectAddFailure(sortedMultiset.headMultiset(b.getElement(), CLOSED), c); expectAddFailure(sortedMultiset.headMultiset(b.getElement(), OPEN), c); expectAddFailure(sortedMultiset.headMultiset(b.getElement(), OPEN), b); expectAddFailure(sortedMultiset.headMultiset(a.getElement(), CLOSED), c); expectAddFailure(sortedMultiset.headMultiset(a.getElement(), CLOSED), b); expectAddFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), c); expectAddFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), b); expectAddFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), a); } @CollectionSize.Require(ONE) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemoveOutOfTailBoundsOne() { expectRemoveZero(sortedMultiset.tailMultiset(a.getElement(), OPEN), a); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemoveOutOfTailBoundsSeveral() { expectRemoveZero(sortedMultiset.tailMultiset(a.getElement(), OPEN), a); expectRemoveZero(sortedMultiset.tailMultiset(b.getElement(), CLOSED), a); expectRemoveZero(sortedMultiset.tailMultiset(b.getElement(), OPEN), a); expectRemoveZero(sortedMultiset.tailMultiset(b.getElement(), OPEN), b); expectRemoveZero(sortedMultiset.tailMultiset(c.getElement(), CLOSED), a); expectRemoveZero(sortedMultiset.tailMultiset(c.getElement(), CLOSED), b); expectRemoveZero(sortedMultiset.tailMultiset(c.getElement(), OPEN), a); expectRemoveZero(sortedMultiset.tailMultiset(c.getElement(), OPEN), b); expectRemoveZero(sortedMultiset.tailMultiset(c.getElement(), OPEN), c); } @CollectionSize.Require(ONE) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemoveOutOfHeadBoundsOne() { expectRemoveZero(sortedMultiset.headMultiset(a.getElement(), OPEN), a); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemoveOutOfHeadBoundsSeveral() { expectRemoveZero(sortedMultiset.headMultiset(c.getElement(), OPEN), c); expectRemoveZero(sortedMultiset.headMultiset(b.getElement(), CLOSED), c); expectRemoveZero(sortedMultiset.headMultiset(b.getElement(), OPEN), c); expectRemoveZero(sortedMultiset.headMultiset(b.getElement(), OPEN), b); expectRemoveZero(sortedMultiset.headMultiset(a.getElement(), CLOSED), c); expectRemoveZero(sortedMultiset.headMultiset(a.getElement(), CLOSED), b); expectRemoveZero(sortedMultiset.headMultiset(a.getElement(), OPEN), c); expectRemoveZero(sortedMultiset.headMultiset(a.getElement(), OPEN), b); expectRemoveZero(sortedMultiset.headMultiset(a.getElement(), OPEN), a); } @CollectionSize.Require(ONE) @CollectionFeature.Require({SUPPORTS_ADD, SUPPORTS_REMOVE}) public void testSetCountOutOfTailBoundsOne() { expectSetCountFailure(sortedMultiset.tailMultiset(a.getElement(), OPEN), a); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require({SUPPORTS_ADD, SUPPORTS_REMOVE}) public void testSetCountOutOfTailBoundsSeveral() { expectSetCountFailure(sortedMultiset.tailMultiset(a.getElement(), OPEN), a); expectSetCountFailure(sortedMultiset.tailMultiset(b.getElement(), CLOSED), a); expectSetCountFailure(sortedMultiset.tailMultiset(b.getElement(), OPEN), a); expectSetCountFailure(sortedMultiset.tailMultiset(b.getElement(), OPEN), b); expectSetCountFailure(sortedMultiset.tailMultiset(c.getElement(), CLOSED), a); expectSetCountFailure(sortedMultiset.tailMultiset(c.getElement(), CLOSED), b); expectSetCountFailure(sortedMultiset.tailMultiset(c.getElement(), OPEN), a); expectSetCountFailure(sortedMultiset.tailMultiset(c.getElement(), OPEN), b); expectSetCountFailure(sortedMultiset.tailMultiset(c.getElement(), OPEN), c); } @CollectionSize.Require(ONE) @CollectionFeature.Require({SUPPORTS_ADD, SUPPORTS_REMOVE}) public void testSetCountOutOfHeadBoundsOne() { expectSetCountFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), a); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require({SUPPORTS_ADD, SUPPORTS_REMOVE}) public void testSetCountOutOfHeadBoundsSeveral() { expectSetCountFailure(sortedMultiset.headMultiset(c.getElement(), OPEN), c); expectSetCountFailure(sortedMultiset.headMultiset(b.getElement(), CLOSED), c); expectSetCountFailure(sortedMultiset.headMultiset(b.getElement(), OPEN), c); expectSetCountFailure(sortedMultiset.headMultiset(b.getElement(), OPEN), b); expectSetCountFailure(sortedMultiset.headMultiset(a.getElement(), CLOSED), c); expectSetCountFailure(sortedMultiset.headMultiset(a.getElement(), CLOSED), b); expectSetCountFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), c); expectSetCountFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), b); expectSetCountFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), a); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_ADD) public void testAddWithConflictingBounds() { testEmptyRangeSubMultisetSupportingAdd(sortedMultiset.subMultiset(a.getElement(), CLOSED, a.getElement(), OPEN)); testEmptyRangeSubMultisetSupportingAdd(sortedMultiset.subMultiset(a.getElement(), OPEN, a.getElement(), OPEN)); testEmptyRangeSubMultisetSupportingAdd(sortedMultiset.subMultiset(a.getElement(), OPEN, a.getElement(), CLOSED)); testEmptyRangeSubMultisetSupportingAdd(sortedMultiset.subMultiset(b.getElement(), CLOSED, a.getElement(), CLOSED)); testEmptyRangeSubMultisetSupportingAdd(sortedMultiset.subMultiset(b.getElement(), CLOSED, a.getElement(), OPEN)); testEmptyRangeSubMultisetSupportingAdd(sortedMultiset.subMultiset(b.getElement(), OPEN, a.getElement(), OPEN)); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_ADD) public void testConflictingBounds() { testEmptyRangeSubMultiset(sortedMultiset.subMultiset(a.getElement(), CLOSED, a.getElement(), OPEN)); testEmptyRangeSubMultiset(sortedMultiset.subMultiset(a.getElement(), OPEN, a.getElement(), OPEN)); testEmptyRangeSubMultiset(sortedMultiset.subMultiset(a.getElement(), OPEN, a.getElement(), CLOSED)); testEmptyRangeSubMultiset(sortedMultiset.subMultiset(b.getElement(), CLOSED, a.getElement(), CLOSED)); testEmptyRangeSubMultiset(sortedMultiset.subMultiset(b.getElement(), CLOSED, a.getElement(), OPEN)); testEmptyRangeSubMultiset(sortedMultiset.subMultiset(b.getElement(), OPEN, a.getElement(), OPEN)); } public void testEmptyRangeSubMultiset(SortedMultiset<E> multiset) { assertTrue(multiset.isEmpty()); assertEquals(0, multiset.size()); assertEquals(0, multiset.toArray().length); assertTrue(multiset.entrySet().isEmpty()); assertFalse(multiset.iterator().hasNext()); assertEquals(0, multiset.entrySet().size()); assertEquals(0, multiset.entrySet().toArray().length); assertFalse(multiset.entrySet().iterator().hasNext()); } @SuppressWarnings("unchecked") public void testEmptyRangeSubMultisetSupportingAdd(SortedMultiset<E> multiset) { for (Entry<E> entry : Arrays.asList(a, b, c)) { expectAddFailure(multiset, entry); } } private int totalSize(Iterable<? extends Entry<?>> entries) { int sum = 0; for (Entry<?> entry : entries) { sum += entry.getCount(); } return sum; } private enum SubMultisetSpec { TAIL_CLOSED { @Override <E> List<Entry<E>> expectedEntries(int targetEntry, List<Entry<E>> entries) { return entries.subList(targetEntry, entries.size()); } @Override <E> SortedMultiset<E> subMultiset(SortedMultiset<E> multiset, List<Entry<E>> entries, int targetEntry) { return multiset.tailMultiset(entries.get(targetEntry).getElement(), CLOSED); } }, TAIL_OPEN { @Override <E> List<Entry<E>> expectedEntries(int targetEntry, List<Entry<E>> entries) { return entries.subList(targetEntry + 1, entries.size()); } @Override <E> SortedMultiset<E> subMultiset(SortedMultiset<E> multiset, List<Entry<E>> entries, int targetEntry) { return multiset.tailMultiset(entries.get(targetEntry).getElement(), OPEN); } }, HEAD_CLOSED { @Override <E> List<Entry<E>> expectedEntries(int targetEntry, List<Entry<E>> entries) { return entries.subList(0, targetEntry + 1); } @Override <E> SortedMultiset<E> subMultiset(SortedMultiset<E> multiset, List<Entry<E>> entries, int targetEntry) { return multiset.headMultiset(entries.get(targetEntry).getElement(), CLOSED); } }, HEAD_OPEN { @Override <E> List<Entry<E>> expectedEntries(int targetEntry, List<Entry<E>> entries) { return entries.subList(0, targetEntry); } @Override <E> SortedMultiset<E> subMultiset(SortedMultiset<E> multiset, List<Entry<E>> entries, int targetEntry) { return multiset.headMultiset(entries.get(targetEntry).getElement(), OPEN); } }; abstract <E> List<Entry<E>> expectedEntries(int targetEntry, List<Entry<E>> entries); abstract <E> SortedMultiset<E> subMultiset(SortedMultiset<E> multiset, List<Entry<E>> entries, int targetEntry); } private void testSubMultisetEntrySet(SubMultisetSpec spec) { List<Entry<E>> entries = copyToList(sortedMultiset.entrySet()); for (int i = 0; i < entries.size(); i++) { List<Entry<E>> expected = spec.expectedEntries(i, entries); SortedMultiset<E> subMultiset = spec.subMultiset(sortedMultiset, entries, i); assertEquals(expected, copyToList(subMultiset.entrySet())); } } private void testSubMultisetSize(SubMultisetSpec spec) { List<Entry<E>> entries = copyToList(sortedMultiset.entrySet()); for (int i = 0; i < entries.size(); i++) { List<Entry<E>> expected = spec.expectedEntries(i, entries); SortedMultiset<E> subMultiset = spec.subMultiset(sortedMultiset, entries, i); assertEquals(totalSize(expected), subMultiset.size()); } } private void testSubMultisetDistinctElements(SubMultisetSpec spec) { List<Entry<E>> entries = copyToList(sortedMultiset.entrySet()); for (int i = 0; i < entries.size(); i++) { List<Entry<E>> expected = spec.expectedEntries(i, entries); SortedMultiset<E> subMultiset = spec.subMultiset(sortedMultiset, entries, i); assertEquals(expected.size(), subMultiset.entrySet().size()); assertEquals(expected.size(), subMultiset.elementSet().size()); } } public void testTailClosedEntrySet() { testSubMultisetEntrySet(SubMultisetSpec.TAIL_CLOSED); } public void testTailClosedSize() { testSubMultisetSize(SubMultisetSpec.TAIL_CLOSED); } public void testTailClosedDistinctElements() { testSubMultisetDistinctElements(SubMultisetSpec.TAIL_CLOSED); } public void testTailOpenEntrySet() { testSubMultisetEntrySet(SubMultisetSpec.TAIL_OPEN); } public void testTailOpenSize() { testSubMultisetSize(SubMultisetSpec.TAIL_OPEN); } public void testTailOpenDistinctElements() { testSubMultisetDistinctElements(SubMultisetSpec.TAIL_OPEN); } public void testHeadClosedEntrySet() { testSubMultisetEntrySet(SubMultisetSpec.HEAD_CLOSED); } public void testHeadClosedSize() { testSubMultisetSize(SubMultisetSpec.HEAD_CLOSED); } public void testHeadClosedDistinctElements() { testSubMultisetDistinctElements(SubMultisetSpec.HEAD_CLOSED); } public void testHeadOpenEntrySet() { testSubMultisetEntrySet(SubMultisetSpec.HEAD_OPEN); } public void testHeadOpenSize() { testSubMultisetSize(SubMultisetSpec.HEAD_OPEN); } public void testHeadOpenDistinctElements() { testSubMultisetDistinctElements(SubMultisetSpec.HEAD_OPEN); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testClearTailOpen() { List<Entry<E>> expected = copyToList(sortedMultiset.headMultiset(b.getElement(), CLOSED).entrySet()); sortedMultiset.tailMultiset(b.getElement(), OPEN).clear(); assertEquals(expected, copyToList(sortedMultiset.entrySet())); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testClearTailOpenEntrySet() { List<Entry<E>> expected = copyToList(sortedMultiset.headMultiset(b.getElement(), CLOSED).entrySet()); sortedMultiset.tailMultiset(b.getElement(), OPEN).entrySet().clear(); assertEquals(expected, copyToList(sortedMultiset.entrySet())); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testClearTailClosed() { List<Entry<E>> expected = copyToList(sortedMultiset.headMultiset(b.getElement(), OPEN).entrySet()); sortedMultiset.tailMultiset(b.getElement(), CLOSED).clear(); assertEquals(expected, copyToList(sortedMultiset.entrySet())); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testClearTailClosedEntrySet() { List<Entry<E>> expected = copyToList(sortedMultiset.headMultiset(b.getElement(), OPEN).entrySet()); sortedMultiset.tailMultiset(b.getElement(), CLOSED).entrySet().clear(); assertEquals(expected, copyToList(sortedMultiset.entrySet())); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testClearHeadOpen() { List<Entry<E>> expected = copyToList(sortedMultiset.tailMultiset(b.getElement(), CLOSED).entrySet()); sortedMultiset.headMultiset(b.getElement(), OPEN).clear(); assertEquals(expected, copyToList(sortedMultiset.entrySet())); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testClearHeadOpenEntrySet() { List<Entry<E>> expected = copyToList(sortedMultiset.tailMultiset(b.getElement(), CLOSED).entrySet()); sortedMultiset.headMultiset(b.getElement(), OPEN).entrySet().clear(); assertEquals(expected, copyToList(sortedMultiset.entrySet())); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testClearHeadClosed() { List<Entry<E>> expected = copyToList(sortedMultiset.tailMultiset(b.getElement(), OPEN).entrySet()); sortedMultiset.headMultiset(b.getElement(), CLOSED).clear(); assertEquals(expected, copyToList(sortedMultiset.entrySet())); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testClearHeadClosedEntrySet() { List<Entry<E>> expected = copyToList(sortedMultiset.tailMultiset(b.getElement(), OPEN).entrySet()); sortedMultiset.headMultiset(b.getElement(), CLOSED).entrySet().clear(); assertEquals(expected, copyToList(sortedMultiset.entrySet())); } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.Multiset; import com.google.common.collect.testing.TestCollectionGenerator; /** * Creates multisets, containing sample elements, to be tested. * * @author Jared Levy */ @GwtCompatible public interface TestMultisetGenerator<E> extends TestCollectionGenerator<E> { @Override Multiset<E> create(Object... elements); }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.BiMap; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.SampleElements; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * Implementation helper for {@link TestBiMapGenerator} for use with bimaps of * strings. * * <p>This class is GWT compatible. * * @author Chris Povirk * @author Jared Levy * @author George van den Driessche * @author Louis Wasserman */ @GwtCompatible public abstract class TestStringBiMapGenerator implements TestBiMapGenerator<String, String> { @Override public SampleElements<Map.Entry<String, String>> samples() { return new SampleElements<Map.Entry<String, String>>( Helpers.mapEntry("one", "January"), Helpers.mapEntry("two", "February"), Helpers.mapEntry("three", "March"), Helpers.mapEntry("four", "April"), Helpers.mapEntry("five", "May") ); } @Override public final BiMap<String, String> create(Object... entries) { @SuppressWarnings("unchecked") Entry<String, String>[] array = new Entry[entries.length]; int i = 0; for (Object o : entries) { @SuppressWarnings("unchecked") Entry<String, String> e = (Entry<String, String>) o; array[i++] = e; } return create(array); } protected abstract BiMap<String, String> create( Entry<String, String>[] entries); @Override @SuppressWarnings("unchecked") public final Entry<String, String>[] createArray(int length) { return new Entry[length]; } @Override public final String[] createKeyArray(int length) { return new String[length]; } @Override public final String[] createValueArray(int length) { return new String[length]; } /** Returns the original element list, unchanged. */ @Override public Iterable<Entry<String, String>> order( List<Entry<String, String>> insertionOrder) { return insertionOrder; } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.Maps; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.TestMapEntrySetGenerator; import com.google.common.collect.testing.TestStringSetGenerator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Generators of various {@link com.google.common.collect.BiMap}s and derived * collections. * * @author Jared Levy * @author Hayward Chan */ @GwtCompatible public class BiMapGenerators { public static class ImmutableBiMapKeySetGenerator extends TestStringSetGenerator { @Override protected Set<String> create(String[] elements) { Map<String, Integer> map = Maps.newLinkedHashMap(); for (int i = 0; i < elements.length; i++) { map.put(elements[i], i); } return ImmutableBiMap.copyOf(map).keySet(); } } public static class ImmutableBiMapValuesGenerator extends TestStringSetGenerator { @Override protected Set<String> create(String[] elements) { Map<Integer, String> map = Maps.newLinkedHashMap(); for (int i = 0; i < elements.length; i++) { map.put(i, elements[i]); } return ImmutableBiMap.copyOf(map).values(); } } public static class ImmutableBiMapInverseEntrySetGenerator extends TestMapEntrySetGenerator<String, String> { public ImmutableBiMapInverseEntrySetGenerator() { super(new SampleElements.Strings(), new SampleElements.Strings()); } @Override public Set<Entry<String, String>> createFromEntries( Entry<String, String>[] entries) { Map<String, String> map = Maps.newLinkedHashMap(); for (Entry<String, String> entry : entries) { checkNotNull(entry); map.put(entry.getValue(), entry.getKey()); } return ImmutableBiMap.copyOf(map).inverse().entrySet(); } } public static class ImmutableBiMapInverseKeySetGenerator extends TestStringSetGenerator { @Override protected Set<String> create(String[] elements) { Map<Integer, String> map = Maps.newLinkedHashMap(); for (int i = 0; i < elements.length; i++) { map.put(i, elements[i]); } return ImmutableBiMap.copyOf(map).inverse().keySet(); } } public static class ImmutableBiMapInverseValuesGenerator extends TestStringSetGenerator { @Override protected Set<String> create(String[] elements) { Map<String, Integer> map = Maps.newLinkedHashMap(); for (int i = 0; i < elements.length; i++) { map.put(elements[i], i); } return ImmutableBiMap.copyOf(map).inverse().values(); } } public static class ImmutableBiMapEntrySetGenerator extends TestMapEntrySetGenerator<String, String> { public ImmutableBiMapEntrySetGenerator() { super(new SampleElements.Strings(), new SampleElements.Strings()); } @Override public Set<Entry<String, String>> createFromEntries( Entry<String, String>[] entries) { Map<String, String> map = Maps.newLinkedHashMap(); for (Entry<String, String> entry : entries) { checkNotNull(entry); map.put(entry.getKey(), entry.getValue()); } return ImmutableBiMap.copyOf(map).entrySet(); } } }
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_INCLUDING_VIEWS; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.Multiset; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.testing.SerializableTester; import java.util.Set; /** * A generic JUnit test which tests multiset-specific serialization. Can't be invoked directly; * please see {@link com.google.common.collect.testing.MultisetTestSuiteBuilder}. * * @author Louis Wasserman */ @GwtCompatible // but no-op public class MultisetSerializationTester<E> extends AbstractMultisetTester<E> { @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) public void testEntrySetSerialization() { Set<Multiset.Entry<E>> expected = getMultiset().entrySet(); assertEquals(expected, SerializableTester.reserialize(expected)); } @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) public void testElementSetSerialization() { Set<E> expected = getMultiset().elementSet(); assertEquals(expected, SerializableTester.reserialize(expected)); } }
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.MapFeature.SUPPORTS_CLEAR; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.BiMap; import com.google.common.collect.testing.features.MapFeature; /** * Tester for {@code BiMap.clear}. * * @author Louis Wasserman */ @GwtCompatible public class BiMapClearTester<K, V> extends AbstractBiMapTester<K, V> { @MapFeature.Require(SUPPORTS_CLEAR) public void testClearClearsInverse() { BiMap<V, K> inv = getMap().inverse(); getMap().clear(); assertTrue(getMap().isEmpty()); assertTrue(inv.isEmpty()); } @MapFeature.Require(SUPPORTS_CLEAR) public void testKeySetClearClearsInverse() { BiMap<V, K> inv = getMap().inverse(); getMap().keySet().clear(); assertTrue(getMap().isEmpty()); assertTrue(inv.isEmpty()); } @MapFeature.Require(SUPPORTS_CLEAR) public void testValuesClearClearsInverse() { BiMap<V, K> inv = getMap().inverse(); getMap().values().clear(); assertTrue(getMap().isEmpty()); assertTrue(inv.isEmpty()); } @MapFeature.Require(SUPPORTS_CLEAR) public void testClearInverseClears() { BiMap<V, K> inv = getMap().inverse(); inv.clear(); assertTrue(getMap().isEmpty()); assertTrue(inv.isEmpty()); } @MapFeature.Require(SUPPORTS_CLEAR) public void testClearInverseKeySetClears() { BiMap<V, K> inv = getMap().inverse(); inv.keySet().clear(); assertTrue(getMap().isEmpty()); assertTrue(inv.isEmpty()); } @MapFeature.Require(SUPPORTS_CLEAR) public void testClearInverseValuesClears() { BiMap<V, K> inv = getMap().inverse(); inv.values().clear(); assertTrue(getMap().isEmpty()); assertTrue(inv.isEmpty()); } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.lang.reflect.Method; /** * Methods factored out so that they can be emulated in GWT. * * @author Hayward Chan */ @GwtCompatible class Platform { @GwtIncompatible("Class.getMethod, java.lang.reflect.Method") static Method getMethod(Class<?> clazz, String name) { try { return clazz.getMethod(name); } catch (Exception e) { throw new RuntimeException(e); } } }
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; import java.lang.reflect.Method; import java.util.Collections; import java.util.List; /** * 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 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; } /** * Returns {@link Method} instances for the tests that assume that the inverse will be the same * after serialization. */ public static List<Method> getInverseSameAfterSerializingMethods() { return Collections.singletonList(getMethod("testInverseSerialization")); } private static Method getMethod(String methodName) { return Platform.getMethod(BiMapInverseTester.class, methodName); } }
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.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedMap.Builder; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.TestCollectionGenerator; import com.google.common.collect.testing.TestMapEntrySetGenerator; import com.google.common.collect.testing.TestStringSetGenerator; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map.Entry; import java.util.Set; /** * Generators of sorted maps and derived collections. * * @author Kevin Bourrillion * @author Jesse Wilson * @author Jared Levy * @author Hayward Chan */ @GwtCompatible public class SortedMapGenerators { public static final Comparator<Entry<String, String>> ENTRY_COMPARATOR = new Comparator<Entry<String, String>>() { @Override public int compare( Entry<String, String> o1, Entry<String, String> o2) { return o1.getKey().compareTo(o2.getKey()); } }; public static class ImmutableSortedMapKeySetGenerator extends TestStringSetGenerator { @Override protected Set<String> create(String[] elements) { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); for (String key : elements) { builder.put(key, 4); } return builder.build().keySet(); } @Override public List<String> order(List<String> insertionOrder) { Collections.sort(insertionOrder); return insertionOrder; } } public static class ImmutableSortedMapValuesGenerator implements TestCollectionGenerator<String> { @Override public SampleElements<String> samples() { return new SampleElements.Strings(); } @Override public Collection<String> create(Object... elements) { Builder<Integer, String> builder = ImmutableSortedMap.naturalOrder(); for (int i = 0; i < elements.length; i++) { builder.put(i, toStringOrNull(elements[i])); } return builder.build().values(); } @Override public String[] createArray(int length) { return new String[length]; } @Override public List<String> order(List<String> insertionOrder) { return insertionOrder; } } public static class ImmutableSortedMapSubMapEntryGenerator extends TestMapEntrySetGenerator<String, String> { public ImmutableSortedMapSubMapEntryGenerator() { super(new SampleElements.Strings(), new SampleElements.Strings()); } @Override public Set<Entry<String, String>> createFromEntries( Entry<String, String>[] entries) { Builder<String, String> builder = ImmutableSortedMap.naturalOrder(); builder.put(SampleElements.Strings.BEFORE_FIRST, "begin"); builder.put(SampleElements.Strings.AFTER_LAST, "end"); for (Entry<String, String> entry : entries) { checkNotNull(entry); builder.put(entry.getKey(), entry.getValue()); } return builder.build().subMap(SampleElements.Strings.MIN_ELEMENT, SampleElements.Strings.AFTER_LAST).entrySet(); } @Override public List<Entry<String, String>> order( List<Entry<String, String>> insertionOrder) { Collections.sort(insertionOrder, ENTRY_COMPARATOR); return insertionOrder; } } public static class ImmutableSortedMapHeadMapKeySetGenerator extends TestStringSetGenerator { @Override protected Set<String> create(String[] elements) { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); builder.put(SampleElements.Strings.AFTER_LAST, -1); for (String key : elements) { builder.put(key, 4); } return builder.build().headMap( SampleElements.Strings.AFTER_LAST).keySet(); } @Override public List<String> order(List<String> insertionOrder) { Collections.sort(insertionOrder); return insertionOrder; } } public static class ImmutableSortedMapTailMapValuesGenerator implements TestCollectionGenerator<String> { @Override public SampleElements<String> samples() { return new SampleElements.Strings(); } @Override public Collection<String> create(Object... elements) { Builder<Integer, String> builder = ImmutableSortedMap.naturalOrder(); builder.put(-1, "begin"); for (int i = 0; i < elements.length; i++) { builder.put(i, toStringOrNull(elements[i])); } return builder.build().tailMap(0).values(); } @Override public String[] createArray(int length) { return new String[length]; } @Override public List<String> order(List<String> insertionOrder) { return insertionOrder; } } public static class ImmutableSortedMapEntrySetGenerator extends TestMapEntrySetGenerator<String, String> { public ImmutableSortedMapEntrySetGenerator() { super(new SampleElements.Strings(), new SampleElements.Strings()); } @Override public Set<Entry<String, String>> createFromEntries( Entry<String, String>[] entries) { Builder<String, String> builder = ImmutableSortedMap.naturalOrder(); for (Entry<String, String> entry : entries) { checkNotNull(entry); builder.put(entry.getKey(), entry.getValue()); } return builder.build().entrySet(); } @Override public List<Entry<String, String>> order( List<Entry<String, String>> insertionOrder) { Collections.sort(insertionOrder, ENTRY_COMPARATOR); return insertionOrder; } } private static String toStringOrNull(Object o) { return (o == null) ? null : o.toString(); } }
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.collect.testing.features.CollectionSize.ONE; 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.HashMultiset; import com.google.common.collect.Multiset; import com.google.common.collect.Multisets; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionSize; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; /** * A generic JUnit test which tests multiset-specific read operations. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.SetTestSuiteBuilder}. * * @author Jared Levy */ @GwtCompatible public class MultisetReadsTester<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)); } public void testCount_null() { assertEquals("multiset.count(null) didn't return 0", 0, getMultiset().count(null)); } public void testCount_wrongType() { assertEquals("multiset.count(wrongType) didn't return 0", 0, getMultiset().count(WrongType.VALUE)); } @CollectionSize.Require(absent = ZERO) public void testElementSet_contains() { assertTrue("multiset.elementSet().contains(present) returned false", getMultiset().elementSet().contains(samples.e0)); } @CollectionSize.Require(absent = ZERO) public void testEntrySet_contains() { assertTrue("multiset.entrySet() didn't contain [present, 1]", getMultiset().entrySet().contains( Multisets.immutableEntry(samples.e0, 1))); } public void testEntrySet_contains_count0() { assertFalse("multiset.entrySet() contains [missing, 0]", getMultiset().entrySet().contains( Multisets.immutableEntry(samples.e3, 0))); } public void testEntrySet_contains_nonentry() { assertFalse("multiset.entrySet() contains a non-entry", getMultiset().entrySet().contains(samples.e0)); } public void testEntrySet_twice() { assertEquals("calling multiset.entrySet() twice returned unequal sets", getMultiset().entrySet(), getMultiset().entrySet()); } @CollectionSize.Require(ZERO) public void testEntrySet_hashCode_size0() { assertEquals("multiset.entrySet() has incorrect hash code", 0, getMultiset().entrySet().hashCode()); } @CollectionSize.Require(ONE) public void testEntrySet_hashCode_size1() { assertEquals("multiset.entrySet() has incorrect hash code", 1 ^ samples.e0.hashCode(), getMultiset().entrySet().hashCode()); } public void testEquals_yes() { assertTrue("multiset doesn't equal a multiset with the same elements", getMultiset().equals(HashMultiset.create(getSampleElements()))); } public void testEquals_differentSize() { Multiset<E> other = HashMultiset.create(getSampleElements()); other.add(samples.e0); assertFalse("multiset equals a multiset with a different size", getMultiset().equals(other)); } @CollectionSize.Require(absent = ZERO) public void testEquals_differentElements() { Multiset<E> other = HashMultiset.create(getSampleElements()); other.remove(samples.e0); other.add(samples.e3); assertFalse("multiset equals a multiset with different elements", getMultiset().equals(other)); } @CollectionSize.Require(ZERO) public void testHashCode_size0() { assertEquals("multiset has incorrect hash code", 0, getMultiset().hashCode()); } @CollectionSize.Require(ONE) public void testHashCode_size1() { assertEquals("multiset has incorrect hash code", 1 ^ samples.e0.hashCode(), getMultiset().hashCode()); } /** * Returns {@link Method} instances for the read tests that assume multisets * support duplicates so that the test of {@code Multisets.forSet()} can * suppress them. */ public static List<Method> getReadsDuplicateInitializingMethods() { return Arrays.asList( Platform.getMethod(MultisetReadsTester.class, "testCount_3")); } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.BiMap; import com.google.common.collect.testing.TestContainerGenerator; import java.util.Map; /** * Creates bimaps, containing sample entries, to be tested. * * @author Louis Wasserman */ @GwtCompatible public interface TestBiMapGenerator<K, V> extends TestContainerGenerator<BiMap<K, V>, Map.Entry<K, V>> { K[] createKeyArray(int length); V[] createValueArray(int length); }
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_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.lang.reflect.Method; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * Tester to make sure the {@code iterator().remove()} implementation of {@code Multiset} works when * there are multiple occurrences of elements. * * @author Louis Wasserman */ @GwtCompatible public class MultisetIteratorTester<E> extends AbstractMultisetTester<E> { @SuppressWarnings("unchecked") @CollectionFeature.Require({SUPPORTS_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_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_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_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(); } /** * Returns {@link Method} instances for the tests that assume multisets support duplicates so that * the test of {@code Multisets.forSet()} can suppress them. */ public static List<Method> getIteratorDuplicateInitializingMethods() { return Arrays.asList( Platform.getMethod(MultisetIteratorTester.class, "testIteratorKnownOrder"), Platform.getMethod(MultisetIteratorTester.class, "testIteratorUnknownOrder"), Platform.getMethod(MultisetIteratorTester.class, "testRemovingIteratorKnownOrder"), Platform.getMethod(MultisetIteratorTester.class, "testRemovingIteratorUnknownOrder")); } }
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.collect.testing.features.CollectionFeature.SUPPORTS_ADD; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_CLEAR; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE_ALL; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_RETAIN_ALL; import static com.google.common.collect.testing.features.CollectionSize.ONE; 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.Multisets; 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.lang.reflect.Method; import java.util.Collections; import java.util.Iterator; /** * A generic JUnit test which tests multiset-specific write operations. * Can't be invoked directly; please see {@link MultisetTestSuiteBuilder}. * * @author Jared Levy */ @GwtCompatible public class MultisetWritesTester<E> extends AbstractMultisetTester<E> { /** * Returns the {@link Method} instance for * {@link #testEntrySet_iterator()} so that tests of * classes with unmodifiable iterators can suppress it. */ public static Method getEntrySetIteratorMethod() { return Platform.getMethod( MultisetWritesTester.class, "testEntrySet_iterator"); } @CollectionFeature.Require(SUPPORTS_ADD) public void testAddOccurrences() { int oldCount = getMultiset().count(samples.e0); assertEquals("multiset.add(E, int) should return the old count", oldCount, getMultiset().add(samples.e0, 2)); assertEquals("multiset.count() incorrect after add(E, int)", oldCount + 2, getMultiset().count(samples.e0)); } @CollectionFeature.Require(absent = SUPPORTS_ADD) public void testAddOccurrences_unsupported() { try { getMultiset().add(samples.e0, 2); fail("unsupported multiset.add(E, int) didn't throw exception"); } catch (UnsupportedOperationException required) {} } @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)); } @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)); } @CollectionFeature.Require(SUPPORTS_CLEAR) public void testEntrySet_clear() { getMultiset().entrySet().clear(); assertTrue("multiset not empty after entrySet().clear()", getMultiset().isEmpty()); } @CollectionSize.Require(ONE) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testEntrySet_iterator() { Iterator<Multiset.Entry<E>> iterator = getMultiset().entrySet().iterator(); assertTrue( "non-empty multiset.entrySet() iterator.hasNext() returned false", iterator.hasNext()); assertEquals("multiset.entrySet() iterator.next() returned incorrect entry", Multisets.immutableEntry(samples.e0, 1), iterator.next()); assertFalse( "size 1 multiset.entrySet() iterator.hasNext() returned true " + "after next()", iterator.hasNext()); iterator.remove(); assertTrue( "multiset isn't empty after multiset.entrySet() iterator.remove()", getMultiset().isEmpty()); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testEntrySet_iterator_remove_unsupported() { Iterator<Multiset.Entry<E>> iterator = getMultiset().entrySet().iterator(); assertTrue( "non-empty multiset.entrySet() iterator.hasNext() returned false", iterator.hasNext()); try { iterator.remove(); fail("multiset.entrySet() iterator.remove() didn't throw an exception"); } catch (UnsupportedOperationException expected) {} } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testEntrySet_remove_present() { assertTrue( "multiset.entrySet.remove(presentEntry) returned false", getMultiset().entrySet().remove( Multisets.immutableEntry(samples.e0, 1))); assertFalse( "multiset contains element after removing its entry", getMultiset().contains(samples.e0)); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testEntrySet_remove_missing() { assertFalse( "multiset.entrySet.remove(missingEntry) returned true", getMultiset().entrySet().remove( Multisets.immutableEntry(samples.e0, 2))); assertTrue( "multiset didn't contain element after removing a missing entry", getMultiset().contains(samples.e0)); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(SUPPORTS_REMOVE_ALL) public void testEntrySet_removeAll_present() { assertTrue( "multiset.entrySet.removeAll(presentEntry) returned false", getMultiset().entrySet().removeAll( Collections.singleton(Multisets.immutableEntry(samples.e0, 1)))); assertFalse( "multiset contains element after removing its entry", getMultiset().contains(samples.e0)); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(SUPPORTS_REMOVE_ALL) public void testEntrySet_removeAll_missing() { assertFalse( "multiset.entrySet.remove(missingEntry) returned true", getMultiset().entrySet().removeAll( Collections.singleton(Multisets.immutableEntry(samples.e0, 2)))); assertTrue( "multiset didn't contain element after removing a missing entry", getMultiset().contains(samples.e0)); } @CollectionFeature.Require(SUPPORTS_REMOVE_ALL) public void testEntrySet_removeAll_null() { try { getMultiset().entrySet().removeAll(null); fail("multiset.entrySet.removeAll(null) didn't throw an exception"); } catch (NullPointerException expected) {} } @CollectionSize.Require(ONE) @CollectionFeature.Require(SUPPORTS_RETAIN_ALL) public void testEntrySet_retainAll_present() { assertFalse( "multiset.entrySet.retainAll(presentEntry) returned false", getMultiset().entrySet().retainAll( Collections.singleton(Multisets.immutableEntry(samples.e0, 1)))); assertTrue( "multiset doesn't contains element after retaining its entry", getMultiset().contains(samples.e0)); } @CollectionSize.Require(ONE) @CollectionFeature.Require(SUPPORTS_RETAIN_ALL) public void testEntrySet_retainAll_missing() { assertTrue( "multiset.entrySet.retainAll(missingEntry) returned true", getMultiset().entrySet().retainAll( Collections.singleton(Multisets.immutableEntry(samples.e0, 2)))); assertFalse( "multiset contains element after retaining a different entry", getMultiset().contains(samples.e0)); } @CollectionFeature.Require(SUPPORTS_RETAIN_ALL) public void testEntrySet_retainAll_null() { try { getMultiset().entrySet().retainAll(null); // Returning successfully is not ideal, but tolerated. } catch (NullPointerException 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.google; import com.google.common.annotations.GwtCompatible; /** * A generic JUnit test which tests unconditional {@code setCount()} operations * on a multiset. Can't be invoked directly; please see * {@link MultisetTestSuiteBuilder}. * * @author Chris Povirk */ @GwtCompatible public class MultisetSetCountUnconditionallyTester<E> extends AbstractMultisetSetCountTester<E> { @Override void setCountCheckReturnValue(E element, int count) { assertEquals("multiset.setCount() should return the old count", getMultiset().count(element), setCount(element, count)); } @Override void setCountNoCheckReturnValue(E element, int count) { setCount(element, count); } private int setCount(E element, int count) { return getMultiset().setCount(element, count); } }
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.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.TestCollectionGenerator; import com.google.common.collect.testing.TestListGenerator; import com.google.common.collect.testing.TestMapEntrySetGenerator; import com.google.common.collect.testing.TestStringMapGenerator; import com.google.common.collect.testing.TestStringSetGenerator; import com.google.common.collect.testing.TestUnhashableCollectionGenerator; import com.google.common.collect.testing.UnhashableObject; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Generators of different types of map and related collections, such as * keys, entries and values. * * @author Hayward Chan */ @GwtCompatible public class MapGenerators { public static class ImmutableMapGenerator extends TestStringMapGenerator { @Override protected Map<String, String> create(Entry<String, String>[] entries) { Builder<String, String> builder = ImmutableMap.builder(); for (Entry<String, String> entry : entries) { builder.put(entry.getKey(), entry.getValue()); } return builder.build(); } } public static class ImmutableMapKeySetGenerator extends TestStringSetGenerator { @Override protected Set<String> create(String[] elements) { Builder<String, Integer> builder = ImmutableMap.builder(); for (String key : elements) { builder.put(key, 4); } return builder.build().keySet(); } } public static class ImmutableMapValuesGenerator implements TestCollectionGenerator<String> { @Override public SampleElements<String> samples() { return new SampleElements.Strings(); } @Override public Collection<String> create(Object... elements) { Builder<Object, String> builder = ImmutableMap.builder(); for (Object key : elements) { builder.put(key, String.valueOf(key)); } return builder.build().values(); } @Override public String[] createArray(int length) { return new String[length]; } @Override public List<String> order(List<String> insertionOrder) { return insertionOrder; } } public static class ImmutableMapUnhashableValuesGenerator extends TestUnhashableCollectionGenerator<Collection<UnhashableObject>> { @Override public Collection<UnhashableObject> create( UnhashableObject[] elements) { Builder<Integer, UnhashableObject> builder = ImmutableMap.builder(); int key = 1; for (UnhashableObject value : elements) { builder.put(key++, value); } return builder.build().values(); } } public static class ImmutableMapEntrySetGenerator extends TestMapEntrySetGenerator<String, String> { public ImmutableMapEntrySetGenerator() { super(new SampleElements.Strings(), new SampleElements.Strings()); } @Override public Set<Entry<String, String>> createFromEntries( Entry<String, String>[] entries) { Builder<String, String> builder = ImmutableMap.builder(); for (Entry<String, String> entry : entries) { // This null-check forces NPE to be thrown for tests with null // elements. Those tests aren't useful in testing entry sets // because entry sets never have null elements. checkNotNull(entry); builder.put(entry.getKey(), entry.getValue()); } return builder.build().entrySet(); } } public static class ImmutableMapValueListGenerator implements TestListGenerator<String> { @Override public SampleElements<String> samples() { return new SampleElements.Strings(); } @Override public List<String> create(Object... elements) { Builder<Integer, String> builder = ImmutableMap.builder(); for (int i = 0; i < elements.length; i++) { builder.put(i, toStringOrNull(elements[i])); } return builder.build().values().asList(); } @Override public String[] createArray(int length) { return new String[length]; } @Override public Iterable<String> order(List<String> insertionOrder) { return insertionOrder; } } private static String toStringOrNull(Object o) { return (o == null) ? null : o.toString(); } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.Multiset; import com.google.common.collect.testing.AbstractCollectionTester; /** * Base class for multiset collection tests. * * @author Jared Levy */ @GwtCompatible public class AbstractMultisetTester<E> extends AbstractCollectionTester<E> { protected final Multiset<E> getMultiset() { return (Multiset<E>) collection; } protected void initThreeCopies() { collection = getSubjectGenerator().create(samples.e0, samples.e0, samples.e0); } }
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.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; /** * Tester for {@code BiMap.put} and {@code BiMap.forcePut}. */ @GwtCompatible public class BiMapPutTester<K, V> extends AbstractBiMapTester<K, V> { @SuppressWarnings("unchecked") @MapFeature.Require(SUPPORTS_PUT) @CollectionSize.Require(ZERO) public void testPutWithSameValueFails() { K k0 = samples.e0.getKey(); K k1 = samples.e1.getKey(); V v0 = samples.e0.getValue(); getMap().put(k0, v0); try { getMap().put(k1, v0); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // success } // verify that the bimap is unchanged expectAdded(samples.e0); } @SuppressWarnings("unchecked") @MapFeature.Require(SUPPORTS_PUT) @CollectionSize.Require(ZERO) public void testPutPresentKeyDifferentValue() { K k0 = samples.e0.getKey(); V v0 = samples.e0.getValue(); V v1 = samples.e1.getValue(); getMap().put(k0, v0); getMap().put(k0, v1); // verify that the bimap is changed, and that the old inverse mapping // from v1 -> v0 is deleted expectContents(Helpers.mapEntry(k0, v1)); } @SuppressWarnings("unchecked") @MapFeature.Require(SUPPORTS_PUT) @CollectionSize.Require(ZERO) public void putDistinctKeysDistinctValues() { getMap().put(samples.e0.getKey(), samples.e0.getValue()); getMap().put(samples.e1.getKey(), samples.e1.getValue()); expectAdded(samples.e0, samples.e1); } @SuppressWarnings("unchecked") @MapFeature.Require(SUPPORTS_PUT) @CollectionSize.Require(ZERO) public void testForcePutOverwritesOldValueEntry() { K k0 = samples.e0.getKey(); K k1 = samples.e1.getKey(); V v0 = samples.e0.getValue(); getMap().put(k0, v0); getMap().forcePut(k1, v0); // verify that the bimap is unchanged expectAdded(Helpers.mapEntry(k1, v0)); } @SuppressWarnings("unchecked") @MapFeature.Require(SUPPORTS_PUT) @CollectionSize.Require(ZERO) public void testInversePut() { K k0 = samples.e0.getKey(); V v0 = samples.e0.getValue(); K k1 = samples.e1.getKey(); V v1 = samples.e1.getValue(); getMap().put(k0, v0); getMap().inverse().put(v1, k1); expectAdded(samples.e0, samples.e1); } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.Multiset; import com.google.common.collect.testing.AbstractCollectionTestSuiteBuilder; import com.google.common.collect.testing.AbstractTester; import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.OneSizeTestContainerGenerator; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.testers.CollectionSerializationEqualTester; import com.google.common.testing.SerializableTester; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Creates, based on your criteria, a JUnit test suite that exhaustively tests * a {@code Multiset} implementation. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible public class MultisetTestSuiteBuilder<E> extends AbstractCollectionTestSuiteBuilder<MultisetTestSuiteBuilder<E>, E> { public static <E> MultisetTestSuiteBuilder<E> using( TestMultisetGenerator<E> generator) { return new MultisetTestSuiteBuilder<E>().usingGenerator(generator); } @Override protected List<Class<? extends AbstractTester>> getTesters() { List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters()); testers.add(CollectionSerializationEqualTester.class); testers.add(MultisetReadsTester.class); testers.add(MultisetSetCountConditionallyTester.class); testers.add(MultisetSetCountUnconditionallyTester.class); testers.add(MultisetWritesTester.class); testers.add(MultisetIteratorTester.class); testers.add(MultisetSerializationTester.class); return testers; } private static Set<Feature<?>> computeReserializedMultisetFeatures( Set<Feature<?>> features) { Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>(); derivedFeatures.addAll(features); derivedFeatures.remove(CollectionFeature.SERIALIZABLE); derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS); return derivedFeatures; } @Override protected List<TestSuite> createDerivedSuites( FeatureSpecificTestSuiteBuilder< ?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) { List<TestSuite> derivedSuites = new ArrayList<TestSuite>( super.createDerivedSuites(parentBuilder)); if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) { derivedSuites.add(MultisetTestSuiteBuilder .using(new ReserializedMultisetGenerator<E>(parentBuilder.getSubjectGenerator())) .named(getName() + " reserialized") .withFeatures(computeReserializedMultisetFeatures(parentBuilder.getFeatures())) .createTestSuite()); } return derivedSuites; } static class ReserializedMultisetGenerator<E> implements TestMultisetGenerator<E>{ final OneSizeTestContainerGenerator<Collection<E>, E> gen; private ReserializedMultisetGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) { this.gen = gen; } @Override public SampleElements<E> samples() { return gen.samples(); } @Override public Multiset<E> create(Object... elements) { return (Multiset<E>) SerializableTester.reserialize(gen.create(elements)); } @Override public E[] createArray(int length) { return gen.createArray(length); } @Override public Iterable<E> order(List<E> insertionOrder) { return gen.order(insertionOrder); } } }
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 java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.testing.TestListGenerator; import com.google.common.collect.testing.TestStringListGenerator; import com.google.common.collect.testing.TestUnhashableCollectionGenerator; import com.google.common.collect.testing.UnhashableObject; import java.util.Collections; import java.util.List; /** * Common generators of different types of lists. * * @author Hayward Chan */ @GwtCompatible public final class ListGenerators { private ListGenerators() {} public static class ImmutableListOfGenerator extends TestStringListGenerator { @Override protected List<String> create(String[] elements) { return ImmutableList.copyOf(elements); } } public static class BuilderAddListGenerator extends TestStringListGenerator { @Override protected List<String> create(String[] elements) { Builder<String> builder = ImmutableList.<String>builder(); for (String element : elements) { builder.add(element); } return builder.build(); } } public static class BuilderAddAllListGenerator extends TestStringListGenerator { @Override protected List<String> create(String[] elements) { return ImmutableList.<String>builder() .addAll(asList(elements)) .build(); } } public static class BuilderReversedListGenerator extends TestStringListGenerator { @Override protected List<String> create(String[] elements) { List<String> list = asList(elements); Collections.reverse(list); return ImmutableList.copyOf(list).reverse(); } } public static class ImmutableListHeadSubListGenerator extends TestStringListGenerator { @Override protected List<String> create(String[] elements) { String[] suffix = {"f", "g"}; String[] all = new String[elements.length + suffix.length]; System.arraycopy(elements, 0, all, 0, elements.length); System.arraycopy(suffix, 0, all, elements.length, suffix.length); return ImmutableList.copyOf(all) .subList(0, elements.length); } } public static class ImmutableListTailSubListGenerator extends TestStringListGenerator { @Override protected List<String> create(String[] elements) { String[] prefix = {"f", "g"}; String[] all = new String[elements.length + prefix.length]; System.arraycopy(prefix, 0, all, 0, 2); System.arraycopy(elements, 0, all, 2, elements.length); return ImmutableList.copyOf(all) .subList(2, elements.length + 2); } } public static class ImmutableListMiddleSubListGenerator extends TestStringListGenerator { @Override protected List<String> create(String[] elements) { String[] prefix = {"f", "g"}; String[] suffix = {"h", "i"}; String[] all = new String[2 + elements.length + 2]; System.arraycopy(prefix, 0, all, 0, 2); System.arraycopy(elements, 0, all, 2, elements.length); System.arraycopy(suffix, 0, all, 2 + elements.length, 2); return ImmutableList.copyOf(all) .subList(2, elements.length + 2); } } private abstract static class TestUnhashableListGenerator extends TestUnhashableCollectionGenerator<List<UnhashableObject>> implements TestListGenerator<UnhashableObject> { } public static class UnhashableElementsImmutableListGenerator extends TestUnhashableListGenerator { @Override public List<UnhashableObject> create(UnhashableObject[] elements) { return ImmutableList.copyOf(elements); } } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.BiMap; import com.google.common.collect.testing.AbstractTester; import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.MapTestSuiteBuilder; import com.google.common.collect.testing.OneSizeTestContainerGenerator; import com.google.common.collect.testing.PerCollectionSizeTestSuiteBuilder; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.SetTestSuiteBuilder; import com.google.common.collect.testing.TestMapGenerator; 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 com.google.common.collect.testing.features.MapFeature; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Creates, based on your criteria, a JUnit test suite that exhaustively tests a {@code BiMap} * implementation. * * @author Louis Wasserman */ @GwtCompatible public class BiMapTestSuiteBuilder<K, V> extends PerCollectionSizeTestSuiteBuilder<BiMapTestSuiteBuilder<K, V>, TestBiMapGenerator<K, V>, BiMap<K, V>, Map.Entry<K, V>> { public static <K, V> BiMapTestSuiteBuilder<K, V> using(TestBiMapGenerator<K, V> generator) { return new BiMapTestSuiteBuilder<K, V>().usingGenerator(generator); } @Override protected List<Class<? extends AbstractTester>> getTesters() { List<Class<? extends AbstractTester>> testers = new ArrayList<Class<? extends AbstractTester>>(); testers.add(BiMapPutTester.class); testers.add(BiMapInverseTester.class); testers.add(BiMapRemoveTester.class); testers.add(BiMapClearTester.class); return testers; } enum NoRecurse implements Feature<Void> { INVERSE; @Override public Set<Feature<? super Void>> getImpliedFeatures() { return Collections.emptySet(); } } @Override protected List<TestSuite> createDerivedSuites( FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>>> parentBuilder) { List<TestSuite> derived = super.createDerivedSuites(parentBuilder); // TODO(cpovirk): consider using this approach (derived suites instead of extension) in // ListTestSuiteBuilder, etc.? derived.add(MapTestSuiteBuilder .using(new MapGenerator<K, V>(parentBuilder.getSubjectGenerator())) .withFeatures(parentBuilder.getFeatures()) .named(parentBuilder.getName() + " [Map]") .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); /* * TODO(cpovirk): the Map tests duplicate most of this effort by using a * CollectionTestSuiteBuilder on values(). It would be nice to avoid that */ derived.add(SetTestSuiteBuilder .using(new BiMapValueSetGenerator<K, V>(parentBuilder.getSubjectGenerator())) .withFeatures(computeValuesSetFeatures(parentBuilder.getFeatures())) .named(parentBuilder.getName() + " values [Set]") .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); if (!parentBuilder.getFeatures().contains(NoRecurse.INVERSE)) { derived.add(BiMapTestSuiteBuilder .using(new InverseBiMapGenerator<K, V>(parentBuilder.getSubjectGenerator())) .withFeatures(computeInverseFeatures(parentBuilder.getFeatures())) .named(parentBuilder.getName() + " inverse") .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); } return derived; } private static Set<Feature<?>> computeInverseFeatures(Set<Feature<?>> mapFeatures) { Set<Feature<?>> inverseFeatures = new HashSet<Feature<?>>(mapFeatures); boolean nullKeys = inverseFeatures.remove(MapFeature.ALLOWS_NULL_KEYS); boolean nullValues = inverseFeatures.remove(MapFeature.ALLOWS_NULL_VALUES); if (nullKeys) { inverseFeatures.add(MapFeature.ALLOWS_NULL_VALUES); } if (nullValues) { inverseFeatures.add(MapFeature.ALLOWS_NULL_KEYS); } inverseFeatures.add(NoRecurse.INVERSE); inverseFeatures.remove(CollectionFeature.KNOWN_ORDER); return inverseFeatures; } // TODO(user): can we eliminate the duplication from MapTestSuiteBuilder here? private static Set<Feature<?>> computeValuesSetFeatures( Set<Feature<?>> mapFeatures) { Set<Feature<?>> valuesCollectionFeatures = computeCommonDerivedCollectionFeatures(mapFeatures); valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES); if (mapFeatures.contains(MapFeature.ALLOWS_NULL_VALUES)) { valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_VALUES); } return valuesCollectionFeatures; } private static Set<Feature<?>> computeCommonDerivedCollectionFeatures( Set<Feature<?>> mapFeatures) { Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>(); if (mapFeatures.contains(MapFeature.SUPPORTS_REMOVE)) { derivedFeatures.add(CollectionFeature.SUPPORTS_REMOVE); derivedFeatures.add(CollectionFeature.SUPPORTS_REMOVE_ALL); derivedFeatures.add(CollectionFeature.SUPPORTS_RETAIN_ALL); } if (mapFeatures.contains(MapFeature.SUPPORTS_CLEAR)) { derivedFeatures.add(CollectionFeature.SUPPORTS_CLEAR); } if (mapFeatures.contains(MapFeature.REJECTS_DUPLICATES_AT_CREATION)) { derivedFeatures.add(CollectionFeature.REJECTS_DUPLICATES_AT_CREATION); } // add the intersection of CollectionSize.values() and mapFeatures for (CollectionSize size : CollectionSize.values()) { if (mapFeatures.contains(size)) { derivedFeatures.add(size); } } return derivedFeatures; } private static class MapGenerator<K, V> implements TestMapGenerator<K, V> { private final OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>> generator; public MapGenerator( OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>> oneSizeTestContainerGenerator) { this.generator = oneSizeTestContainerGenerator; } @Override public SampleElements<Map.Entry<K, V>> samples() { return generator.samples(); } @Override public Map<K, V> create(Object... elements) { return generator.create(elements); } @Override public Map.Entry<K, V>[] createArray(int length) { return generator.createArray(length); } @Override public Iterable<Map.Entry<K, V>> order(List<Map.Entry<K, V>> insertionOrder) { return generator.order(insertionOrder); } @SuppressWarnings("unchecked") @Override public K[] createKeyArray(int length) { return (K[]) new Object[length]; } @SuppressWarnings("unchecked") @Override public V[] createValueArray(int length) { return (V[]) new Object[length]; } } private static class InverseBiMapGenerator<K, V> implements TestBiMapGenerator<V, K> { private final OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>> generator; public InverseBiMapGenerator( OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>> oneSizeTestContainerGenerator) { this.generator = oneSizeTestContainerGenerator; } @Override public SampleElements<Map.Entry<V, K>> samples() { SampleElements<Entry<K, V>> samples = generator.samples(); return new SampleElements<Map.Entry<V, K>>(reverse(samples.e0), reverse(samples.e1), reverse(samples.e2), reverse(samples.e3), reverse(samples.e4)); } private Map.Entry<V, K> reverse(Map.Entry<K, V> entry) { return Helpers.mapEntry(entry.getValue(), entry.getKey()); } @SuppressWarnings("unchecked") @Override public BiMap<V, K> create(Object... elements) { Entry[] entries = new Entry[elements.length]; for (int i = 0; i < elements.length; i++) { entries[i] = reverse((Entry<K, V>) elements[i]); } return generator.create((Object[]) entries).inverse(); } @SuppressWarnings("unchecked") @Override public Map.Entry<V, K>[] createArray(int length) { return new Entry[length]; } @Override public Iterable<Entry<V, K>> order(List<Entry<V, K>> insertionOrder) { return insertionOrder; } @SuppressWarnings("unchecked") @Override public V[] createKeyArray(int length) { return (V[]) new Object[length]; } @SuppressWarnings("unchecked") @Override public K[] createValueArray(int length) { return (K[]) new Object[length]; } } private static class BiMapValueSetGenerator<K, V> implements TestSetGenerator<V> { private final OneSizeTestContainerGenerator<BiMap<K, V>, Map.Entry<K, V>> mapGenerator; private final SampleElements<V> samples; public BiMapValueSetGenerator( OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>> mapGenerator) { this.mapGenerator = mapGenerator; final SampleElements<Map.Entry<K, V>> mapSamples = this.mapGenerator.samples(); this.samples = new SampleElements<V>( mapSamples.e0.getValue(), mapSamples.e1.getValue(), mapSamples.e2.getValue(), mapSamples.e3.getValue(), mapSamples.e4.getValue()); } @Override public SampleElements<V> samples() { return samples; } @Override public Set<V> create(Object... elements) { @SuppressWarnings("unchecked") V[] valuesArray = (V[]) elements; // Start with a suitably shaped collection of entries Collection<Map.Entry<K, V>> originalEntries = mapGenerator.getSampleElements(elements.length); // Create a copy of that, with the desired value for each value Collection<Map.Entry<K, V>> entries = new ArrayList<Entry<K, V>>(elements.length); int i = 0; for (Map.Entry<K, V> entry : originalEntries) { entries.add(Helpers.mapEntry(entry.getKey(), valuesArray[i++])); } return mapGenerator.create(entries.toArray()).values(); } @Override public V[] createArray(int length) { final V[] vs = ((TestBiMapGenerator<K, V>) mapGenerator.getInnerGenerator()) .createValueArray(length); return vs; } @Override public Iterable<V> order(List<V> insertionOrder) { return insertionOrder; } } }
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.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 com.google.common.annotations.GwtCompatible; 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.Sets; import com.google.common.collect.testing.TestCollectionGenerator; import com.google.common.collect.testing.TestCollidingSetGenerator; 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 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 Comparator<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)); } }
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.lang.reflect.Method; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; /** * 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 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}) 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 /** * Returns {@link Method} instances for the {@code setCount()} tests that * assume multisets support duplicates so that the test of {@code * Multisets.forSet()} can suppress them. */ public static List<Method> getSetCountDuplicateInitializingMethods() { return Arrays.asList( getMethod("testSetCount_threeToThree_removeSupported"), getMethod("testSetCount_threeToZero_supported"), getMethod("testSetCount_threeToOne_supported")); } private static Method getMethod(String methodName) { return Platform.getMethod(AbstractMultisetSetCountTester.class, methodName); } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.Multiset; import com.google.common.collect.testing.AnEnum; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.SampleElements.Enums; import java.util.Collections; import java.util.List; /** * An abstract {@code TestMultisetGenerator} for generating multisets containing * enum values. * * @author Jared Levy */ @GwtCompatible public abstract class TestEnumMultisetGenerator implements TestMultisetGenerator<AnEnum> { @Override public SampleElements<AnEnum> samples() { return new Enums(); } @Override public Multiset<AnEnum> create(Object... elements) { AnEnum[] array = new AnEnum[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (AnEnum) e; } return create(array); } protected abstract Multiset<AnEnum> create(AnEnum[] elements); @Override public AnEnum[] createArray(int length) { return new AnEnum[length]; } /** * Sorts the enums according to their natural ordering. */ @Override public List<AnEnum> order(List<AnEnum> insertionOrder) { Collections.sort(insertionOrder); return insertionOrder; } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.Multiset; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.SampleElements.Strings; import java.util.List; /** * Create multisets of strings for tests. * * @author Jared Levy */ @GwtCompatible public abstract class TestStringMultisetGenerator implements TestMultisetGenerator<String> { @Override public SampleElements<String> samples() { return new Strings(); } @Override public Multiset<String> create(Object... elements) { String[] array = new String[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (String) e; } return create(array); } protected abstract Multiset<String> create(String[] elements); @Override public String[] createArray(int length) { return new String[length]; } /** Returns the original element list, unchanged. */ @Override public List<String> order(List<String> insertionOrder) { return insertionOrder; } }
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.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import java.util.Iterator; /** * Tester for {@code BiMap.remove}. * * @author Louis Wasserman */ @GwtCompatible public class BiMapRemoveTester<K, V> extends AbstractBiMapTester<K, V> { @SuppressWarnings("unchecked") @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemoveKeyRemovesFromInverse() { getMap().remove(samples.e0.getKey()); expectMissing(samples.e0); } @SuppressWarnings("unchecked") @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemoveKeyFromKeySetRemovesFromInverse() { getMap().keySet().remove(samples.e0.getKey()); expectMissing(samples.e0); } @SuppressWarnings("unchecked") @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemoveFromValuesRemovesFromInverse() { getMap().values().remove(samples.e0.getValue()); expectMissing(samples.e0); } @SuppressWarnings("unchecked") @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemoveFromInverseRemovesFromForward() { getMap().inverse().remove(samples.e0.getValue()); expectMissing(samples.e0); } @SuppressWarnings("unchecked") @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemoveFromInverseKeySetRemovesFromForward() { getMap().inverse().keySet().remove(samples.e0.getValue()); expectMissing(samples.e0); } @SuppressWarnings("unchecked") @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemoveFromInverseValuesRemovesFromInverse() { getMap().inverse().values().remove(samples.e0.getKey()); expectMissing(samples.e0); } @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testKeySetIteratorRemove() { int initialSize = getNumElements(); Iterator<K> iterator = getMap().keySet().iterator(); iterator.next(); iterator.remove(); assertEquals(initialSize - 1, getMap().size()); assertEquals(initialSize - 1, getMap().inverse().size()); } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.BiMap; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.Helpers; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map.Entry; /** * Skeleton for a tester of a {@code BiMap}. */ @GwtCompatible public abstract class AbstractBiMapTester<K, V> extends AbstractMapTester<K, V> { @Override protected BiMap<K, V> getMap() { return (BiMap<K, V>) super.getMap(); } static <K, V> Entry<V, K> reverseEntry(Entry<K, V> entry) { return Helpers.mapEntry(entry.getValue(), entry.getKey()); } @Override protected void expectContents(Collection<Entry<K, V>> expected) { super.expectContents(expected); List<Entry<V, K>> reversedEntries = new ArrayList<Entry<V, K>>(); for (Entry<K, V> entry : expected) { reversedEntries.add(reverseEntry(entry)); } Helpers.assertEqualIgnoringOrder(getMap().inverse().entrySet(), reversedEntries); for (Entry<K, V> entry : expected) { assertEquals("Wrong key for value " + entry.getValue(), entry.getKey(), getMap() .inverse() .get(entry.getValue())); } } @Override protected void expectMissing(Entry<K, V>... entries) { super.expectMissing(entries); for (Entry<K, V> entry : entries) { Entry<V, K> reversed = reverseEntry(entry); BiMap<V, K> inv = getMap().inverse(); assertFalse("Inverse should not contain entry " + reversed, inv.entrySet().contains(entry)); assertFalse("Inverse should not contain key " + entry.getValue(), inv.containsKey(entry.getValue())); assertFalse("Inverse should not contain value " + entry.getKey(), inv.containsValue(entry.getKey())); assertNull("Inverse should not return a mapping for key " + entry.getValue(), getMap().get(entry.getValue())); } } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.BoundType; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Multiset; import com.google.common.collect.SortedMultiset; import com.google.common.collect.testing.AbstractTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.Feature; import com.google.common.testing.SerializableTester; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Creates, based on your criteria, a JUnit test suite that exhaustively tests a * {@code SortedMultiset} implementation. * * <p><b>Warning</b>: expects that {@code E} is a String. * * @author Louis Wasserman */ @GwtCompatible public class SortedMultisetTestSuiteBuilder<E> extends MultisetTestSuiteBuilder<E> { public static <E> SortedMultisetTestSuiteBuilder<E> using( TestMultisetGenerator<E> generator) { SortedMultisetTestSuiteBuilder<E> result = new SortedMultisetTestSuiteBuilder<E>(); result.usingGenerator(generator); return result; } @Override public TestSuite createTestSuite() { TestSuite suite = super.createTestSuite(); for (TestSuite subSuite : createDerivedSuites(this)) { suite.addTest(subSuite); } return suite; } @Override protected List<Class<? extends AbstractTester>> getTesters() { List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters()); testers.add(MultisetNavigationTester.class); return testers; } /** * To avoid infinite recursion, test suites with these marker features won't * have derived suites created for them. */ enum NoRecurse implements Feature<Void> { SUBMULTISET, DESCENDING; @Override public Set<Feature<? super Void>> getImpliedFeatures() { return Collections.emptySet(); } } /** * Two bounds (from and to) define how to build a subMultiset. */ enum Bound { INCLUSIVE, EXCLUSIVE, NO_BOUND; } List<TestSuite> createDerivedSuites( SortedMultisetTestSuiteBuilder<E> parentBuilder) { List<TestSuite> derivedSuites = Lists.newArrayList(); if (!parentBuilder.getFeatures().contains(NoRecurse.DESCENDING)) { derivedSuites.add(createDescendingSuite(parentBuilder)); } if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) { derivedSuites.add(createReserializedSuite(parentBuilder)); } if (!parentBuilder.getFeatures().contains(NoRecurse.SUBMULTISET)) { derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.NO_BOUND, Bound.EXCLUSIVE)); derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.NO_BOUND, Bound.INCLUSIVE)); derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.NO_BOUND)); derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.EXCLUSIVE)); derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.INCLUSIVE)); derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.INCLUSIVE, Bound.NO_BOUND)); derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.INCLUSIVE, Bound.EXCLUSIVE)); derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.INCLUSIVE, Bound.INCLUSIVE)); } return derivedSuites; } private TestSuite createSubMultisetSuite( SortedMultisetTestSuiteBuilder<E> parentBuilder, final Bound from, final Bound to) { final TestMultisetGenerator<E> delegate = (TestMultisetGenerator<E>) parentBuilder.getSubjectGenerator(); Set<Feature<?>> features = new HashSet<Feature<?>>(); features.add(NoRecurse.SUBMULTISET); features.add(CollectionFeature.RESTRICTS_ELEMENTS); features.addAll(parentBuilder.getFeatures()); if (!features.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) { features.remove(CollectionFeature.SERIALIZABLE); } SortedMultiset<E> emptyMultiset = (SortedMultiset<E>) delegate.create(); final Comparator<? super E> comparator = emptyMultiset.comparator(); SampleElements<E> samples = delegate.samples(); @SuppressWarnings("unchecked") List<E> samplesList = Arrays.asList(samples.e0, samples.e1, samples.e2, samples.e3, samples.e4); Collections.sort(samplesList, comparator); final E firstInclusive = samplesList.get(0); final E lastInclusive = samplesList.get(samplesList.size() - 1); return SortedMultisetTestSuiteBuilder .using(new ForwardingTestMultisetGenerator<E>(delegate) { @Override public SortedMultiset<E> create(Object... entries) { @SuppressWarnings("unchecked") // we dangerously assume E is a string List<E> extremeValues = (List) getExtremeValues(); @SuppressWarnings("unchecked") // map generators must past entry objects List<E> normalValues = (List) Arrays.asList(entries); // prepare extreme values to be filtered out of view Collections.sort(extremeValues, comparator); E firstExclusive = extremeValues.get(1); E lastExclusive = extremeValues.get(2); if (from == Bound.NO_BOUND) { extremeValues.remove(0); extremeValues.remove(0); } if (to == Bound.NO_BOUND) { extremeValues.remove(extremeValues.size() - 1); extremeValues.remove(extremeValues.size() - 1); } // the regular values should be visible after filtering List<E> allEntries = new ArrayList<E>(); allEntries.addAll(extremeValues); allEntries.addAll(normalValues); SortedMultiset<E> multiset = (SortedMultiset<E>) delegate.create(allEntries.toArray()); // call the smallest subMap overload that filters out the extreme // values if (from == Bound.INCLUSIVE) { multiset = multiset.tailMultiset(firstInclusive, BoundType.CLOSED); } else if (from == Bound.EXCLUSIVE) { multiset = multiset.tailMultiset(firstExclusive, BoundType.OPEN); } if (to == Bound.INCLUSIVE) { multiset = multiset.headMultiset(lastInclusive, BoundType.CLOSED); } else if (to == Bound.EXCLUSIVE) { multiset = multiset.headMultiset(lastExclusive, BoundType.OPEN); } return multiset; } }) .named(parentBuilder.getName() + " subMultiset " + from + "-" + to) .withFeatures(features) .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite(); } /** * Returns an array of four bogus elements that will always be too high or too * low for the display. This includes two values for each extreme. * * <p> * This method (dangerously) assume that the strings {@code "!! a"} and * {@code "~~ z"} will work for this purpose, which may cause problems for * navigable maps with non-string or unicode generators. */ private List<String> getExtremeValues() { List<String> result = new ArrayList<String>(); result.add("!! a"); result.add("!! b"); result.add("~~ y"); result.add("~~ z"); return result; } private TestSuite createDescendingSuite( SortedMultisetTestSuiteBuilder<E> parentBuilder) { final TestMultisetGenerator<E> delegate = (TestMultisetGenerator<E>) parentBuilder.getSubjectGenerator(); Set<Feature<?>> features = new HashSet<Feature<?>>(); features.add(NoRecurse.DESCENDING); features.addAll(parentBuilder.getFeatures()); if (!features.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) { features.remove(CollectionFeature.SERIALIZABLE); } return SortedMultisetTestSuiteBuilder .using(new ForwardingTestMultisetGenerator<E>(delegate) { @Override public SortedMultiset<E> create(Object... entries) { return ((SortedMultiset<E>) super.create(entries)) .descendingMultiset(); } @Override public Iterable<E> order(List<E> insertionOrder) { return ImmutableList.copyOf(super.order(insertionOrder)).reverse(); } }) .named(parentBuilder.getName() + " descending") .withFeatures(features) .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite(); } private TestSuite createReserializedSuite( SortedMultisetTestSuiteBuilder<E> parentBuilder) { final TestMultisetGenerator<E> delegate = (TestMultisetGenerator<E>) parentBuilder.getSubjectGenerator(); Set<Feature<?>> features = new HashSet<Feature<?>>(); features.addAll(parentBuilder.getFeatures()); features.remove(CollectionFeature.SERIALIZABLE); features.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS); return SortedMultisetTestSuiteBuilder .using(new ForwardingTestMultisetGenerator<E>(delegate) { @Override public SortedMultiset<E> create(Object... entries) { return SerializableTester.reserialize(((SortedMultiset<E>) super.create(entries))); } }) .named(parentBuilder.getName() + " reserialized") .withFeatures(features) .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite(); } private static class ForwardingTestMultisetGenerator<E> implements TestMultisetGenerator<E> { private final TestMultisetGenerator<E> delegate; ForwardingTestMultisetGenerator(TestMultisetGenerator<E> delegate) { this.delegate = delegate; } @Override public SampleElements<E> samples() { return delegate.samples(); } @Override public E[] createArray(int length) { return delegate.createArray(length); } @Override public Iterable<E> order(List<E> insertionOrder) { return delegate.order(insertionOrder); } @Override public Multiset<E> create(Object... elements) { return delegate.create(elements); } } }
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.google; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; import static junit.framework.TestCase.fail; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.LinkedHashMultiset; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multiset; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Set; /** * A series of tests that support asserting that collections cannot be * modified, either through direct or indirect means. * * @author Robert Konigsberg */ @GwtCompatible public class UnmodifiableCollectionTests { public static void assertMapEntryIsUnmodifiable(Entry<?, ?> entry) { try { entry.setValue(null); fail("setValue on unmodifiable Map.Entry succeeded"); } catch (UnsupportedOperationException expected) { } } /** * Verifies that an Iterator is unmodifiable. * * <p>This test only works with iterators that iterate over a finite set. */ public static void assertIteratorIsUnmodifiable(Iterator<?> iterator) { while (iterator.hasNext()) { iterator.next(); try { iterator.remove(); fail("Remove on unmodifiable iterator succeeded"); } catch (UnsupportedOperationException expected) { } } } /** * Asserts that two iterators contain elements in tandem. * * <p>This test only works with iterators that iterate over a finite set. */ public static void assertIteratorsInOrder( Iterator<?> expectedIterator, Iterator<?> actualIterator) { int i = 0; while (expectedIterator.hasNext()) { Object expected = expectedIterator.next(); assertTrue( "index " + i + " expected <" + expected + "., actual is exhausted", actualIterator.hasNext()); Object actual = actualIterator.next(); assertEquals("index " + i, expected, actual); i++; } if (actualIterator.hasNext()) { fail("index " + i + ", expected is exhausted, actual <" + actualIterator.next() + ">"); } } /** * Verifies that a collection is immutable. * * <p>A collection is considered immutable if: * <ol> * <li>All its mutation methods result in UnsupportedOperationException, and * do not change the underlying contents. * <li>All methods that return objects that can indirectly mutate the * collection throw UnsupportedOperationException when those mutators * are called. * </ol> * * @param collection the presumed-immutable collection * @param sampleElement an element of the same type as that contained by * {@code collection}. {@code collection} may or may not have {@code * sampleElement} as a member. */ public static <E> void assertCollectionIsUnmodifiable( Collection<E> collection, E sampleElement) { Collection<E> siblingCollection = new ArrayList<E>(); siblingCollection.add(sampleElement); Collection<E> copy = new ArrayList<E>(); copy.addAll(collection); try { collection.add(sampleElement); fail("add succeeded on unmodifiable collection"); } catch (UnsupportedOperationException expected) { } assertCollectionsAreEquivalent(copy, collection); try { collection.addAll(siblingCollection); fail("addAll succeeded on unmodifiable collection"); } catch (UnsupportedOperationException expected) { } assertCollectionsAreEquivalent(copy, collection); try { collection.clear(); fail("clear succeeded on unmodifiable collection"); } catch (UnsupportedOperationException expected) { } assertCollectionsAreEquivalent(copy, collection); assertIteratorIsUnmodifiable(collection.iterator()); assertCollectionsAreEquivalent(copy, collection); try { collection.remove(sampleElement); fail("remove succeeded on unmodifiable collection"); } catch (UnsupportedOperationException expected) { } assertCollectionsAreEquivalent(copy, collection); try { collection.removeAll(siblingCollection); fail("removeAll succeeded on unmodifiable collection"); } catch (UnsupportedOperationException expected) { } assertCollectionsAreEquivalent(copy, collection); try { collection.retainAll(siblingCollection); fail("retainAll succeeded on unmodifiable collection"); } catch (UnsupportedOperationException expected) { } assertCollectionsAreEquivalent(copy, collection); } /** * Verifies that a set is immutable. * * <p>A set is considered immutable if: * <ol> * <li>All its mutation methods result in UnsupportedOperationException, and * do not change the underlying contents. * <li>All methods that return objects that can indirectly mutate the * set throw UnsupportedOperationException when those mutators * are called. * </ol> * * @param set the presumed-immutable set * @param sampleElement an element of the same type as that contained by * {@code set}. {@code set} may or may not have {@code sampleElement} as a * member. */ public static <E> void assertSetIsUnmodifiable( Set<E> set, E sampleElement) { assertCollectionIsUnmodifiable(set, sampleElement); } /** * Verifies that a multiset is immutable. * * <p>A multiset is considered immutable if: * <ol> * <li>All its mutation methods result in UnsupportedOperationException, and * do not change the underlying contents. * <li>All methods that return objects that can indirectly mutate the * multiset throw UnsupportedOperationException when those mutators * are called. * </ol> * * @param multiset the presumed-immutable multiset * @param sampleElement an element of the same type as that contained by * {@code multiset}. {@code multiset} may or may not have {@code * sampleElement} as a member. */ public static <E> void assertMultisetIsUnmodifiable(Multiset<E> multiset, final E sampleElement) { Multiset<E> copy = LinkedHashMultiset.create(multiset); assertCollectionsAreEquivalent(multiset, copy); // Multiset is a collection, so we can use all those tests. assertCollectionIsUnmodifiable(multiset, sampleElement); assertCollectionsAreEquivalent(multiset, copy); try { multiset.add(sampleElement, 2); fail("add(Object, int) succeeded on unmodifiable collection"); } catch (UnsupportedOperationException expected) { } assertCollectionsAreEquivalent(multiset, copy); try { multiset.remove(sampleElement, 2); fail("remove(Object, int) succeeded on unmodifiable collection"); } catch (UnsupportedOperationException expected) { } assertCollectionsAreEquivalent(multiset, copy); assertCollectionsAreEquivalent(multiset, copy); assertSetIsUnmodifiable(multiset.elementSet(), sampleElement); assertCollectionsAreEquivalent(multiset, copy); assertSetIsUnmodifiable( multiset.entrySet(), new Multiset.Entry<E>() { @Override public int getCount() { return 1; } @Override public E getElement() { return sampleElement; } }); assertCollectionsAreEquivalent(multiset, copy); } /** * Verifies that a multimap is immutable. * * <p>A multimap is considered immutable if: * <ol> * <li>All its mutation methods result in UnsupportedOperationException, and * do not change the underlying contents. * <li>All methods that return objects that can indirectly mutate the * multimap throw UnsupportedOperationException when those mutators * </ol> * * @param multimap the presumed-immutable multimap * @param sampleKey a key of the same type as that contained by * {@code multimap}. {@code multimap} may or may not have {@code sampleKey} as * a key. * @param sampleValue a key of the same type as that contained by * {@code multimap}. {@code multimap} may or may not have {@code sampleValue} * as a key. */ public static <K, V> void assertMultimapIsUnmodifiable( Multimap<K, V> multimap, final K sampleKey, final V sampleValue) { List<Entry<K, V>> originalEntries = Collections.unmodifiableList(Lists.newArrayList(multimap.entries())); assertMultimapRemainsUnmodified(multimap, originalEntries); Collection<V> sampleValueAsCollection = Collections.singleton(sampleValue); // Test #clear() try { multimap.clear(); fail("clear succeeded on unmodifiable multimap"); } catch (UnsupportedOperationException expected) { } assertMultimapRemainsUnmodified(multimap, originalEntries); // Test asMap().entrySet() assertSetIsUnmodifiable( multimap.asMap().entrySet(), Maps.immutableEntry(sampleKey, sampleValueAsCollection)); // Test #values() assertMultimapRemainsUnmodified(multimap, originalEntries); if (!multimap.isEmpty()) { Collection<V> values = multimap.asMap().entrySet().iterator().next().getValue(); assertCollectionIsUnmodifiable(values, sampleValue); } // Test #entries() assertCollectionIsUnmodifiable( multimap.entries(), Maps.immutableEntry(sampleKey, sampleValue)); assertMultimapRemainsUnmodified(multimap, originalEntries); // Iterate over every element in the entry set for (Entry<K, V> entry : multimap.entries()) { assertMapEntryIsUnmodifiable(entry); } assertMultimapRemainsUnmodified(multimap, originalEntries); // Test #keys() assertMultisetIsUnmodifiable(multimap.keys(), sampleKey); assertMultimapRemainsUnmodified(multimap, originalEntries); // Test #keySet() assertSetIsUnmodifiable(multimap.keySet(), sampleKey); assertMultimapRemainsUnmodified(multimap, originalEntries); // Test #get() if (!multimap.isEmpty()) { K key = multimap.keySet().iterator().next(); assertCollectionIsUnmodifiable(multimap.get(key), sampleValue); assertMultimapRemainsUnmodified(multimap, originalEntries); } // Test #put() try { multimap.put(sampleKey, sampleValue); fail("put succeeded on unmodifiable multimap"); } catch (UnsupportedOperationException expected) { } assertMultimapRemainsUnmodified(multimap, originalEntries); // Test #putAll(K, Collection<V>) try { multimap.putAll(sampleKey, sampleValueAsCollection); fail("putAll(K, Iterable) succeeded on unmodifiable multimap"); } catch (UnsupportedOperationException expected) { } assertMultimapRemainsUnmodified(multimap, originalEntries); // Test #putAll(Multimap<K, V>) Multimap<K, V> multimap2 = ArrayListMultimap.create(); multimap2.put(sampleKey, sampleValue); try { multimap.putAll(multimap2); fail("putAll(Multimap<K, V>) succeeded on unmodifiable multimap"); } catch (UnsupportedOperationException expected) { } assertMultimapRemainsUnmodified(multimap, originalEntries); // Test #remove() try { multimap.remove(sampleKey, sampleValue); fail("remove succeeded on unmodifiable multimap"); } catch (UnsupportedOperationException expected) { } assertMultimapRemainsUnmodified(multimap, originalEntries); // Test #removeAll() try { multimap.removeAll(sampleKey); fail("removeAll succeeded on unmodifiable multimap"); } catch (UnsupportedOperationException expected) { } assertMultimapRemainsUnmodified(multimap, originalEntries); // Test #replaceValues() try { multimap.replaceValues(sampleKey, sampleValueAsCollection); fail("replaceValues succeeded on unmodifiable multimap"); } catch (UnsupportedOperationException expected) { } assertMultimapRemainsUnmodified(multimap, originalEntries); // Test #asMap() try { multimap.asMap().remove(sampleKey); fail("asMap().remove() succeeded on unmodifiable multimap"); } catch (UnsupportedOperationException expected) { } assertMultimapRemainsUnmodified(multimap, originalEntries); if (!multimap.isEmpty()) { K presentKey = multimap.keySet().iterator().next(); try { multimap.asMap().get(presentKey).remove(sampleValue); fail("asMap().get().remove() succeeded on unmodifiable multimap"); } catch (UnsupportedOperationException expected) { } assertMultimapRemainsUnmodified(multimap, originalEntries); try { multimap.asMap().values().iterator().next().remove(sampleValue); fail("asMap().values().iterator().next().remove() succeeded on " + "unmodifiable multimap"); } catch (UnsupportedOperationException expected) { } try { ((Collection<?>) multimap.asMap().values().toArray()[0]).clear(); fail("asMap().values().toArray()[0].clear() succeeded on " + "unmodifiable multimap"); } catch (UnsupportedOperationException expected) { } } assertCollectionIsUnmodifiable(multimap.values(), sampleValue); assertMultimapRemainsUnmodified(multimap, originalEntries); } private static <E> void assertCollectionsAreEquivalent( Collection<E> expected, Collection<E> actual) { assertIteratorsInOrder(expected.iterator(), actual.iterator()); } private static <K, V> void assertMultimapRemainsUnmodified( Multimap<K, V> expected, List<Entry<K, V>> actual) { assertIteratorsInOrder( expected.entries().iterator(), actual.iterator()); } }
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.SUPPORTS_ADD; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static java.util.Collections.nCopies; 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 conditional {@code setCount()} operations on * a multiset. Can't be invoked directly; please see * {@link MultisetTestSuiteBuilder}. * * @author Chris Povirk */ @GwtCompatible public class MultisetSetCountConditionallyTester<E> extends AbstractMultisetSetCountTester<E> { @Override void setCountCheckReturnValue(E element, int count) { assertTrue( "setCount() with the correct expected present count should return true", setCount(element, count)); } @Override void setCountNoCheckReturnValue(E element, int count) { setCount(element, count); } private boolean setCount(E element, int count) { return getMultiset().setCount(element, getMultiset().count(element), count); } private void assertSetCountNegativeOldCount() { try { getMultiset().setCount(samples.e3, -1, 1); fail("calling setCount() with a negative oldCount should throw " + "IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } // Negative oldCount. @CollectionFeature.Require(SUPPORTS_ADD) public void testSetCountConditional_negativeOldCount_addSupported() { assertSetCountNegativeOldCount(); } @CollectionFeature.Require(absent = SUPPORTS_ADD) public void testSetCountConditional_negativeOldCount_addUnsupported() { try { assertSetCountNegativeOldCount(); } catch (UnsupportedOperationException tolerated) { } } // Incorrect expected present count. @CollectionFeature.Require(SUPPORTS_ADD) public void testSetCountConditional_oldCountTooLarge() { assertFalse("setCount() with a too-large oldCount should return false", getMultiset().setCount(samples.e0, 2, 3)); expectUnchanged(); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(SUPPORTS_ADD) public void testSetCountConditional_oldCountTooSmallZero() { assertFalse("setCount() with a too-small oldCount should return false", getMultiset().setCount(samples.e0, 0, 2)); expectUnchanged(); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require(SUPPORTS_ADD) public void testSetCountConditional_oldCountTooSmallNonzero() { initThreeCopies(); assertFalse("setCount() with a too-small oldCount should return false", getMultiset().setCount(samples.e0, 1, 5)); expectContents(nCopies(3, samples.e0)); } /* * TODO: test that unmodifiable multisets either throw UOE or return false * when both are valid options. Currently we test the UOE cases and the * return-false cases but not their intersection */ }
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; import java.util.Collection; import java.util.List; import java.util.Map; /** * To be implemented by test generators of things that can contain * elements. Such things include both {@link Collection} and {@link Map}; since * there isn't an established collective noun that encompasses both of these, * 'container' is used. * * <p>This class is GWT compatible. * * @author George van den Driessche */ public interface TestContainerGenerator<T, E> { /** * Returns the sample elements that this generate populates its container * with. */ SampleElements<E> samples(); /** * Creates a new container containing the given elements. TODO: would be nice * to figure out how to use E... or E[] as a parameter type, but this doesn't * seem to work because Java creates an array of the erased type. */ T create(Object ... elements); /** * Helper method to create an array of the appropriate type used by this * generator. The returned array will contain only nulls. */ E[] createArray(int length); /** * Returns the iteration ordering of elements, given the order in * which they were added to the container. This method may return the * original list unchanged, the original list modified in place, or a * different list. * * <p>This method runs only when {@link * com.google.common.collect.testing.features.CollectionFeature#KNOWN_ORDER} * is specified when creating the test suite. It should never run when testing * containers such as {@link java.util.HashSet}, which have a * non-deterministic iteration order. */ Iterable<E> order(List<E> insertionOrder); }
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.common.collect.testing.SampleElements.Unhashables; import java.util.Collection; import java.util.List; /** * Creates collections containing unhashable sample elements, to be tested. * * <p>This class is GWT compatible. * * @author Regina O'Dell */ public abstract class TestUnhashableCollectionGenerator<T extends Collection<UnhashableObject>> implements TestCollectionGenerator<UnhashableObject> { @Override public SampleElements<UnhashableObject> samples() { return new Unhashables(); } @Override public T create(Object... elements) { UnhashableObject[] array = createArray(elements.length); int i = 0; for (Object e : elements) { array[i++] = (UnhashableObject) e; } return create(array); } /** * Creates a new collection containing the given elements; implement this * method instead of {@link #create(Object...)}. */ protected abstract T create(UnhashableObject[] elements); @Override public UnhashableObject[] createArray(int length) { return new UnhashableObject[length]; } @Override public Iterable<UnhashableObject> order( List<UnhashableObject> insertionOrder) { return insertionOrder; } }
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; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; /** * Base class for map testers. * * <p>This class is GWT compatible. * * TODO: see how much of this is actually needed once Map testers are written. * (It was cloned from AbstractCollectionTester.) * * @param <K> the key type of the map to be tested. * @param <V> the value type of the map to be tested. * * @author George van den Driessche */ public abstract class AbstractMapTester<K, V> extends AbstractContainerTester<Map<K, V>, Map.Entry<K, V>> { protected Map<K, V> getMap() { return container; } @Override public void setUp() throws Exception { super.setUp(); samples = this.getSubjectGenerator().samples(); resetMap(); } @Override protected Collection<Map.Entry<K, V>> actualContents() { return getMap().entrySet(); } /** @see AbstractContainerTester#resetContainer() */ protected void resetMap() { resetContainer(); } protected void expectMissingKeys(K... elements) { for (K element : elements) { assertFalse("Should not contain key " + element, getMap().containsKey(element)); } } protected void expectMissingValues(V... elements) { for (V element : elements) { assertFalse("Should not contain value " + element, getMap().containsValue(element)); } } /** * @return an array of the proper size with {@code null} as the key of the * middle element. */ protected Map.Entry<K, V>[] createArrayWithNullKey() { Map.Entry<K, V>[] array = createSamplesArray(); final int nullKeyLocation = getNullLocation(); final Map.Entry<K, V> oldEntry = array[nullKeyLocation]; array[nullKeyLocation] = entry(null, oldEntry.getValue()); return array; } protected V getValueForNullKey() { return getEntryNullReplaces().getValue(); } protected K getKeyForNullValue() { return getEntryNullReplaces().getKey(); } private Entry<K, V> getEntryNullReplaces() { Iterator<Entry<K, V>> entries = getSampleElements().iterator(); for (int i = 0; i < getNullLocation(); i++) { entries.next(); } return entries.next(); } /** * @return an array of the proper size with {@code null} as the value of the * middle element. */ protected Map.Entry<K, V>[] createArrayWithNullValue() { Map.Entry<K, V>[] array = createSamplesArray(); final int nullValueLocation = getNullLocation(); final Map.Entry<K, V> oldEntry = array[nullValueLocation]; array[nullValueLocation] = entry(oldEntry.getKey(), null); return array; } protected void initMapWithNullKey() { resetMap(createArrayWithNullKey()); } protected void initMapWithNullValue() { resetMap(createArrayWithNullValue()); } /** * Equivalent to {@link #expectMissingKeys(Object[]) expectMissingKeys} * {@code (null)} * except that the call to {@code contains(null)} is permitted to throw a * {@code NullPointerException}. * @param message message to use upon assertion failure */ protected void expectNullKeyMissingWhenNullKeysUnsupported(String message) { try { assertFalse(message, getMap().containsKey(null)); } catch (NullPointerException tolerated) { // Tolerated } } /** * Equivalent to {@link #expectMissingValues(Object[]) expectMissingValues} * {@code (null)} * except that the call to {@code contains(null)} is permitted to throw a * {@code NullPointerException}. * @param message message to use upon assertion failure */ protected void expectNullValueMissingWhenNullValuesUnsupported( String message) { try { assertFalse(message, getMap().containsValue(null)); } catch (NullPointerException tolerated) { // Tolerated } } @SuppressWarnings("unchecked") @Override protected MinimalCollection<Map.Entry<K, V>> createDisjointCollection() { return MinimalCollection.of(samples.e3, samples.e4); } protected int getNumEntries() { return getNumElements(); } protected Collection<Map.Entry<K, V>> getSampleEntries(int howMany) { return getSampleElements(howMany); } protected Collection<Map.Entry<K, V>> getSampleEntries() { return getSampleElements(); } @Override protected void expectMissing(Entry<K, V>... entries) { for (Entry<K, V> entry : entries) { assertFalse("Should not contain entry " + entry, actualContents().contains(entry)); assertFalse("Should not contain key " + entry.getKey(), getMap().containsKey(entry.getKey())); assertFalse("Should not contain value " + entry.getValue(), getMap().containsValue(entry.getValue())); assertNull("Should not return a mapping for key " + entry.getKey(), getMap().get(entry.getKey())); } } // This one-liner saves us from some ugly casts protected Entry<K, V> entry(K key, V value) { return Helpers.mapEntry(key, value); } @Override protected void expectContents(Collection<Entry<K, V>> expected) { // TODO: move this to invariant checks once the appropriate hook exists? super.expectContents(expected); for (Entry<K, V> entry : expected) { assertEquals("Wrong value for key " + entry.getKey(), entry.getValue(), getMap().get(entry.getKey())); } } protected final void expectReplacement(Entry<K, V> newEntry) { List<Entry<K, V>> expected = Helpers.copyToList(getSampleElements()); replaceValue(expected, newEntry); expectContents(expected); } private void replaceValue(List<Entry<K, V>> expected, Entry<K, V> newEntry) { for (ListIterator<Entry<K, V>> i = expected.listIterator(); i.hasNext();) { if (Helpers.equal(i.next().getKey(), newEntry.getKey())) { i.set(newEntry); return; } } throw new IllegalArgumentException(Platform.format( "key %s not found in entries %s", newEntry.getKey(), expected)); } /** * Wrapper for {@link Map#get(Object)} that forces the caller to pass in a key * of the same type as the map. Besides being slightly shorter than code that * uses {@link #getMap()}, it also ensures that callers don't pass an * {@link Entry} by mistake. */ protected V get(K key) { return getMap().get(key); } protected void resetMap(Entry<K, V>[] entries) { resetContainer(getSubjectGenerator().create((Object[]) entries)); } }
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; import java.util.Collection; /** * Creates collections, containing sample elements, to be tested. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ public interface TestCollectionGenerator<E> extends TestContainerGenerator<Collection<E>, E> { }
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.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.SetFeature; import com.google.common.collect.testing.testers.CollectionIteratorTester; import junit.framework.Test; import junit.framework.TestSuite; import java.io.Serializable; import java.lang.reflect.Method; import java.util.AbstractSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.CopyOnWriteArraySet; /** * Generates a test suite covering the {@link Set} implementations in the * {@link java.util} package. Can be subclassed to specify tests that should * be suppressed. * * @author Kevin Bourrillion */ public class TestsForSetsInJavaUtil { public static Test suite() { return new TestsForSetsInJavaUtil().allTests(); } public Test allTests() { TestSuite suite = new TestSuite("java.util Sets"); suite.addTest(testsForEmptySet()); suite.addTest(testsForSingletonSet()); suite.addTest(testsForHashSet()); suite.addTest(testsForLinkedHashSet()); suite.addTest(testsForEnumSet()); suite.addTest(testsForTreeSetNatural()); suite.addTest(testsForTreeSetWithComparator()); suite.addTest(testsForCopyOnWriteArraySet()); suite.addTest(testsForUnmodifiableSet()); suite.addTest(testsForCheckedSet()); suite.addTest(testsForAbstractSet()); suite.addTest(testsForBadlyCollidingHashSet()); return suite; } protected Collection<Method> suppressForEmptySet() { return Collections.emptySet(); } protected Collection<Method> suppressForSingletonSet() { return Collections.emptySet(); } protected Collection<Method> suppressForHashSet() { return Collections.emptySet(); } protected Collection<Method> suppressForLinkedHashSet() { return Collections.emptySet(); } protected Collection<Method> suppressForEnumSet() { return Collections.emptySet(); } protected Collection<Method> suppressForTreeSetNatural() { return Collections.emptySet(); } protected Collection<Method> suppressForTreeSetWithComparator() { return Collections.emptySet(); } protected Collection<Method> suppressForCopyOnWriteArraySet() { return Collections.singleton(CollectionIteratorTester .getIteratorKnownOrderRemoveSupportedMethod()); } protected Collection<Method> suppressForUnmodifiableSet() { return Collections.emptySet(); } protected Collection<Method> suppressForCheckedSet() { return Collections.emptySet(); } protected Collection<Method> suppressForAbstractSet() { return Collections.emptySet(); } public Test testsForEmptySet() { return SetTestSuiteBuilder .using(new TestStringSetGenerator() { @Override public Set<String> create(String[] elements) { return Collections.emptySet(); } }) .named("emptySet") .withFeatures( CollectionFeature.SERIALIZABLE, CollectionSize.ZERO) .suppressing(suppressForEmptySet()) .createTestSuite(); } public Test testsForSingletonSet() { return SetTestSuiteBuilder .using(new TestStringSetGenerator() { @Override public Set<String> create(String[] elements) { return Collections.singleton(elements[0]); } }) .named("singleton") .withFeatures( CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ONE) .suppressing(suppressForSingletonSet()) .createTestSuite(); } public Test testsForHashSet() { return SetTestSuiteBuilder .using(new TestStringSetGenerator() { @Override public Set<String> create(String[] elements) { return new HashSet<String>(MinimalCollection.of(elements)); } }) .named("HashSet") .withFeatures( SetFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionSize.ANY) .suppressing(suppressForHashSet()) .createTestSuite(); } public Test testsForLinkedHashSet() { return SetTestSuiteBuilder .using(new TestStringSetGenerator() { @Override public Set<String> create(String[] elements) { return new LinkedHashSet<String>(MinimalCollection.of(elements)); } }) .named("LinkedHashSet") .withFeatures( SetFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.KNOWN_ORDER, CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionSize.ANY) .suppressing(suppressForLinkedHashSet()) .createTestSuite(); } public Test testsForEnumSet() { return SetTestSuiteBuilder .using(new TestEnumSetGenerator() { @Override public Set<AnEnum> create(AnEnum[] elements) { return (elements.length == 0) ? EnumSet.noneOf(AnEnum.class) : EnumSet.copyOf(MinimalCollection.of(elements)); } }) .named("EnumSet") .withFeatures( SetFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.KNOWN_ORDER, CollectionFeature.RESTRICTS_ELEMENTS, CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionSize.ANY) .suppressing(suppressForEnumSet()) .createTestSuite(); } public Test testsForTreeSetNatural() { return SetTestSuiteBuilder .using(new TestStringSortedSetGenerator() { @Override public SortedSet<String> create(String[] elements) { return new TreeSet<String>(MinimalCollection.of(elements)); } }) .named("TreeSet, natural") .withFeatures( SetFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.KNOWN_ORDER, CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionSize.ANY) .suppressing(suppressForTreeSetNatural()) .createTestSuite(); } public Test testsForTreeSetWithComparator() { return SetTestSuiteBuilder .using(new TestStringSortedSetGenerator() { @Override public SortedSet<String> create(String[] elements) { SortedSet<String> set = new TreeSet<String>(arbitraryNullFriendlyComparator()); Collections.addAll(set, elements); return set; } }) .named("TreeSet, with comparator") .withFeatures( SetFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.KNOWN_ORDER, CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionSize.ANY) .suppressing(suppressForTreeSetWithComparator()) .createTestSuite(); } public Test testsForCopyOnWriteArraySet() { return SetTestSuiteBuilder .using(new TestStringSetGenerator() { @Override public Set<String> create(String[] elements) { return new CopyOnWriteArraySet<String>( MinimalCollection.of(elements)); } }) .named("CopyOnWriteArraySet") .withFeatures( SetFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY) .suppressing(suppressForCopyOnWriteArraySet()) .createTestSuite(); } public Test testsForUnmodifiableSet() { return SetTestSuiteBuilder .using(new TestStringSetGenerator() { @Override public Set<String> create(String[] elements) { Set<String> innerSet = new HashSet<String>(); Collections.addAll(innerSet, elements); return Collections.unmodifiableSet(innerSet); } }) .named("unmodifiableSet/HashSet") .withFeatures( CollectionFeature.NONE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForUnmodifiableSet()) .createTestSuite(); } public Test testsForCheckedSet() { return SetTestSuiteBuilder .using(new TestStringSetGenerator() { @Override public Set<String> create(String[] elements) { Set<String> innerSet = new HashSet<String>(); Collections.addAll(innerSet, elements); return Collections.checkedSet(innerSet, String.class); } }) .named("checkedSet/HashSet") .withFeatures( SetFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.RESTRICTS_ELEMENTS, CollectionSize.ANY) .suppressing(suppressForCheckedSet()) .createTestSuite(); } public Test testsForAbstractSet() { return SetTestSuiteBuilder .using(new TestStringSetGenerator () { @Override protected Set<String> create(String[] elements) { final String[] deduped = dedupe(elements); return new AbstractSet<String>() { @Override public int size() { return deduped.length; } @Override public Iterator<String> iterator() { return MinimalCollection.of(deduped).iterator(); } }; } }) .named("AbstractSet") .withFeatures( CollectionFeature.NONE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.KNOWN_ORDER, // in this case, anyway CollectionSize.ANY) .suppressing(suppressForAbstractSet()) .createTestSuite(); } public Test testsForBadlyCollidingHashSet() { return SetTestSuiteBuilder .using(new TestCollidingSetGenerator() { @Override public Set<Object> create(Object... elements) { return new HashSet<Object>(MinimalCollection.of(elements)); } }) .named("badly colliding HashSet") .withFeatures( SetFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.SEVERAL) .suppressing(suppressForHashSet()) .createTestSuite(); } private static String[] dedupe(String[] elements) { Set<String> tmp = new LinkedHashSet<String>(); Collections.addAll(tmp, elements); return tmp.toArray(new String[0]); } static <T> Comparator<T> arbitraryNullFriendlyComparator() { return new NullFriendlyComparator<T>(); } private static final class NullFriendlyComparator<T> implements Comparator<T>, Serializable { @Override public int compare(T left, T right) { return String.valueOf(left).compareTo(String.valueOf(right)); } } }
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; import com.google.common.collect.testing.testers.CollectionAddAllTester; import com.google.common.collect.testing.testers.CollectionAddTester; import com.google.common.collect.testing.testers.CollectionClearTester; import com.google.common.collect.testing.testers.CollectionContainsAllTester; import com.google.common.collect.testing.testers.CollectionContainsTester; import com.google.common.collect.testing.testers.CollectionCreationTester; import com.google.common.collect.testing.testers.CollectionEqualsTester; import com.google.common.collect.testing.testers.CollectionIsEmptyTester; import com.google.common.collect.testing.testers.CollectionIteratorTester; import com.google.common.collect.testing.testers.CollectionRemoveAllTester; import com.google.common.collect.testing.testers.CollectionRemoveTester; import com.google.common.collect.testing.testers.CollectionRetainAllTester; import com.google.common.collect.testing.testers.CollectionSerializationTester; import com.google.common.collect.testing.testers.CollectionSizeTester; import com.google.common.collect.testing.testers.CollectionToArrayTester; import com.google.common.collect.testing.testers.CollectionToStringTester; import junit.framework.TestSuite; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Abstract superclass of all test-suite builders for collection interfaces. * * @author George van den Driessche */ public abstract class AbstractCollectionTestSuiteBuilder< B extends AbstractCollectionTestSuiteBuilder<B, E>, E> extends PerCollectionSizeTestSuiteBuilder< B, TestCollectionGenerator<E>, Collection<E>, E> { // Class parameters must be raw. @SuppressWarnings("unchecked") @Override protected List<Class<? extends AbstractTester>> getTesters() { return Arrays.<Class<? extends AbstractTester>>asList( CollectionAddAllTester.class, CollectionAddTester.class, CollectionClearTester.class, CollectionContainsAllTester.class, CollectionContainsTester.class, CollectionCreationTester.class, CollectionEqualsTester.class, CollectionIsEmptyTester.class, CollectionIteratorTester.class, CollectionRemoveAllTester.class, CollectionRemoveTester.class, CollectionRetainAllTester.class, CollectionSerializationTester.class, CollectionSizeTester.class, CollectionToArrayTester.class, CollectionToStringTester.class ); } @Override protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder< ?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) { DerivedIteratorTestSuiteBuilder<?> iteratorTestSuiteBuilder = new DerivedIteratorTestSuiteBuilder<E>() .named(parentBuilder.getName()) .usingGenerator(parentBuilder.getSubjectGenerator()) .withFeatures(parentBuilder.getFeatures()); return Collections.singletonList( iteratorTestSuiteBuilder.createTestSuite()); } }
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; import static java.util.Collections.singleton; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Tests representing the contract of {@link Map}. Concrete subclasses of this * base class test conformance of concrete {@link Map} subclasses to that * contract. * * TODO: Descriptive assertion messages, with hints as to probable * fixes. * TODO: Add another constructor parameter indicating whether the * class under test is ordered, and check the order if so. * TODO: Refactor to share code with SetTestBuilder &c. * * <p>This class is GWT compatible. * * @param <K> the type of keys used by the maps under test * @param <V> the type of mapped values used the maps under test * * @author George van den Driessche */ public abstract class MapInterfaceTest<K, V> extends TestCase { /** A key type that is not assignable to any classes but Object. */ private static final class IncompatibleKeyType { @Override public String toString() { return "IncompatibleKeyType"; } } protected final boolean supportsPut; protected final boolean supportsRemove; protected final boolean supportsClear; protected final boolean allowsNullKeys; protected final boolean allowsNullValues; protected final boolean supportsIteratorRemove; /** * Creates a new, empty instance of the class under test. * * @return a new, empty map instance. * @throws UnsupportedOperationException if it's not possible to make an * empty instance of the class under test. */ protected abstract Map<K, V> makeEmptyMap() throws UnsupportedOperationException; /** * Creates a new, non-empty instance of the class under test. * * @return a new, non-empty map instance. * @throws UnsupportedOperationException if it's not possible to make a * non-empty instance of the class under test. */ protected abstract Map<K, V> makePopulatedMap() throws UnsupportedOperationException; /** * Creates a new key that is not expected to be found * in {@link #makePopulatedMap()}. * * @return a key. * @throws UnsupportedOperationException if it's not possible to make a key * that will not be found in the map. */ protected abstract K getKeyNotInPopulatedMap() throws UnsupportedOperationException; /** * Creates a new value that is not expected to be found * in {@link #makePopulatedMap()}. * * @return a value. * @throws UnsupportedOperationException if it's not possible to make a value * that will not be found in the map. */ protected abstract V getValueNotInPopulatedMap() throws UnsupportedOperationException; /** * Constructor that assigns {@code supportsIteratorRemove} the same value as * {@code supportsRemove}. */ protected MapInterfaceTest( boolean allowsNullKeys, boolean allowsNullValues, boolean supportsPut, boolean supportsRemove, boolean supportsClear) { this(allowsNullKeys, allowsNullValues, supportsPut, supportsRemove, supportsClear, supportsRemove); } /** * Constructor with an explicit {@code supportsIteratorRemove} parameter. */ protected MapInterfaceTest( boolean allowsNullKeys, boolean allowsNullValues, boolean supportsPut, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { this.supportsPut = supportsPut; this.supportsRemove = supportsRemove; this.supportsClear = supportsClear; this.allowsNullKeys = allowsNullKeys; this.allowsNullValues = allowsNullValues; this.supportsIteratorRemove = supportsIteratorRemove; } /** * Used by tests that require a map, but don't care whether it's * populated or not. * * @return a new map instance. */ protected Map<K, V> makeEitherMap() { try { return makePopulatedMap(); } catch (UnsupportedOperationException e) { return makeEmptyMap(); } } protected final boolean supportsValuesHashCode(Map<K, V> map) { // get the first non-null value Collection<V> values = map.values(); for (V value : values) { if (value != null) { try { value.hashCode(); } catch (Exception e) { return false; } return true; } } return true; } /** * Checks all the properties that should always hold of a map. Also calls * {@link #assertMoreInvariants} to check invariants that are peculiar to * specific implementations. * * @see #assertMoreInvariants * @param map the map to check. */ protected final void assertInvariants(Map<K, V> map) { Set<K> keySet = map.keySet(); Collection<V> valueCollection = map.values(); Set<Entry<K, V>> entrySet = map.entrySet(); assertEquals(map.size() == 0, map.isEmpty()); assertEquals(map.size(), keySet.size()); assertEquals(keySet.size() == 0, keySet.isEmpty()); assertEquals(!keySet.isEmpty(), keySet.iterator().hasNext()); int expectedKeySetHash = 0; for (K key : keySet) { V value = map.get(key); expectedKeySetHash += key != null ? key.hashCode() : 0; assertTrue(map.containsKey(key)); assertTrue(map.containsValue(value)); assertTrue(valueCollection.contains(value)); assertTrue(valueCollection.containsAll(Collections.singleton(value))); assertTrue(entrySet.contains(mapEntry(key, value))); assertTrue(allowsNullKeys || (key != null)); } assertEquals(expectedKeySetHash, keySet.hashCode()); assertEquals(map.size(), valueCollection.size()); assertEquals(valueCollection.size() == 0, valueCollection.isEmpty()); assertEquals( !valueCollection.isEmpty(), valueCollection.iterator().hasNext()); for (V value : valueCollection) { assertTrue(map.containsValue(value)); assertTrue(allowsNullValues || (value != null)); } assertEquals(map.size(), entrySet.size()); assertEquals(entrySet.size() == 0, entrySet.isEmpty()); assertEquals(!entrySet.isEmpty(), entrySet.iterator().hasNext()); assertFalse(entrySet.contains("foo")); boolean supportsValuesHashCode = supportsValuesHashCode(map); if (supportsValuesHashCode) { int expectedEntrySetHash = 0; for (Entry<K, V> entry : entrySet) { assertTrue(map.containsKey(entry.getKey())); assertTrue(map.containsValue(entry.getValue())); int expectedHash = (entry.getKey() == null ? 0 : entry.getKey().hashCode()) ^ (entry.getValue() == null ? 0 : entry.getValue().hashCode()); assertEquals(expectedHash, entry.hashCode()); expectedEntrySetHash += expectedHash; } assertEquals(expectedEntrySetHash, entrySet.hashCode()); assertTrue(entrySet.containsAll(new HashSet<Entry<K, V>>(entrySet))); assertTrue(entrySet.equals(new HashSet<Entry<K, V>>(entrySet))); } Object[] entrySetToArray1 = entrySet.toArray(); assertEquals(map.size(), entrySetToArray1.length); assertTrue(Arrays.asList(entrySetToArray1).containsAll(entrySet)); Entry<?, ?>[] entrySetToArray2 = new Entry<?, ?>[map.size() + 2]; entrySetToArray2[map.size()] = mapEntry("foo", 1); assertSame(entrySetToArray2, entrySet.toArray(entrySetToArray2)); assertNull(entrySetToArray2[map.size()]); assertTrue(Arrays.asList(entrySetToArray2).containsAll(entrySet)); Object[] valuesToArray1 = valueCollection.toArray(); assertEquals(map.size(), valuesToArray1.length); assertTrue(Arrays.asList(valuesToArray1).containsAll(valueCollection)); Object[] valuesToArray2 = new Object[map.size() + 2]; valuesToArray2[map.size()] = "foo"; assertSame(valuesToArray2, valueCollection.toArray(valuesToArray2)); assertNull(valuesToArray2[map.size()]); assertTrue(Arrays.asList(valuesToArray2).containsAll(valueCollection)); if (supportsValuesHashCode) { int expectedHash = 0; for (Entry<K, V> entry : entrySet) { expectedHash += entry.hashCode(); } assertEquals(expectedHash, map.hashCode()); } assertMoreInvariants(map); } /** * Override this to check invariants which should hold true for a particular * implementation, but which are not generally applicable to every instance * of Map. * * @param map the map whose additional invariants to check. */ protected void assertMoreInvariants(Map<K, V> map) { } public void testClear() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } if (supportsClear) { map.clear(); assertTrue(map.isEmpty()); } else { try { map.clear(); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testContainsKey() { final Map<K, V> map; final K unmappedKey; try { map = makePopulatedMap(); unmappedKey = getKeyNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } assertFalse(map.containsKey(unmappedKey)); try { assertFalse(map.containsKey(new IncompatibleKeyType())); } catch (ClassCastException tolerated) {} assertTrue(map.containsKey(map.keySet().iterator().next())); if (allowsNullKeys) { map.containsKey(null); } else { try { map.containsKey(null); } catch (NullPointerException optional) { } } assertInvariants(map); } public void testContainsValue() { final Map<K, V> map; final V unmappedValue; try { map = makePopulatedMap(); unmappedValue = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } assertFalse(map.containsValue(unmappedValue)); assertTrue(map.containsValue(map.values().iterator().next())); if (allowsNullValues) { map.containsValue(null); } else { try { map.containsKey(null); } catch (NullPointerException optional) { } } assertInvariants(map); } public void testEntrySet() { final Map<K, V> map; final Set<Entry<K, V>> entrySet; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } assertInvariants(map); entrySet = map.entrySet(); final K unmappedKey; final V unmappedValue; try { unmappedKey = getKeyNotInPopulatedMap(); unmappedValue = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } for (Entry<K, V> entry : entrySet) { assertFalse(unmappedKey.equals(entry.getKey())); assertFalse(unmappedValue.equals(entry.getValue())); } } public void testEntrySetForEmptyMap() { final Map<K, V> map; try { map = makeEmptyMap(); } catch (UnsupportedOperationException e) { return; } assertInvariants(map); } public void testEntrySetContainsEntryIncompatibleKey() { final Map<K, V> map; final Set<Entry<K, V>> entrySet; try { map = makeEitherMap(); } catch (UnsupportedOperationException e) { return; } assertInvariants(map); entrySet = map.entrySet(); final V unmappedValue; try { unmappedValue = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } Entry<IncompatibleKeyType, V> entry = mapEntry(new IncompatibleKeyType(), unmappedValue); try { assertFalse(entrySet.contains(entry)); } catch (ClassCastException tolerated) {} } public void testEntrySetContainsEntryNullKeyPresent() { if (!allowsNullKeys || !supportsPut) { return; } final Map<K, V> map; final Set<Entry<K, V>> entrySet; try { map = makeEitherMap(); } catch (UnsupportedOperationException e) { return; } assertInvariants(map); entrySet = map.entrySet(); final V unmappedValue; try { unmappedValue = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } map.put(null, unmappedValue); Entry<K, V> entry = mapEntry(null, unmappedValue); assertTrue(entrySet.contains(entry)); assertFalse(entrySet.contains(mapEntry(null, null))); } public void testEntrySetContainsEntryNullKeyMissing() { final Map<K, V> map; final Set<Entry<K, V>> entrySet; try { map = makeEitherMap(); } catch (UnsupportedOperationException e) { return; } assertInvariants(map); entrySet = map.entrySet(); final V unmappedValue; try { unmappedValue = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } Entry<K, V> entry = mapEntry(null, unmappedValue); try { assertFalse(entrySet.contains(entry)); } catch (NullPointerException e) { assertFalse(allowsNullKeys); } try { assertFalse(entrySet.contains(mapEntry(null, null))); } catch (NullPointerException e) { assertFalse(allowsNullKeys && allowsNullValues); } } public void testEntrySetIteratorRemove() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Set<Entry<K, V>> entrySet = map.entrySet(); Iterator<Entry<K, V>> iterator = entrySet.iterator(); if (supportsIteratorRemove) { int initialSize = map.size(); Entry<K, V> entry = iterator.next(); Entry<K, V> entryCopy = Helpers.mapEntry( entry.getKey(), entry.getValue()); iterator.remove(); assertEquals(initialSize - 1, map.size()); // Use "entryCopy" instead of "entry" because "entry" might be invalidated after // iterator.remove(). assertFalse(entrySet.contains(entryCopy)); assertInvariants(map); try { iterator.remove(); fail("Expected IllegalStateException."); } catch (IllegalStateException e) { // Expected. } } else { try { iterator.next(); iterator.remove(); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testEntrySetRemove() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Set<Entry<K, V>> entrySet = map.entrySet(); if (supportsRemove) { int initialSize = map.size(); boolean didRemove = entrySet.remove(entrySet.iterator().next()); assertTrue(didRemove); assertEquals(initialSize - 1, map.size()); } else { try { entrySet.remove(entrySet.iterator().next()); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testEntrySetRemoveMissingKey() { final Map<K, V> map; final K key; try { map = makeEitherMap(); key = getKeyNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } Set<Entry<K, V>> entrySet = map.entrySet(); Entry<K, V> entry = mapEntry(key, getValueNotInPopulatedMap()); int initialSize = map.size(); if (supportsRemove) { boolean didRemove = entrySet.remove(entry); assertFalse(didRemove); } else { try { boolean didRemove = entrySet.remove(entry); assertFalse(didRemove); } catch (UnsupportedOperationException optional) {} } assertEquals(initialSize, map.size()); assertFalse(map.containsKey(key)); assertInvariants(map); } public void testEntrySetRemoveDifferentValue() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Set<Entry<K, V>> entrySet = map.entrySet(); K key = map.keySet().iterator().next(); Entry<K, V> entry = mapEntry(key, getValueNotInPopulatedMap()); int initialSize = map.size(); if (supportsRemove) { boolean didRemove = entrySet.remove(entry); assertFalse(didRemove); } else { try { boolean didRemove = entrySet.remove(entry); assertFalse(didRemove); } catch (UnsupportedOperationException optional) {} } assertEquals(initialSize, map.size()); assertTrue(map.containsKey(key)); assertInvariants(map); } public void testEntrySetRemoveNullKeyPresent() { if (!allowsNullKeys || !supportsPut || !supportsRemove) { return; } final Map<K, V> map; final Set<Entry<K, V>> entrySet; try { map = makeEitherMap(); } catch (UnsupportedOperationException e) { return; } assertInvariants(map); entrySet = map.entrySet(); final V unmappedValue; try { unmappedValue = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } map.put(null, unmappedValue); assertEquals(unmappedValue, map.get(null)); assertTrue(map.containsKey(null)); Entry<K, V> entry = mapEntry(null, unmappedValue); assertTrue(entrySet.remove(entry)); assertNull(map.get(null)); assertFalse(map.containsKey(null)); } public void testEntrySetRemoveNullKeyMissing() { final Map<K, V> map; try { map = makeEitherMap(); } catch (UnsupportedOperationException e) { return; } Set<Entry<K, V>> entrySet = map.entrySet(); Entry<K, V> entry = mapEntry(null, getValueNotInPopulatedMap()); int initialSize = map.size(); if (supportsRemove) { try { boolean didRemove = entrySet.remove(entry); assertFalse(didRemove); } catch (NullPointerException e) { assertFalse(allowsNullKeys); } } else { try { boolean didRemove = entrySet.remove(entry); assertFalse(didRemove); } catch (UnsupportedOperationException optional) {} } assertEquals(initialSize, map.size()); assertInvariants(map); } public void testEntrySetRemoveAll() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Set<Entry<K, V>> entrySet = map.entrySet(); Entry<K, V> entryToRemove = entrySet.iterator().next(); Set<Entry<K, V>> entriesToRemove = singleton(entryToRemove); if (supportsRemove) { // We use a copy of "entryToRemove" in the assertion because "entryToRemove" might be // invalidated and have undefined behavior after entrySet.removeAll(entriesToRemove), // for example entryToRemove.getValue() might be null. Entry<K, V> entryToRemoveCopy = Helpers.mapEntry( entryToRemove.getKey(), entryToRemove.getValue()); int initialSize = map.size(); boolean didRemove = entrySet.removeAll(entriesToRemove); assertTrue(didRemove); assertEquals(initialSize - entriesToRemove.size(), map.size()); // Use "entryToRemoveCopy" instead of "entryToRemove" because it might be invalidated and // have undefined behavior after entrySet.removeAll(entriesToRemove), assertFalse(entrySet.contains(entryToRemoveCopy)); } else { try { entrySet.removeAll(entriesToRemove); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testEntrySetRemoveAllNullFromEmpty() { final Map<K, V> map; try { map = makeEmptyMap(); } catch (UnsupportedOperationException e) { return; } Set<Entry<K, V>> entrySet = map.entrySet(); if (supportsRemove) { try { entrySet.removeAll(null); fail("Expected NullPointerException."); } catch (NullPointerException e) { // Expected. } } else { try { entrySet.removeAll(null); fail("Expected UnsupportedOperationException or NullPointerException."); } catch (UnsupportedOperationException e) { // Expected. } catch (NullPointerException e) { // Expected. } } assertInvariants(map); } public void testEntrySetRetainAll() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Set<Entry<K, V>> entrySet = map.entrySet(); Set<Entry<K, V>> entriesToRetain = singleton(entrySet.iterator().next()); if (supportsRemove) { boolean shouldRemove = (entrySet.size() > entriesToRetain.size()); boolean didRemove = entrySet.retainAll(entriesToRetain); assertEquals(shouldRemove, didRemove); assertEquals(entriesToRetain.size(), map.size()); for (Entry<K, V> entry : entriesToRetain) { assertTrue(entrySet.contains(entry)); } } else { try { entrySet.retainAll(entriesToRetain); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testEntrySetRetainAllNullFromEmpty() { final Map<K, V> map; try { map = makeEmptyMap(); } catch (UnsupportedOperationException e) { return; } Set<Entry<K, V>> entrySet = map.entrySet(); if (supportsRemove) { try { entrySet.retainAll(null); // Returning successfully is not ideal, but tolerated. } catch (NullPointerException e) { // Expected. } } else { try { entrySet.retainAll(null); // We have to tolerate a successful return (Sun bug 4802647) } catch (UnsupportedOperationException e) { // Expected. } catch (NullPointerException e) { // Expected. } } assertInvariants(map); } public void testEntrySetClear() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Set<Entry<K, V>> entrySet = map.entrySet(); if (supportsClear) { entrySet.clear(); assertTrue(entrySet.isEmpty()); } else { try { entrySet.clear(); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testEntrySetAddAndAddAll() { final Map<K, V> map = makeEitherMap(); Set<Entry<K, V>> entrySet = map.entrySet(); final Entry<K, V> entryToAdd = mapEntry(null, null); try { entrySet.add(entryToAdd); fail("Expected UnsupportedOperationException or NullPointerException."); } catch (UnsupportedOperationException e) { // Expected. } catch (NullPointerException e) { // Expected. } assertInvariants(map); try { entrySet.addAll(singleton(entryToAdd)); fail("Expected UnsupportedOperationException or NullPointerException."); } catch (UnsupportedOperationException e) { // Expected. } catch (NullPointerException e) { // Expected. } assertInvariants(map); } public void testEntrySetSetValue() { // TODO: Investigate the extent to which, in practice, maps that support // put() also support Entry.setValue(). if (!supportsPut) { return; } final Map<K, V> map; final V valueToSet; try { map = makePopulatedMap(); valueToSet = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } Set<Entry<K, V>> entrySet = map.entrySet(); Entry<K, V> entry = entrySet.iterator().next(); final V oldValue = entry.getValue(); final V returnedValue = entry.setValue(valueToSet); assertEquals(oldValue, returnedValue); assertTrue(entrySet.contains( mapEntry(entry.getKey(), valueToSet))); assertEquals(valueToSet, map.get(entry.getKey())); assertInvariants(map); } public void testEntrySetSetValueSameValue() { // TODO: Investigate the extent to which, in practice, maps that support // put() also support Entry.setValue(). if (!supportsPut) { return; } final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Set<Entry<K, V>> entrySet = map.entrySet(); Entry<K, V> entry = entrySet.iterator().next(); final V oldValue = entry.getValue(); final V returnedValue = entry.setValue(oldValue); assertEquals(oldValue, returnedValue); assertTrue(entrySet.contains( mapEntry(entry.getKey(), oldValue))); assertEquals(oldValue, map.get(entry.getKey())); assertInvariants(map); } public void testEqualsForEqualMap() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } assertEquals(map, map); assertEquals(makePopulatedMap(), map); assertFalse(map.equals(Collections.emptyMap())); //no-inspection ObjectEqualsNull assertFalse(map.equals(null)); } public void testEqualsForLargerMap() { if (!supportsPut) { return; } final Map<K, V> map; final Map<K, V> largerMap; try { map = makePopulatedMap(); largerMap = makePopulatedMap(); largerMap.put(getKeyNotInPopulatedMap(), getValueNotInPopulatedMap()); } catch (UnsupportedOperationException e) { return; } assertFalse(map.equals(largerMap)); } public void testEqualsForSmallerMap() { if (!supportsRemove) { return; } final Map<K, V> map; final Map<K, V> smallerMap; try { map = makePopulatedMap(); smallerMap = makePopulatedMap(); smallerMap.remove(smallerMap.keySet().iterator().next()); } catch (UnsupportedOperationException e) { return; } assertFalse(map.equals(smallerMap)); } public void testEqualsForEmptyMap() { final Map<K, V> map; try { map = makeEmptyMap(); } catch (UnsupportedOperationException e) { return; } assertEquals(map, map); assertEquals(makeEmptyMap(), map); assertEquals(Collections.emptyMap(), map); assertFalse(map.equals(Collections.emptySet())); //noinspection ObjectEqualsNull assertFalse(map.equals(null)); } public void testGet() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } for (Entry<K, V> entry : map.entrySet()) { assertEquals(entry.getValue(), map.get(entry.getKey())); } K unmappedKey = null; try { unmappedKey = getKeyNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } assertNull(map.get(unmappedKey)); } public void testGetForEmptyMap() { final Map<K, V> map; K unmappedKey = null; try { map = makeEmptyMap(); unmappedKey = getKeyNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } assertNull(map.get(unmappedKey)); } public void testGetNull() { Map<K, V> map = makeEitherMap(); if (allowsNullKeys) { if (allowsNullValues) { // TODO: decide what to test here. } else { assertEquals(map.containsKey(null), map.get(null) != null); } } else { try { map.get(null); } catch (NullPointerException optional) { } } assertInvariants(map); } public void testHashCode() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } assertInvariants(map); } public void testHashCodeForEmptyMap() { final Map<K, V> map; try { map = makeEmptyMap(); } catch (UnsupportedOperationException e) { return; } assertInvariants(map); } public void testPutNewKey() { final Map<K, V> map = makeEitherMap(); final K keyToPut; final V valueToPut; try { keyToPut = getKeyNotInPopulatedMap(); valueToPut = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } if (supportsPut) { int initialSize = map.size(); V oldValue = map.put(keyToPut, valueToPut); assertEquals(valueToPut, map.get(keyToPut)); assertTrue(map.containsKey(keyToPut)); assertTrue(map.containsValue(valueToPut)); assertEquals(initialSize + 1, map.size()); assertNull(oldValue); } else { try { map.put(keyToPut, valueToPut); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testPutExistingKey() { final Map<K, V> map; final K keyToPut; final V valueToPut; try { map = makePopulatedMap(); valueToPut = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } keyToPut = map.keySet().iterator().next(); if (supportsPut) { int initialSize = map.size(); map.put(keyToPut, valueToPut); assertEquals(valueToPut, map.get(keyToPut)); assertTrue(map.containsKey(keyToPut)); assertTrue(map.containsValue(valueToPut)); assertEquals(initialSize, map.size()); } else { try { map.put(keyToPut, valueToPut); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testPutNullKey() { if (!supportsPut) { return; } final Map<K, V> map = makeEitherMap(); final V valueToPut; try { valueToPut = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } if (allowsNullKeys) { final V oldValue = map.get(null); final V returnedValue = map.put(null, valueToPut); assertEquals(oldValue, returnedValue); assertEquals(valueToPut, map.get(null)); assertTrue(map.containsKey(null)); assertTrue(map.containsValue(valueToPut)); } else { try { map.put(null, valueToPut); fail("Expected RuntimeException"); } catch (RuntimeException e) { // Expected. } } assertInvariants(map); } public void testPutNullValue() { if (!supportsPut) { return; } final Map<K, V> map = makeEitherMap(); final K keyToPut; try { keyToPut = getKeyNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } if (allowsNullValues) { int initialSize = map.size(); final V oldValue = map.get(keyToPut); final V returnedValue = map.put(keyToPut, null); assertEquals(oldValue, returnedValue); assertNull(map.get(keyToPut)); assertTrue(map.containsKey(keyToPut)); assertTrue(map.containsValue(null)); assertEquals(initialSize + 1, map.size()); } else { try { map.put(keyToPut, null); fail("Expected RuntimeException"); } catch (RuntimeException e) { // Expected. } } assertInvariants(map); } public void testPutNullValueForExistingKey() { if (!supportsPut) { return; } final Map<K, V> map; final K keyToPut; try { map = makePopulatedMap(); keyToPut = map.keySet().iterator().next(); } catch (UnsupportedOperationException e) { return; } if (allowsNullValues) { int initialSize = map.size(); final V oldValue = map.get(keyToPut); final V returnedValue = map.put(keyToPut, null); assertEquals(oldValue, returnedValue); assertNull(map.get(keyToPut)); assertTrue(map.containsKey(keyToPut)); assertTrue(map.containsValue(null)); assertEquals(initialSize, map.size()); } else { try { map.put(keyToPut, null); fail("Expected RuntimeException"); } catch (RuntimeException e) { // Expected. } } assertInvariants(map); } public void testPutAllNewKey() { final Map<K, V> map = makeEitherMap(); final K keyToPut; final V valueToPut; try { keyToPut = getKeyNotInPopulatedMap(); valueToPut = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } final Map<K, V> mapToPut = Collections.singletonMap(keyToPut, valueToPut); if (supportsPut) { int initialSize = map.size(); map.putAll(mapToPut); assertEquals(valueToPut, map.get(keyToPut)); assertTrue(map.containsKey(keyToPut)); assertTrue(map.containsValue(valueToPut)); assertEquals(initialSize + 1, map.size()); } else { try { map.putAll(mapToPut); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testPutAllExistingKey() { final Map<K, V> map; final K keyToPut; final V valueToPut; try { map = makePopulatedMap(); valueToPut = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } keyToPut = map.keySet().iterator().next(); final Map<K, V> mapToPut = Collections.singletonMap(keyToPut, valueToPut); int initialSize = map.size(); if (supportsPut) { map.putAll(mapToPut); assertEquals(valueToPut, map.get(keyToPut)); assertTrue(map.containsKey(keyToPut)); assertTrue(map.containsValue(valueToPut)); } else { try { map.putAll(mapToPut); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertEquals(initialSize, map.size()); assertInvariants(map); } public void testRemove() { final Map<K, V> map; final K keyToRemove; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } keyToRemove = map.keySet().iterator().next(); if (supportsRemove) { int initialSize = map.size(); V expectedValue = map.get(keyToRemove); V oldValue = map.remove(keyToRemove); 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); } public void testRemoveMissingKey() { final Map<K, V> map; final K keyToRemove; try { map = makePopulatedMap(); keyToRemove = getKeyNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } if (supportsRemove) { int initialSize = map.size(); assertNull(map.remove(keyToRemove)); assertEquals(initialSize, map.size()); } else { try { map.remove(keyToRemove); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testSize() { assertInvariants(makeEitherMap()); } public void testKeySetRemove() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Set<K> keys = map.keySet(); K key = keys.iterator().next(); if (supportsRemove) { int initialSize = map.size(); keys.remove(key); assertEquals(initialSize - 1, map.size()); assertFalse(map.containsKey(key)); } else { try { keys.remove(key); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testKeySetRemoveAll() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Set<K> keys = map.keySet(); K key = keys.iterator().next(); if (supportsRemove) { int initialSize = map.size(); assertTrue(keys.removeAll(Collections.singleton(key))); assertEquals(initialSize - 1, map.size()); assertFalse(map.containsKey(key)); } else { try { keys.removeAll(Collections.singleton(key)); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testKeySetRetainAll() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Set<K> keys = map.keySet(); K key = keys.iterator().next(); if (supportsRemove) { keys.retainAll(Collections.singleton(key)); assertEquals(1, map.size()); assertTrue(map.containsKey(key)); } else { try { keys.retainAll(Collections.singleton(key)); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testKeySetClear() { final Map<K, V> map; try { map = makeEitherMap(); } catch (UnsupportedOperationException e) { return; } Set<K> keySet = map.keySet(); if (supportsClear) { keySet.clear(); assertTrue(keySet.isEmpty()); } else { try { keySet.clear(); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testKeySetRemoveAllNullFromEmpty() { final Map<K, V> map; try { map = makeEmptyMap(); } catch (UnsupportedOperationException e) { return; } Set<K> keySet = map.keySet(); if (supportsRemove) { try { keySet.removeAll(null); fail("Expected NullPointerException."); } catch (NullPointerException e) { // Expected. } } else { try { keySet.removeAll(null); fail("Expected UnsupportedOperationException or NullPointerException."); } catch (UnsupportedOperationException e) { // Expected. } catch (NullPointerException e) { // Expected. } } assertInvariants(map); } public void testKeySetRetainAllNullFromEmpty() { final Map<K, V> map; try { map = makeEmptyMap(); } catch (UnsupportedOperationException e) { return; } Set<K> keySet = map.keySet(); if (supportsRemove) { try { keySet.retainAll(null); // Returning successfully is not ideal, but tolerated. } catch (NullPointerException e) { // Expected. } } else { try { keySet.retainAll(null); // We have to tolerate a successful return (Sun bug 4802647) } catch (UnsupportedOperationException e) { // Expected. } catch (NullPointerException e) { // Expected. } } assertInvariants(map); } public void testValues() { final Map<K, V> map; final Collection<V> valueCollection; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } assertInvariants(map); valueCollection = map.values(); final V unmappedValue; try { unmappedValue = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } for (V value : valueCollection) { assertFalse(unmappedValue.equals(value)); } } public void testValuesIteratorRemove() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Collection<V> valueCollection = map.values(); Iterator<V> iterator = valueCollection.iterator(); if (supportsIteratorRemove) { int initialSize = map.size(); iterator.next(); iterator.remove(); assertEquals(initialSize - 1, map.size()); // (We can't assert that the values collection no longer contains the // removed value, because the underlying map can have multiple mappings // to the same value.) assertInvariants(map); try { iterator.remove(); fail("Expected IllegalStateException."); } catch (IllegalStateException e) { // Expected. } } else { try { iterator.next(); iterator.remove(); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testValuesRemove() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Collection<V> valueCollection = map.values(); if (supportsRemove) { int initialSize = map.size(); valueCollection.remove(valueCollection.iterator().next()); assertEquals(initialSize - 1, map.size()); // (We can't assert that the values collection no longer contains the // removed value, because the underlying map can have multiple mappings // to the same value.) } else { try { valueCollection.remove(valueCollection.iterator().next()); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testValuesRemoveMissing() { final Map<K, V> map; final V valueToRemove; try { map = makeEitherMap(); valueToRemove = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } Collection<V> valueCollection = map.values(); int initialSize = map.size(); if (supportsRemove) { assertFalse(valueCollection.remove(valueToRemove)); } else { try { assertFalse(valueCollection.remove(valueToRemove)); } catch (UnsupportedOperationException e) { // Tolerated. } } assertEquals(initialSize, map.size()); assertInvariants(map); } public void testValuesRemoveAll() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Collection<V> valueCollection = map.values(); Set<V> valuesToRemove = singleton(valueCollection.iterator().next()); if (supportsRemove) { valueCollection.removeAll(valuesToRemove); for (V value : valuesToRemove) { assertFalse(valueCollection.contains(value)); } for (V value : valueCollection) { assertFalse(valuesToRemove.contains(value)); } } else { try { valueCollection.removeAll(valuesToRemove); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testValuesRemoveAllNullFromEmpty() { final Map<K, V> map; try { map = makeEmptyMap(); } catch (UnsupportedOperationException e) { return; } Collection<V> values = map.values(); if (supportsRemove) { try { values.removeAll(null); // Returning successfully is not ideal, but tolerated. } catch (NullPointerException e) { // Expected. } } else { try { values.removeAll(null); // We have to tolerate a successful return (Sun bug 4802647) } catch (UnsupportedOperationException e) { // Expected. } catch (NullPointerException e) { // Expected. } } assertInvariants(map); } public void testValuesRetainAll() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Collection<V> valueCollection = map.values(); Set<V> valuesToRetain = singleton(valueCollection.iterator().next()); if (supportsRemove) { valueCollection.retainAll(valuesToRetain); for (V value : valuesToRetain) { assertTrue(valueCollection.contains(value)); } for (V value : valueCollection) { assertTrue(valuesToRetain.contains(value)); } } else { try { valueCollection.retainAll(valuesToRetain); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } public void testValuesRetainAllNullFromEmpty() { final Map<K, V> map; try { map = makeEmptyMap(); } catch (UnsupportedOperationException e) { return; } Collection<V> values = map.values(); if (supportsRemove) { try { values.retainAll(null); // Returning successfully is not ideal, but tolerated. } catch (NullPointerException e) { // Expected. } } else { try { values.retainAll(null); // We have to tolerate a successful return (Sun bug 4802647) } catch (UnsupportedOperationException e) { // Expected. } catch (NullPointerException e) { // Expected. } } assertInvariants(map); } public void testValuesClear() { final Map<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Collection<V> valueCollection = map.values(); if (supportsClear) { valueCollection.clear(); assertTrue(valueCollection.isEmpty()); } else { try { valueCollection.clear(); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } static <K, V> Entry<K, V> mapEntry(K key, V value) { return Collections.singletonMap(key, value).entrySet().iterator().next(); } }
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; import java.util.List; /** * Creates sets, containing sample elements, to be tested. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ public interface TestListGenerator<E> extends TestCollectionGenerator<E> { @Override List<E> create(Object... elements); }
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; import java.util.List; import java.util.Map; import java.util.Set; /** * Creates map entries using sample keys and sample values. * * <p>This class is GWT compatible. * * @author Jesse Wilson */ public abstract class TestMapEntrySetGenerator<K, V> implements TestSetGenerator<Map.Entry<K, V>> { private final SampleElements<K> keys; private final SampleElements<V> values; protected TestMapEntrySetGenerator( SampleElements<K> keys, SampleElements<V> values) { this.keys = keys; this.values = values; } @Override public SampleElements<Map.Entry<K, V>> samples() { return SampleElements.mapEntries(keys, values); } @Override public Set<Map.Entry<K, V>> create(Object... elements) { Map.Entry<K, V>[] entries = createArray(elements.length); Platform.unsafeArrayCopy(elements, 0, entries, 0, elements.length); return createFromEntries(entries); } public abstract Set<Map.Entry<K, V>> createFromEntries( Map.Entry<K, V>[] entries); @Override @SuppressWarnings("unchecked") // generic arrays make typesafety sad public Map.Entry<K, V>[] createArray(int length) { return new Map.Entry[length]; } /** Returns the original element list, unchanged. */ @Override public List<Map.Entry<K, V>> order(List<Map.Entry<K, V>> insertionOrder) { return insertionOrder; } }
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; import junit.framework.TestSuite; import java.util.List; /** * Given a test iterable generator, builds a test suite for the * iterable's iterator, by delegating to a {@link IteratorTestSuiteBuilder}. * * @author George van den Driessche */ public class DerivedIteratorTestSuiteBuilder<E> extends FeatureSpecificTestSuiteBuilder< DerivedIteratorTestSuiteBuilder<E>, TestSubjectGenerator<? extends Iterable<E>>> { /** * We rely entirely on the delegate builder for test creation, so this * just throws UnsupportedOperationException. * * @return never. */ @Override protected List<Class<? extends AbstractTester>> getTesters() { throw new UnsupportedOperationException(); } @Override public TestSuite createTestSuite() { checkCanCreate(); return new IteratorTestSuiteBuilder<E>() .named(getName() + " iterator") .usingGenerator(new DerivedTestIteratorGenerator<E>( getSubjectGenerator())) .withFeatures(getFeatures()) .createTestSuite(); } }
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.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.ListFeature; import junit.framework.Test; import junit.framework.TestSuite; import java.lang.reflect.Method; import java.util.AbstractList; import java.util.AbstractSequentialList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.concurrent.CopyOnWriteArrayList; /** * Generates a test suite covering the {@link List} implementations in the * {@link java.util} package. Can be subclassed to specify tests that should * be suppressed. * * @author Kevin Bourrillion */ public class TestsForListsInJavaUtil { public static Test suite() { return new TestsForListsInJavaUtil().allTests(); } public Test allTests() { TestSuite suite = new TestSuite("java.util Lists"); suite.addTest(testsForEmptyList()); suite.addTest(testsForSingletonList()); suite.addTest(testsForArraysAsList()); suite.addTest(testsForArrayList()); suite.addTest(testsForLinkedList()); suite.addTest(testsForCopyOnWriteArrayList()); suite.addTest(testsForUnmodifiableList()); suite.addTest(testsForCheckedList()); suite.addTest(testsForAbstractList()); suite.addTest(testsForAbstractSequentialList()); return suite; } protected Collection<Method> suppressForEmptyList() { return Collections.emptySet(); } protected Collection<Method> suppressForSingletonList() { return Collections.emptySet(); } protected Collection<Method> suppressForArraysAsList() { return Collections.emptySet(); } protected Collection<Method> suppressForArrayList() { return Collections.emptySet(); } protected Collection<Method> suppressForLinkedList() { return Collections.emptySet(); } protected Collection<Method> suppressForCopyOnWriteArrayList() { return Collections.emptySet(); } protected Collection<Method> suppressForUnmodifiableList() { return Collections.emptySet(); } protected Collection<Method> suppressForCheckedList() { return Collections.emptySet(); } protected Collection<Method> suppressForAbstractList() { return Collections.emptySet(); } protected Collection<Method> suppressForAbstractSequentialList() { return Collections.emptySet(); } public Test testsForEmptyList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return Collections.emptyList(); } }) .named("emptyList") .withFeatures( CollectionFeature.SERIALIZABLE, CollectionSize.ZERO) .suppressing(suppressForEmptyList()) .createTestSuite(); } public Test testsForSingletonList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return Collections.singletonList(elements[0]); } }) .named("singletonList") .withFeatures( CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ONE) .suppressing(suppressForSingletonList()) .createTestSuite(); } public Test testsForArraysAsList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return Arrays.asList(elements.clone()); } }) .named("Arrays.asList") .withFeatures( ListFeature.SUPPORTS_SET, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForArraysAsList()) .createTestSuite(); } public Test testsForArrayList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return new ArrayList<String>(MinimalCollection.of(elements)); } }) .named("ArrayList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionSize.ANY) .suppressing(suppressForArrayList()) .createTestSuite(); } public Test testsForLinkedList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return new LinkedList<String>(MinimalCollection.of(elements)); } }) .named("LinkedList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionSize.ANY) .suppressing(suppressForLinkedList()) .createTestSuite(); } public Test testsForCopyOnWriteArrayList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return new CopyOnWriteArrayList<String>( MinimalCollection.of(elements)); } }) .named("CopyOnWriteArrayList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForCopyOnWriteArrayList()) .createTestSuite(); } public Test testsForUnmodifiableList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { List<String> innerList = new ArrayList<String>(); Collections.addAll(innerList, elements); return Collections.unmodifiableList(innerList); } }) .named("unmodifiableList/ArrayList") .withFeatures( CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForUnmodifiableList()) .createTestSuite(); } public Test testsForCheckedList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { List<String> innerList = new ArrayList<String>(); Collections.addAll(innerList, elements); return Collections.checkedList(innerList, String.class); } }) .named("checkedList/ArrayList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.RESTRICTS_ELEMENTS, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForCheckedList()) .createTestSuite(); } public Test testsForAbstractList() { return ListTestSuiteBuilder .using(new TestStringListGenerator () { @Override protected List<String> create(final String[] elements) { return new AbstractList<String>() { @Override public int size() { return elements.length; } @Override public String get(int index) { return elements[index]; } }; } }) .named("AbstractList") .withFeatures( CollectionFeature.NONE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForAbstractList()) .createTestSuite(); } public Test testsForAbstractSequentialList() { return ListTestSuiteBuilder .using(new TestStringListGenerator () { @Override protected List<String> create(final String[] elements) { // For this test we trust ArrayList works final List<String> list = new ArrayList<String>(); Collections.addAll(list, elements); return new AbstractSequentialList<String>() { @Override public int size() { return list.size(); } @Override public ListIterator<String> listIterator(int index) { return list.listIterator(index); } }; } }) .named("AbstractSequentialList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForAbstractSequentialList()) .createTestSuite(); } }
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; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Base class for testers of classes (including {@link Collection} * and {@link java.util.Map Map}) that contain elements. * * <p>This class is GWT compatible. * * @param <C> the type of the container * @param <E> the type of the container's contents * * @author George van den Driessche */ public abstract class AbstractContainerTester<C, E> extends AbstractTester<OneSizeTestContainerGenerator<C, E>> { protected SampleElements<E> samples; protected C container; @Override public void setUp() throws Exception { super.setUp(); samples = this.getSubjectGenerator().samples(); resetContainer(); } /** * @return the contents of the container under test, for use by * {@link #expectContents(Object[]) expectContents(E...)} and its friends. */ protected abstract Collection<E> actualContents(); /** * Replaces the existing container under test with a new container created * by the subject generator. * * @see #resetContainer(Object) resetContainer(C) * * @return the new container instance. */ protected C resetContainer() { return resetContainer(getSubjectGenerator().createTestSubject()); } /** * Replaces the existing container under test with a new container. * This is useful when a single test method needs to create multiple * containers while retaining the ability to use * {@link #expectContents(Object[]) expectContents(E...)} and other * convenience methods. The creation of multiple containers in a single * method is discouraged in most cases, but it is vital to the iterator tests. * * @return the new container instance * @param newValue the new container instance */ protected C resetContainer(C newValue) { container = newValue; return container; } /** * @see #expectContents(java.util.Collection) * * @param elements expected contents of {@link #container} */ protected final void expectContents(E... elements) { expectContents(Arrays.asList(elements)); } /** * Asserts that the collection under test contains exactly the given elements, * respecting cardinality but not order. Subclasses may override this method * to provide stronger assertions, e.g., to check ordering in lists, but * realize that <strong>unless a test extends * {@link com.google.common.collect.testing.testers.AbstractListTester * AbstractListTester}, a call to {@code expectContents()} invokes this * version</strong>. * * @param expected expected value of {@link #container} */ /* * TODO: improve this and other implementations and move out of this framework * for wider use * * TODO: could we incorporate the overriding logic from AbstractListTester, by * examining whether the features include KNOWN_ORDER? */ protected void expectContents(Collection<E> expected) { Helpers.assertEqualIgnoringOrder(expected, actualContents()); } protected void expectUnchanged() { expectContents(getSampleElements()); } /** * Asserts that the collection under test contains exactly the elements it was * initialized with plus the given elements, according to * {@link #expectContents(java.util.Collection)}. In other words, for the * default {@code expectContents()} implementation, the number of occurrences * of each given element has increased by one since the test collection was * created, and the number of occurrences of all other elements has not * changed. * * <p>Note: This means that a test like the following will fail if * {@code collection} is a {@code Set}: * * <pre> * collection.add(existingElement); * expectAdded(existingElement);</pre> * * In this case, {@code collection} was not modified as a result of the * {@code add()} call, and the test will fail because the number of * occurrences of {@code existingElement} is unchanged. * * @param elements expected additional contents of {@link #container} */ protected final void expectAdded(E... elements) { List<E> expected = Helpers.copyToList(getSampleElements()); expected.addAll(Arrays.asList(elements)); expectContents(expected); } protected final void expectAdded(int index, E... elements) { expectAdded(index, Arrays.asList(elements)); } protected final void expectAdded(int index, Collection<E> elements) { List<E> expected = Helpers.copyToList(getSampleElements()); expected.addAll(index, elements); expectContents(expected); } /* * TODO: if we're testing a list, we could check indexOf(). (Doing it in * AbstractListTester isn't enough because many tests that run on lists don't * extends AbstractListTester.) We could also iterate over all elements to * verify absence */ protected void expectMissing(E... elements) { for (E element : elements) { assertFalse("Should not contain " + element, actualContents().contains(element)); } } protected E[] createSamplesArray() { E[] array = getSubjectGenerator().createArray(getNumElements()); getSampleElements().toArray(array); return array; } public static class ArrayWithDuplicate<E> { public final E[] elements; public final E duplicate; private ArrayWithDuplicate(E[] elements, E duplicate) { this.elements = elements; this.duplicate = duplicate; } } /** * @return an array of the proper size with a duplicate element. * The size must be at least three. */ protected ArrayWithDuplicate<E> createArrayWithDuplicateElement() { E[] elements = createSamplesArray(); E duplicate = elements[(elements.length / 2) - 1]; elements[(elements.length / 2) + 1] = duplicate; return new ArrayWithDuplicate<E>(elements, duplicate); } // Helper methods to improve readability of derived classes protected int getNumElements() { return getSubjectGenerator().getCollectionSize().getNumElements(); } protected Collection<E> getSampleElements(int howMany) { return getSubjectGenerator().getSampleElements(howMany); } protected Collection<E> getSampleElements() { return getSampleElements(getNumElements()); } /** * Returns the {@linkplain #getSampleElements() sample elements} as ordered by * {@link TestContainerGenerator#order(List)}. Tests should used this method * only if they declare requirement {@link * com.google.common.collect.testing.features.CollectionFeature#KNOWN_ORDER}. */ protected List<E> getOrderedElements() { List<E> list = new ArrayList<E>(); for (E e : getSubjectGenerator().order( new ArrayList<E>(getSampleElements()))) { list.add(e); } return Collections.unmodifiableList(list); } /** * @return a suitable location for a null element, to use when initializing * containers for tests that involve a null element being present. */ protected int getNullLocation() { return getNumElements() / 2; } @SuppressWarnings("unchecked") protected MinimalCollection<E> createDisjointCollection() { return MinimalCollection.of(samples.e3, samples.e4); } @SuppressWarnings("unchecked") protected MinimalCollection<E> emptyCollection() { return MinimalCollection.<E>of(); } }
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.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import junit.framework.Test; import junit.framework.TestSuite; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; /** * Generates a test suite covering the {@link Queue} implementations in the * {@link java.util} package. Can be subclassed to specify tests that should * be suppressed. * * @author Jared Levy */ public class TestsForQueuesInJavaUtil { public static Test suite() { return new TestsForQueuesInJavaUtil().allTests(); } public Test allTests() { TestSuite suite = new TestSuite(); suite.addTest(testsForLinkedList()); suite.addTest(testsForArrayBlockingQueue()); suite.addTest(testsForConcurrentLinkedQueue()); suite.addTest(testsForLinkedBlockingQueue()); suite.addTest(testsForPriorityBlockingQueue()); suite.addTest(testsForPriorityQueue()); return suite; } protected Collection<Method> suppressForLinkedList() { return Collections.emptySet(); } protected Collection<Method> suppressForArrayBlockingQueue() { return Collections.emptySet(); } protected Collection<Method> suppressForConcurrentLinkedQueue() { return Collections.emptySet(); } protected Collection<Method> suppressForLinkedBlockingQueue() { return Collections.emptySet(); } protected Collection<Method> suppressForPriorityBlockingQueue() { return Collections.emptySet(); } protected Collection<Method> suppressForPriorityQueue() { return Collections.emptySet(); } public Test testsForLinkedList() { return QueueTestSuiteBuilder .using(new TestStringQueueGenerator() { @Override public Queue<String> create(String[] elements) { return new LinkedList<String>(MinimalCollection.of(elements)); } }) .named("LinkedList") .withFeatures( CollectionFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY) .skipCollectionTests() // already covered in TestsForListsInJavaUtil .suppressing(suppressForLinkedList()) .createTestSuite(); } public Test testsForArrayBlockingQueue() { return QueueTestSuiteBuilder .using(new TestStringQueueGenerator() { @Override public Queue<String> create(String[] elements) { return new ArrayBlockingQueue<String>( 100, false, MinimalCollection.of(elements)); } }) .named("ArrayBlockingQueue") .withFeatures( CollectionFeature.GENERAL_PURPOSE, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY) .suppressing(suppressForArrayBlockingQueue()) .createTestSuite(); } public Test testsForConcurrentLinkedQueue() { return QueueTestSuiteBuilder .using(new TestStringQueueGenerator() { @Override public Queue<String> create(String[] elements) { return new ConcurrentLinkedQueue<String>( MinimalCollection.of(elements)); } }) .named("ConcurrentLinkedQueue") .withFeatures( CollectionFeature.GENERAL_PURPOSE, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY) .suppressing(suppressForConcurrentLinkedQueue()) .createTestSuite(); } public Test testsForLinkedBlockingQueue() { return QueueTestSuiteBuilder .using(new TestStringQueueGenerator() { @Override public Queue<String> create(String[] elements) { return new LinkedBlockingQueue<String>( MinimalCollection.of(elements)); } }) .named("LinkedBlockingQueue") .withFeatures( CollectionFeature.GENERAL_PURPOSE, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY) .suppressing(suppressForLinkedBlockingQueue()) .createTestSuite(); } // Not specifying KNOWN_ORDER for PriorityQueue and PriorityBlockingQueue // even though they do have it, because our tests interpret KNOWN_ORDER to // also mean that the iterator returns the head element first, which those // don't. public Test testsForPriorityBlockingQueue() { return QueueTestSuiteBuilder .using(new TestStringQueueGenerator() { @Override public Queue<String> create(String[] elements) { return new PriorityBlockingQueue<String>( MinimalCollection.of(elements)); } }) .named("PriorityBlockingQueue") .withFeatures( CollectionFeature.GENERAL_PURPOSE, CollectionSize.ANY) .suppressing(suppressForPriorityBlockingQueue()) .createTestSuite(); } public Test testsForPriorityQueue() { return QueueTestSuiteBuilder .using(new TestStringQueueGenerator() { @Override public Queue<String> create(String[] elements) { return new PriorityQueue<String>(MinimalCollection.of(elements)); } }) .named("PriorityQueue") .withFeatures( CollectionFeature.GENERAL_PURPOSE, CollectionSize.ANY) .suppressing(suppressForPriorityQueue()) .createTestSuite(); } }
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; import java.util.AbstractCollection; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; /** * A simplistic collection which implements only the bare minimum allowed by the * spec, and throws exceptions whenever it can. * * @author Kevin Bourrillion */ public class MinimalCollection<E> extends AbstractCollection<E> { // TODO: expose allow nulls parameter? public static <E> MinimalCollection<E> of(E... contents) { return new MinimalCollection<E>(Object.class, true, contents); } // TODO: use this public static <E> MinimalCollection<E> ofClassAndContents( Class<? super E> type, E... contents) { return new MinimalCollection<E>(type, true, contents); } private final E[] contents; private final Class<? super E> type; private final boolean allowNulls; // Package-private so that it can be extended. MinimalCollection(Class<? super E> type, boolean allowNulls, E... contents) { // TODO: consider making it shuffle the contents to test iteration order. this.contents = Platform.clone(contents); this.type = type; this.allowNulls = allowNulls; if (!allowNulls) { for (Object element : contents) { if (element == null) { throw new NullPointerException(); } } } } @Override public int size() { return contents.length; } @Override public boolean contains(Object object) { if (!allowNulls) { // behave badly if (object == null) { throw new NullPointerException(); } } Platform.checkCast(type, object); // behave badly return Arrays.asList(contents).contains(object); } @Override public boolean containsAll(Collection<?> collection) { if (!allowNulls) { for (Object object : collection) { // behave badly if (object == null) { throw new NullPointerException(); } } } return super.containsAll(collection); } @Override public Iterator<E> iterator() { return Arrays.asList(contents).iterator(); } @Override public Object[] toArray() { Object[] result = new Object[contents.length]; Platform.unsafeArrayCopy(contents, 0, result, 0, contents.length); return result; } /* * a "type A" unmodifiable collection freaks out proactively, even if there * wasn't going to be any actual work to do anyway */ @Override public boolean addAll(Collection<? extends E> elementsToAdd) { throw up(); } @Override public boolean removeAll(Collection<?> elementsToRemove) { throw up(); } @Override public boolean retainAll(Collection<?> elementsToRetain) { throw up(); } @Override public void clear() { throw up(); } private static UnsupportedOperationException up() { throw new UnsupportedOperationException(); } }
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.testing; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; /** * A wrapper around {@code TreeMap} that aggressively checks to see if keys are * mutually comparable. This implementation passes the navigable map test * suites. * * @author Louis Wasserman */ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V> { @SuppressWarnings("unchecked") private static final Comparator NATURAL_ORDER = new Comparator<Comparable>() { @Override public int compare(Comparable o1, Comparable o2) { return o1.compareTo(o2); } }; private final NavigableMap<K, V> delegate; public SafeTreeMap() { this(new TreeMap<K, V>()); } public SafeTreeMap(Comparator<? super K> comparator) { this(new TreeMap<K, V>(comparator)); } public SafeTreeMap(Map<? extends K, ? extends V> map) { this(new TreeMap<K, V>(map)); } public SafeTreeMap(SortedMap<K, ? extends V> map) { this(new TreeMap<K, V>(map)); } private SafeTreeMap(NavigableMap<K, V> delegate) { this.delegate = delegate; if (delegate == null) { throw new NullPointerException(); } for (K k : keySet()) { checkValid(k); } } @Override public Entry<K, V> ceilingEntry(K key) { return delegate.ceilingEntry(checkValid(key)); } @Override public K ceilingKey(K key) { return delegate.ceilingKey(checkValid(key)); } @Override public void clear() { delegate.clear(); } @SuppressWarnings("unchecked") @Override public Comparator<? super K> comparator() { Comparator<? super K> comparator = delegate.comparator(); if (comparator == null) { comparator = NATURAL_ORDER; } return comparator; } @Override public boolean containsKey(Object key) { try { return delegate.containsKey(checkValid(key)); } catch (NullPointerException e) { return false; } catch (ClassCastException e) { return false; } } @Override public boolean containsValue(Object value) { return delegate.containsValue(value); } @Override public NavigableSet<K> descendingKeySet() { return delegate.descendingKeySet(); } @Override public NavigableMap<K, V> descendingMap() { return new SafeTreeMap<K, V>(delegate.descendingMap()); } @Override public Set<Entry<K, V>> entrySet() { return delegate.entrySet(); } @Override public Entry<K, V> firstEntry() { return delegate.firstEntry(); } @Override public K firstKey() { return delegate.firstKey(); } @Override public Entry<K, V> floorEntry(K key) { return delegate.floorEntry(checkValid(key)); } @Override public K floorKey(K key) { return delegate.floorKey(checkValid(key)); } @Override public V get(Object key) { return delegate.get(checkValid(key)); } @Override public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } @Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { return new SafeTreeMap<K, V>( delegate.headMap(checkValid(toKey), inclusive)); } @Override public Entry<K, V> higherEntry(K key) { return delegate.higherEntry(checkValid(key)); } @Override public K higherKey(K key) { return delegate.higherKey(checkValid(key)); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public NavigableSet<K> keySet() { return navigableKeySet(); } @Override public Entry<K, V> lastEntry() { return delegate.lastEntry(); } @Override public K lastKey() { return delegate.lastKey(); } @Override public Entry<K, V> lowerEntry(K key) { return delegate.lowerEntry(checkValid(key)); } @Override public K lowerKey(K key) { return delegate.lowerKey(checkValid(key)); } @Override public NavigableSet<K> navigableKeySet() { return delegate.navigableKeySet(); } @Override public Entry<K, V> pollFirstEntry() { return delegate.pollFirstEntry(); } @Override public Entry<K, V> pollLastEntry() { return delegate.pollLastEntry(); } @Override public V put(K key, V value) { return delegate.put(checkValid(key), value); } @Override public void putAll(Map<? extends K, ? extends V> map) { for (K key : map.keySet()) { checkValid(key); } delegate.putAll(map); } @Override public V remove(Object key) { return delegate.remove(checkValid(key)); } @Override public int size() { return delegate.size(); } @Override public NavigableMap<K, V> subMap( K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return new SafeTreeMap<K, V>(delegate.subMap( checkValid(fromKey), fromInclusive, checkValid(toKey), toInclusive)); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } @Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { return new SafeTreeMap<K, V>( delegate.tailMap(checkValid(fromKey), inclusive)); } @Override public Collection<V> values() { return delegate.values(); } private <T> T checkValid(T t) { // a ClassCastException is what's supposed to happen! @SuppressWarnings("unchecked") K k = (K) t; comparator().compare(k, k); return t; } @Override public boolean equals(Object obj) { return delegate.equals(obj); } @Override public int hashCode() { return delegate.hashCode(); } @Override public String toString() { return delegate.toString(); } private static final long serialVersionUID = 0L; }
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 java.util.Arrays; import java.util.Collection; import java.util.Iterator; /** * An implementation of {@code Iterable} which throws an exception on all * invocations of the {@link #iterator()} method after the first, and whose * iterator is always unmodifiable. * * <p>The {@code Iterable} specification does not make it absolutely clear what * should happen on a second invocation, so implementors have made various * choices, including: * * <ul> * <li>returning the same iterator again * <li>throwing an exception of some kind * <li>or the usual, <i>robust</i> behavior, which all known {@link Collection} * implementations have, of returning a new, independent iterator * </ul> * * Because of this situation, any public method accepting an iterable should * invoke the {@code iterator} method only once, and should be tested using this * class. Exceptions to this rule should be clearly documented. * * <p>Note that although your APIs should be liberal in what they accept, your * methods which <i>return</i> iterables should make every attempt to return * ones of the robust variety. * * <p>This testing utility is not thread-safe. * * @author Kevin Bourrillion */ public final class MinimalIterable<E> implements Iterable<E> { /** * Returns an iterable whose iterator returns the given elements in order. */ public static <E> MinimalIterable<E> of(E... elements) { // Make sure to get an unmodifiable iterator return new MinimalIterable<E>(Arrays.asList(elements).iterator()); } /** * Returns an iterable whose iterator returns the given elements in order. * The elements are copied out of the source collection at the time this * method is called. */ @SuppressWarnings("unchecked") // Es come in, Es go out public static <E> MinimalIterable<E> from(final Collection<E> elements) { return (MinimalIterable) of(elements.toArray()); } private Iterator<E> iterator; private MinimalIterable(Iterator<E> iterator) { this.iterator = iterator; } @Override public Iterator<E> iterator() { if (iterator == null) { // TODO: throw something else? Do we worry that people's code and tests // might be relying on this particular type of exception? throw new IllegalStateException(); } try { return iterator; } finally { iterator = null; } } }
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 java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedMap; /** * Tests representing the contract of {@link SortedMap}. Concrete subclasses of * this base class test conformance of concrete {@link SortedMap} subclasses to * that contract. * * <p>This class is GWT compatible. * * @author Jared Levy */ // TODO: Use this class to test classes besides ImmutableSortedMap. public abstract class SortedMapInterfaceTest<K, V> extends MapInterfaceTest<K, V> { /** A key type that is not assignable to any classes but Object. */ private static final class IncompatibleComparableKeyType implements Comparable<IncompatibleComparableKeyType> { @Override public String toString() { return "IncompatibleComparableKeyType"; } @Override public int compareTo(IncompatibleComparableKeyType o) { throw new ClassCastException(); } } protected SortedMapInterfaceTest(boolean allowsNullKeys, boolean allowsNullValues, boolean supportsPut, boolean supportsRemove, boolean supportsClear) { super(allowsNullKeys, allowsNullValues, supportsPut, supportsRemove, supportsClear); } @Override protected abstract SortedMap<K, V> makeEmptyMap() throws UnsupportedOperationException; @Override protected abstract SortedMap<K, V> makePopulatedMap() throws UnsupportedOperationException; @Override protected SortedMap<K, V> makeEitherMap() { try { return makePopulatedMap(); } catch (UnsupportedOperationException e) { return makeEmptyMap(); } } @SuppressWarnings("unchecked") // Needed for null comparator public void testOrdering() { final SortedMap<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } Iterator<K> iterator = map.keySet().iterator(); K prior = iterator.next(); Comparator<? super K> comparator = map.comparator(); while (iterator.hasNext()) { K current = iterator.next(); if (comparator == null) { Comparable comparable = (Comparable) prior; assertTrue(comparable.compareTo(current) < 0); } else { assertTrue(map.comparator().compare(prior, current) < 0); } current = prior; } } public void testEntrySetContainsEntryIncompatibleComparableKey() { final Map<K, V> map; final Set<Entry<K, V>> entrySet; try { map = makeEitherMap(); } catch (UnsupportedOperationException e) { return; } assertInvariants(map); entrySet = map.entrySet(); final V unmappedValue; try { unmappedValue = getValueNotInPopulatedMap(); } catch (UnsupportedOperationException e) { return; } Entry<IncompatibleComparableKeyType, V> entry = mapEntry(new IncompatibleComparableKeyType(), unmappedValue); assertFalse(entrySet.contains(entry)); } public void testFirstKeyEmpty() { final SortedMap<K, V> map; try { map = makeEmptyMap(); } catch (UnsupportedOperationException e) { return; } try { map.firstKey(); fail("Expected NoSuchElementException"); } catch (NoSuchElementException expected) {} assertInvariants(map); } public void testFirstKeyNonEmpty() { final SortedMap<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } K expected = map.keySet().iterator().next(); assertEquals(expected, map.firstKey()); assertInvariants(map); } public void testLastKeyEmpty() { final SortedMap<K, V> map; try { map = makeEmptyMap(); } catch (UnsupportedOperationException e) { return; } try { map.lastKey(); fail("Expected NoSuchElementException"); } catch (NoSuchElementException expected) {} assertInvariants(map); } public void testLastKeyNonEmpty() { final SortedMap<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } K expected = null; for (K key : map.keySet()) { expected = key; } assertEquals(expected, map.lastKey()); assertInvariants(map); } private static <E> List<E> toList(Collection<E> collection) { return new ArrayList<E>(collection); } private static <E> List<E> subListSnapshot( List<E> list, int fromIndex, int toIndex) { List<E> subList = new ArrayList<E>(); for (int i = fromIndex; i < toIndex; i++) { subList.add(list.get(i)); } return Collections.unmodifiableList(subList); } public void testHeadMap() { final SortedMap<K, V> map; try { map = makeEitherMap(); } catch (UnsupportedOperationException e) { return; } List<Entry<K, V>> list = toList(map.entrySet()); for (int i = 0; i < list.size(); i++) { List<Entry<K, V>> expected = subListSnapshot(list, 0, i); SortedMap<K, V> headMap = map.headMap(list.get(i).getKey()); assertEquals(expected, toList(headMap.entrySet())); } } public void testTailMap() { final SortedMap<K, V> map; try { map = makeEitherMap(); } catch (UnsupportedOperationException e) { return; } List<Entry<K, V>> list = toList(map.entrySet()); for (int i = 0; i < list.size(); i++) { List<Entry<K, V>> expected = subListSnapshot(list, i, list.size()); SortedMap<K, V> tailMap = map.tailMap(list.get(i).getKey()); assertEquals(expected, toList(tailMap.entrySet())); } } public void testSubMap() { final SortedMap<K, V> map; try { map = makeEitherMap(); } catch (UnsupportedOperationException e) { return; } List<Entry<K, V>> list = toList(map.entrySet()); for (int i = 0; i < list.size(); i++) { for (int j = i; j < list.size(); j++) { List<Entry<K, V>> expected = subListSnapshot(list, i, j); SortedMap<K, V> subMap = map.subMap(list.get(i).getKey(), list.get(j).getKey()); assertEquals(expected, toList(subMap.entrySet())); } } } public void testSubMapIllegal() { final SortedMap<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } if (map.size() < 2) { return; } Iterator<K> iterator = map.keySet().iterator(); K first = iterator.next(); K second = iterator.next(); try { map.subMap(second, first); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } public void testTailMapEntrySet() { final SortedMap<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } if (map.size() < 3) { return; } Iterator<Entry<K, V>> iterator = map.entrySet().iterator(); Entry<K, V> firstEntry = iterator.next(); Entry<K, V> secondEntry = iterator.next(); Entry<K, V> thirdEntry = iterator.next(); SortedMap<K, V> tail = map.tailMap(secondEntry.getKey()); Set<Entry<K, V>> tailEntrySet = tail.entrySet(); assertTrue(tailEntrySet.contains(thirdEntry)); assertTrue(tailEntrySet.contains(secondEntry)); assertFalse(tailEntrySet.contains(firstEntry)); assertEquals(tail.firstKey(), secondEntry.getKey()); } public void testHeadMapEntrySet() { final SortedMap<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } if (map.size() < 3) { return; } Iterator<Entry<K, V>> iterator = map.entrySet().iterator(); Entry<K, V> firstEntry = iterator.next(); Entry<K, V> secondEntry = iterator.next(); Entry<K, V> thirdEntry = iterator.next(); SortedMap<K, V> head = map.headMap(secondEntry.getKey()); Set<Entry<K, V>> headEntrySet = head.entrySet(); assertFalse(headEntrySet.contains(thirdEntry)); assertFalse(headEntrySet.contains(secondEntry)); assertTrue(headEntrySet.contains(firstEntry)); assertEquals(head.firstKey(), firstEntry.getKey()); assertEquals(head.lastKey(), firstEntry.getKey()); } public void testTailMapWriteThrough() { final SortedMap<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } if (map.size() < 2 || !supportsPut) { return; } Iterator<Entry<K, V>> iterator = map.entrySet().iterator(); Entry<K, V> firstEntry = iterator.next(); Entry<K, V> secondEntry = iterator.next(); K key = secondEntry.getKey(); SortedMap<K, V> subMap = map.tailMap(key); V value = getValueNotInPopulatedMap(); subMap.put(key, value); assertEquals(secondEntry.getValue(), value); assertEquals(map.get(key), value); try { subMap.put(firstEntry.getKey(), value); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testTailMapRemoveThrough() { final SortedMap<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } int oldSize = map.size(); if (map.size() < 2 || !supportsRemove) { return; } Iterator<Entry<K, V>> iterator = map.entrySet().iterator(); Entry<K, V> firstEntry = iterator.next(); Entry<K, V> secondEntry = iterator.next(); K key = secondEntry.getKey(); SortedMap<K, V> subMap = map.tailMap(key); subMap.remove(key); assertNull(subMap.remove(firstEntry.getKey())); assertEquals(map.size(), oldSize - 1); assertFalse(map.containsKey(key)); assertEquals(subMap.size(), oldSize - 2); } public void testTailMapClearThrough() { final SortedMap<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } int oldSize = map.size(); if (map.size() < 2 || !supportsClear) { return; } Iterator<Entry<K, V>> iterator = map.entrySet().iterator(); Entry<K, V> firstEntry = iterator.next(); Entry<K, V> secondEntry = iterator.next(); K key = secondEntry.getKey(); SortedMap<K, V> subMap = map.tailMap(key); int subMapSize = subMap.size(); subMap.clear(); assertEquals(map.size(), oldSize - subMapSize); assertTrue(subMap.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.testing; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.List; /** * Reserializes the sets created by another test set generator. * * TODO: make CollectionTestSuiteBuilder test reserialized collections * * @author Jesse Wilson */ public class ReserializingTestCollectionGenerator<E> implements TestCollectionGenerator<E> { private final TestCollectionGenerator<E> delegate; ReserializingTestCollectionGenerator(TestCollectionGenerator<E> delegate) { this.delegate = delegate; } public static <E> ReserializingTestCollectionGenerator<E> newInstance( TestCollectionGenerator<E> delegate) { return new ReserializingTestCollectionGenerator<E>(delegate); } @Override public Collection<E> create(Object... elements) { return reserialize(delegate.create(elements)); } @SuppressWarnings("unchecked") static <T> T reserialize(T object) { try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bytes); out.writeObject(object); ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(bytes.toByteArray())); return (T) in.readObject(); } catch (IOException e) { Helpers.fail(e, e.getMessage()); } catch (ClassNotFoundException e) { Helpers.fail(e, e.getMessage()); } throw new AssertionError("not reachable"); } @Override public SampleElements<E> samples() { return delegate.samples(); } @Override public E[] createArray(int length) { return delegate.createArray(length); } @Override public Iterable<E> order(List<E> insertionOrder) { return delegate.order(insertionOrder); } }
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; import java.util.Set; /** * Creates sets, containing sample elements, to be tested. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ public interface TestSetGenerator<E> extends TestCollectionGenerator<E> { @Override Set<E> create(Object... elements); }
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; import com.google.common.collect.testing.features.CollectionSize; import java.util.Collection; /** * The subject-generator interface accepted by Collection testers, for testing * a Collection at one particular {@link CollectionSize}. * * <p>This interface should not be implemented outside this package; * {@link PerCollectionSizeTestSuiteBuilder} constructs instances of it from * a more general {@link TestCollectionGenerator}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ public interface OneSizeTestContainerGenerator<T, E> extends TestSubjectGenerator<T>, TestContainerGenerator<T, E> { TestContainerGenerator<T, E> getInnerGenerator(); Collection<E> getSampleElements(int howMany); CollectionSize getCollectionSize(); }
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; 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 com.google.common.collect.testing.features.MapFeature; import com.google.common.collect.testing.testers.MapClearTester; import com.google.common.collect.testing.testers.MapContainsKeyTester; import com.google.common.collect.testing.testers.MapContainsValueTester; import com.google.common.collect.testing.testers.MapCreationTester; import com.google.common.collect.testing.testers.MapEqualsTester; import com.google.common.collect.testing.testers.MapGetTester; import com.google.common.collect.testing.testers.MapHashCodeTester; import com.google.common.collect.testing.testers.MapIsEmptyTester; import com.google.common.collect.testing.testers.MapPutAllTester; import com.google.common.collect.testing.testers.MapPutTester; import com.google.common.collect.testing.testers.MapRemoveTester; import com.google.common.collect.testing.testers.MapSerializationTester; import com.google.common.collect.testing.testers.MapSizeTester; import com.google.common.testing.SerializableTester; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Creates, based on your criteria, a JUnit test suite that exhaustively tests * a Map implementation. * * @author George van den Driessche */ public class MapTestSuiteBuilder<K, V> extends PerCollectionSizeTestSuiteBuilder< MapTestSuiteBuilder<K, V>, TestMapGenerator<K, V>, Map<K, V>, Map.Entry<K, V>> { public static <K, V> MapTestSuiteBuilder<K, V> using( TestMapGenerator<K, V> generator) { return new MapTestSuiteBuilder<K, V>().usingGenerator(generator); } @SuppressWarnings("unchecked") // Class parameters must be raw. @Override protected List<Class<? extends AbstractTester>> getTesters() { return Arrays.<Class<? extends AbstractTester>>asList( MapClearTester.class, MapContainsKeyTester.class, MapContainsValueTester.class, MapCreationTester.class, MapEqualsTester.class, MapGetTester.class, MapHashCodeTester.class, MapIsEmptyTester.class, MapPutTester.class, MapPutAllTester.class, MapRemoveTester.class, MapSerializationTester.class, MapSizeTester.class ); } @Override protected List<TestSuite> createDerivedSuites( FeatureSpecificTestSuiteBuilder< ?, ? extends OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>>> parentBuilder) { // TODO: Once invariant support is added, supply invariants to each of the // derived suites, to check that mutations to the derived collections are // reflected in the underlying map. List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder); if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) { derivedSuites.add(MapTestSuiteBuilder.using( new ReserializedMapGenerator<K, V>(parentBuilder.getSubjectGenerator())) .withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures())) .named(parentBuilder.getName() + " reserialized") .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); } derivedSuites.add(SetTestSuiteBuilder.using( new MapEntrySetGenerator<K, V>(parentBuilder.getSubjectGenerator())) .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures())) .named(parentBuilder.getName() + " entrySet") .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); derivedSuites.add(createDerivedKeySetSuite( new MapKeySetGenerator<K, V>(parentBuilder.getSubjectGenerator())) .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures())) .named(parentBuilder.getName() + " keys") .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); derivedSuites.add(CollectionTestSuiteBuilder.using( new MapValueCollectionGenerator<K, V>( parentBuilder.getSubjectGenerator())) .named(parentBuilder.getName() + " values") .withFeatures(computeValuesCollectionFeatures( parentBuilder.getFeatures())) .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); return derivedSuites; } protected SetTestSuiteBuilder<K> createDerivedKeySetSuite(TestSetGenerator<K> keySetGenerator) { return SetTestSuiteBuilder.using(keySetGenerator); } private static Set<Feature<?>> computeReserializedMapFeatures( Set<Feature<?>> mapFeatures) { Set<Feature<?>> derivedFeatures = Helpers.copyToSet(mapFeatures); derivedFeatures.remove(CollectionFeature.SERIALIZABLE); derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS); return derivedFeatures; } private static Set<Feature<?>> computeEntrySetFeatures( Set<Feature<?>> mapFeatures) { Set<Feature<?>> entrySetFeatures = computeCommonDerivedCollectionFeatures(mapFeatures); entrySetFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES); return entrySetFeatures; } private static Set<Feature<?>> computeKeySetFeatures( Set<Feature<?>> mapFeatures) { Set<Feature<?>> keySetFeatures = computeCommonDerivedCollectionFeatures(mapFeatures); if (mapFeatures.contains(MapFeature.ALLOWS_NULL_KEYS)) { keySetFeatures.add(CollectionFeature.ALLOWS_NULL_VALUES); } else if (mapFeatures.contains(MapFeature.ALLOWS_NULL_QUERIES)) { keySetFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES); } return keySetFeatures; } private static Set<Feature<?>> computeValuesCollectionFeatures( Set<Feature<?>> mapFeatures) { Set<Feature<?>> valuesCollectionFeatures = computeCommonDerivedCollectionFeatures(mapFeatures); valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES); if (mapFeatures.contains(MapFeature.ALLOWS_NULL_VALUES)) { valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_VALUES); } return valuesCollectionFeatures; } private static Set<Feature<?>> computeCommonDerivedCollectionFeatures( Set<Feature<?>> mapFeatures) { Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>(); if (mapFeatures.contains(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) { derivedFeatures.add(CollectionFeature.SERIALIZABLE); } if (mapFeatures.contains(MapFeature.SUPPORTS_REMOVE)) { derivedFeatures.add(CollectionFeature.SUPPORTS_REMOVE); derivedFeatures.add(CollectionFeature.SUPPORTS_REMOVE_ALL); derivedFeatures.add(CollectionFeature.SUPPORTS_RETAIN_ALL); } if (mapFeatures.contains(MapFeature.SUPPORTS_CLEAR)) { derivedFeatures.add(CollectionFeature.SUPPORTS_CLEAR); } if (mapFeatures.contains(MapFeature.REJECTS_DUPLICATES_AT_CREATION)) { derivedFeatures.add(CollectionFeature.REJECTS_DUPLICATES_AT_CREATION); } if (mapFeatures.contains(MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION)) { derivedFeatures.add(CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION); } // add the intersection of CollectionSize.values() and mapFeatures for (CollectionSize size : CollectionSize.values()) { if (mapFeatures.contains(size)) { derivedFeatures.add(size); } } return derivedFeatures; } private static class ReserializedMapGenerator<K, V> implements TestMapGenerator<K, V> { private final OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>> mapGenerator; public ReserializedMapGenerator( OneSizeTestContainerGenerator< Map<K, V>, Map.Entry<K, V>> mapGenerator) { this.mapGenerator = mapGenerator; } @Override public SampleElements<Map.Entry<K, V>> samples() { return mapGenerator.samples(); } @Override public Map.Entry<K, V>[] createArray(int length) { return mapGenerator.createArray(length); } @Override public Iterable<Map.Entry<K, V>> order( List<Map.Entry<K, V>> insertionOrder) { return mapGenerator.order(insertionOrder); } @Override public Map<K, V> create(Object... elements) { return SerializableTester.reserialize(mapGenerator.create(elements)); } @Override public K[] createKeyArray(int length) { return ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator()) .createKeyArray(length); } @Override public V[] createValueArray(int length) { return ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator()) .createValueArray(length); } } private static class MapEntrySetGenerator<K, V> implements TestSetGenerator<Map.Entry<K, V>> { private final OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>> mapGenerator; public MapEntrySetGenerator( OneSizeTestContainerGenerator< Map<K, V>, Map.Entry<K, V>> mapGenerator) { this.mapGenerator = mapGenerator; } @Override public SampleElements<Map.Entry<K, V>> samples() { return mapGenerator.samples(); } @Override public Set<Map.Entry<K, V>> create(Object... elements) { return mapGenerator.create(elements).entrySet(); } @Override public Map.Entry<K, V>[] createArray(int length) { return mapGenerator.createArray(length); } @Override public Iterable<Map.Entry<K, V>> order( List<Map.Entry<K, V>> insertionOrder) { return mapGenerator.order(insertionOrder); } } // TODO: investigate some API changes to SampleElements that would tidy up // parts of the following classes. private static class MapKeySetGenerator<K, V> implements TestSetGenerator<K> { private final OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>> mapGenerator; private final SampleElements<K> samples; public MapKeySetGenerator( OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>> mapGenerator) { this.mapGenerator = mapGenerator; final SampleElements<Map.Entry<K, V>> mapSamples = this.mapGenerator.samples(); this.samples = new SampleElements<K>( mapSamples.e0.getKey(), mapSamples.e1.getKey(), mapSamples.e2.getKey(), mapSamples.e3.getKey(), mapSamples.e4.getKey()); } @Override public SampleElements<K> samples() { return samples; } @Override public Set<K> create(Object... elements) { @SuppressWarnings("unchecked") K[] keysArray = (K[]) elements; // Start with a suitably shaped collection of entries Collection<Map.Entry<K, V>> originalEntries = mapGenerator.getSampleElements(elements.length); // Create a copy of that, with the desired value for each key Collection<Map.Entry<K, V>> entries = new ArrayList<Entry<K, V>>(elements.length); int i = 0; for (Map.Entry<K, V> entry : originalEntries) { entries.add(Helpers.mapEntry(keysArray[i++], entry.getValue())); } return mapGenerator.create(entries.toArray()).keySet(); } @Override public K[] createArray(int length) { // TODO: with appropriate refactoring of OneSizeGenerator, we can perhaps // tidy this up and get rid of the casts here and in // MapValueCollectionGenerator. return ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator()) .createKeyArray(length); } @Override public Iterable<K> order(List<K> insertionOrder) { return insertionOrder; } } private static class MapValueCollectionGenerator<K, V> implements TestCollectionGenerator<V> { private final OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>> mapGenerator; private final SampleElements<V> samples; public MapValueCollectionGenerator( OneSizeTestContainerGenerator< Map<K, V>, Map.Entry<K, V>> mapGenerator) { this.mapGenerator = mapGenerator; final SampleElements<Map.Entry<K, V>> mapSamples = this.mapGenerator.samples(); this.samples = new SampleElements<V>( mapSamples.e0.getValue(), mapSamples.e1.getValue(), mapSamples.e2.getValue(), mapSamples.e3.getValue(), mapSamples.e4.getValue()); } @Override public SampleElements<V> samples() { return samples; } @Override public Collection<V> create(Object... elements) { @SuppressWarnings("unchecked") V[] valuesArray = (V[]) elements; // Start with a suitably shaped collection of entries Collection<Map.Entry<K, V>> originalEntries = mapGenerator.getSampleElements(elements.length); // Create a copy of that, with the desired value for each value Collection<Map.Entry<K, V>> entries = new ArrayList<Entry<K, V>>(elements.length); int i = 0; for (Map.Entry<K, V> entry : originalEntries) { entries.add(Helpers.mapEntry(entry.getKey(), valuesArray[i++])); } return mapGenerator.create(entries.toArray()).values(); } @Override public V[] createArray(int length) { //noinspection UnnecessaryLocalVariable final V[] vs = ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator()) .createValueArray(length); return vs; } @Override public Iterable<V> order(List<V> insertionOrder) { return insertionOrder; } } }
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; /** * A sample enumerated type we use for testing. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ public enum AnEnum { A, B, C, D, E, F }
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; import java.util.Map; /** * Creates maps, containing sample elements, to be tested. * * <p>This class is GWT compatible. * * @author George van den Driessche */ public interface TestMapGenerator<K, V> extends TestContainerGenerator<Map<K, V>, Map.Entry<K, V>> { K[] createKeyArray(int length); V[] createValueArray(int 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.testing; import com.google.common.collect.testing.SampleElements.Colliders; import java.util.List; /** * A generator using sample elements whose hash codes all collide badly. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ public abstract class TestCollidingSetGenerator implements TestSetGenerator<Object> { @Override public SampleElements<Object> samples() { return new Colliders(); } @Override public Object[] createArray(int length) { return new Object[length]; } /** Returns the original element list, unchanged. */ @Override public List<Object> order(List<Object> insertionOrder) { return insertionOrder; } }
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; import com.google.common.collect.testing.features.CollectionSize; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * Generator for collection of a particular size. * * <p>This class is GWT compatible. * * @author George van den Driessche */ public final class OneSizeGenerator<T, E> implements OneSizeTestContainerGenerator<T, E> { private final TestContainerGenerator<T, E> generator; private final CollectionSize collectionSize; public OneSizeGenerator(TestContainerGenerator<T, E> generator, CollectionSize collectionSize) { this.generator = generator; this.collectionSize = collectionSize; } @Override public TestContainerGenerator<T, E> getInnerGenerator() { return generator; } @Override public SampleElements<E> samples() { return generator.samples(); } @Override public T create(Object... elements) { return generator.create(elements); } @Override public E[] createArray(int length) { return generator.createArray(length); } @Override public T createTestSubject() { Collection<E> elements = getSampleElements( getCollectionSize().getNumElements()); return generator.create(elements.toArray()); } @Override public Collection<E> getSampleElements(int howMany) { SampleElements<E> samples = samples(); @SuppressWarnings("unchecked") List<E> allSampleElements = Arrays.asList( samples.e0, samples.e1, samples.e2, samples.e3, samples.e4); return new ArrayList<E>(allSampleElements.subList(0, howMany)); } @Override public CollectionSize getCollectionSize() { return collectionSize; } @Override public Iterable<E> order(List<E> insertionOrder) { return generator.order(insertionOrder); } }
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; import junit.framework.TestCase; /** * This abstract base class for testers allows the framework to inject needed * information after JUnit constructs the instances. * * <p>This class is emulated in GWT. * * @param <G> the type of the test generator required by this tester. An * instance of G should somehow provide an instance of the class under test, * plus any other information required to parameterize the test. * * @author George van den Driessche */ public class AbstractTester<G> extends TestCase { private G subjectGenerator; private String suiteName; private Runnable setUp; private Runnable tearDown; // public so that it can be referenced in generated GWT tests. @Override public void setUp() throws Exception { if (setUp != null) { setUp.run(); } } // public so that it can be referenced in generated GWT tests. @Override public void tearDown() throws Exception { if (tearDown != null) { tearDown.run(); } } // public so that it can be referenced in generated GWT tests. public final void init( G subjectGenerator, String suiteName, Runnable setUp, Runnable tearDown) { this.subjectGenerator = subjectGenerator; this.suiteName = suiteName; this.setUp = setUp; this.tearDown = tearDown; } // public so that it can be referenced in generated GWT tests. public final void init(G subjectGenerator, String suiteName) { init(subjectGenerator, suiteName, null, null); } public G getSubjectGenerator() { return subjectGenerator; } /** Returns the name of the test method invoked by this test instance. */ public final String getTestMethodName() { return super.getName(); } @Override public String getName() { return Platform.format("%s[%s]", super.getName(), suiteName); } }
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; /** * An unhashable object to be used in testing as values in our collections. * * <p>This class is GWT compatible. * * @author Regina O'Dell */ public class UnhashableObject implements Comparable<UnhashableObject> { private final int value; public UnhashableObject(int value) { this.value = value; } @Override public boolean equals(Object object) { if (object instanceof UnhashableObject) { UnhashableObject that = (UnhashableObject) object; return this.value == that.value; } return false; } @Override public int hashCode() { throw new UnsupportedOperationException(); } // needed because otherwise Object.toString() calls hashCode() @Override public String toString() { return "DontHashMe" + value; } @Override public int compareTo(UnhashableObject o) { return (this.value < o.value) ? -1 : (this.value > o.value) ? 1 : 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.testing; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import junit.framework.Test; import junit.framework.TestSuite; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; /** * Generates a test suite covering the {@link Map} implementations in the * {@link java.util} package. Can be subclassed to specify tests that should * be suppressed. * * @author Kevin Bourrillion */ public class TestsForMapsInJavaUtil { public static Test suite() { return new TestsForMapsInJavaUtil().allTests(); } public Test allTests() { TestSuite suite = new TestSuite("java.util Maps"); suite.addTest(testsForEmptyMap()); suite.addTest(testsForSingletonMap()); suite.addTest(testsForHashMap()); suite.addTest(testsForLinkedHashMap()); suite.addTest(testsForTreeMap()); suite.addTest(testsForEnumMap()); suite.addTest(testsForConcurrentHashMap()); return suite; } protected Collection<Method> suppressForEmptyMap() { return Collections.emptySet(); } protected Collection<Method> suppressForSingletonMap() { return Collections.emptySet(); } protected Collection<Method> suppressForHashMap() { return Collections.emptySet(); } protected Collection<Method> suppressForLinkedHashMap() { return Collections.emptySet(); } protected Collection<Method> suppressForTreeMap() { return Collections.emptySet(); } protected Collection<Method> suppressForEnumMap() { return Collections.emptySet(); } protected Collection<Method> suppressForConcurrentHashMap() { return Collections.emptySet(); } public Test testsForEmptyMap() { return MapTestSuiteBuilder .using(new TestStringMapGenerator() { @Override protected Map<String, String> create( Entry<String, String>[] entries) { return Collections.emptyMap(); } }) .named("emptyMap") .withFeatures( CollectionFeature.SERIALIZABLE, CollectionSize.ZERO) .suppressing(suppressForEmptyMap()) .createTestSuite(); } public Test testsForSingletonMap() { return MapTestSuiteBuilder .using(new TestStringMapGenerator() { @Override protected Map<String, String> create( Entry<String, String>[] entries) { return Collections.singletonMap( entries[0].getKey(), entries[0].getValue()); } }) .named("singletonMap") .withFeatures( MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_NULL_VALUES, CollectionFeature.SERIALIZABLE, CollectionSize.ONE) .suppressing(suppressForSingletonMap()) .createTestSuite(); } public Test testsForHashMap() { return MapTestSuiteBuilder .using(new TestStringMapGenerator() { @Override protected Map<String, String> create( Entry<String, String>[] entries) { return toHashMap(entries); } @Override public Iterable<Entry<String, String>> order( List<Entry<String, String>> insertionOrder) { /* * For convenience, make this test double as a test that no tester * calls order() on a container without the KNOWN_ORDER feature. */ throw new UnsupportedOperationException(); } }) .named("HashMap") .withFeatures( MapFeature.GENERAL_PURPOSE, MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_NULL_VALUES, MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForHashMap()) .createTestSuite(); } public Test testsForLinkedHashMap() { return MapTestSuiteBuilder .using(new TestStringMapGenerator() { @Override protected Map<String, String> create( Entry<String, String>[] entries) { return populate(new LinkedHashMap<String, String>(), entries); } }) .named("LinkedHashMap") .withFeatures( MapFeature.GENERAL_PURPOSE, MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_NULL_VALUES, MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionFeature.KNOWN_ORDER, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForLinkedHashMap()) .createTestSuite(); } public Test testsForTreeMap() { return NavigableMapTestSuiteBuilder .using(new TestStringMapGenerator() { @Override protected Map<String, String> create( Entry<String, String>[] entries) { return populate(new TreeMap<String, String>( arbitraryNullFriendlyComparator()), entries); } }) .named("TreeMap") .withFeatures( MapFeature.GENERAL_PURPOSE, MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_NULL_VALUES, MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionFeature.KNOWN_ORDER, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForTreeMap()) .createTestSuite(); } public Test testsForEnumMap() { return MapTestSuiteBuilder .using(new TestEnumMapGenerator() { @Override protected Map<AnEnum, String> create( Entry<AnEnum, String>[] entries) { return populate( new EnumMap<AnEnum, String>(AnEnum.class), entries); } }) .named("EnumMap") .withFeatures( MapFeature.GENERAL_PURPOSE, MapFeature.ALLOWS_NULL_VALUES, MapFeature.RESTRICTS_KEYS, CollectionFeature.KNOWN_ORDER, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForEnumMap()) .createTestSuite(); } public Test testsForConcurrentHashMap() { return MapTestSuiteBuilder .using(new TestStringMapGenerator() { @Override protected Map<String, String> create( Entry<String, String>[] entries) { return populate(new ConcurrentHashMap<String, String>(), entries); } }) .named("ConcurrentHashMap") .withFeatures( MapFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForConcurrentHashMap()) .createTestSuite(); } // TODO: IdentityHashMap, AbstractMap private static Map<String, String> toHashMap( Entry<String, String>[] entries) { return populate(new HashMap<String, String>(), entries); } // TODO: call conversion constructors or factory methods instead of using // populate() on an empty map private static <T> Map<T, String> populate( Map<T, String> map, Entry<T, String>[] entries) { for (Entry<T, String> entry : entries) { map.put(entry.getKey(), entry.getValue()); } return map; } static <T> Comparator<T> arbitraryNullFriendlyComparator() { return new NullFriendlyComparator<T>(); } private static final class NullFriendlyComparator<T> implements Comparator<T>, Serializable { @Override public int compare(T left, T right) { return String.valueOf(left).compareTo(String.valueOf(right)); } } }
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; import com.google.common.collect.testing.SampleElements.Enums; import java.util.Collections; import java.util.List; import java.util.Set; /** * An abstract TestSetGenerator for generating sets containing enum values. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ public abstract class TestEnumSetGenerator implements TestSetGenerator<AnEnum> { @Override public SampleElements<AnEnum> samples() { return new Enums(); } @Override public Set<AnEnum> create(Object... elements) { AnEnum[] array = new AnEnum[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (AnEnum) e; } return create(array); } protected abstract Set<AnEnum> create(AnEnum[] elements); @Override public AnEnum[] createArray(int length) { return new AnEnum[length]; } /** * Sorts the enums according to their natural ordering. */ @Override public List<AnEnum> order(List<AnEnum> insertionOrder) { Collections.sort(insertionOrder); return insertionOrder; } }
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.testing; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import junit.framework.Assert; import junit.framework.AssertionFailedError; /** * Tests serialization and deserialization of an object, optionally asserting * that the resulting object is equal to the original. * * <p><b>GWT warning:</b> Under GWT, both methods simply returns their input, * as proper GWT serialization tests require more setup. This no-op behavior * allows test authors to intersperse {@code SerializableTester} calls with * other, GWT-compatible tests. * * * @author Mike Bostock * @since 10.0 */ @Beta @GwtCompatible // but no-op! public final class SerializableTester { private SerializableTester() {} /** * Serializes and deserializes the specified object. * * <p><b>GWT warning:</b> Under GWT, this method simply returns its input, as * proper GWT serialization tests require more setup. This no-op behavior * allows test authors to intersperse {@code SerializableTester} calls with * other, GWT-compatible tests. * * <p>Note that the specified object may not be known by the compiler to be a * {@link java.io.Serializable} instance, and is thus declared an * {@code Object}. For example, it might be declared as a {@code List}. * * @return the re-serialized object * @throws RuntimeException if the specified object was not successfully * serialized or deserialized */ @SuppressWarnings("unchecked") public static <T> T reserialize(T object) { return Platform.reserialize(object); } /** * Serializes and deserializes the specified object and verifies that the * re-serialized object is equal to the provided object, that the hashcodes * are identical, and that the class of the re-serialized object is identical * to that of the original. * * <p><b>GWT warning:</b> Under GWT, this method simply returns its input, as * proper GWT serialization tests require more setup. This no-op behavior * allows test authors to intersperse {@code SerializableTester} calls with * other, GWT-compatible tests. * * <p>Note that the specified object may not be known by the compiler to be a * {@link java.io.Serializable} instance, and is thus declared an * {@code Object}. For example, it might be declared as a {@code List}. * * <p>Note also that serialization is not in general required to return an * object that is {@linkplain Object#equals equal} to the original, nor is it * required to return even an object of the same class. For example, if * sublists of {@code MyList} instances were serializable, those sublists * might implement a private {@code MySubList} type but serialize as a plain * {@code MyList} to save space. So long as {@code MyList} has all the public * supertypes of {@code MySubList}, this is safe. For these cases, for which * {@code reserializeAndAssert} is too strict, use {@link #reserialize}. * * @return the re-serialized object * @throws RuntimeException if the specified object was not successfully * serialized or deserialized * @throws AssertionFailedError if the re-serialized object is not equal to * the original object, or if the hashcodes are different. */ public static <T> T reserializeAndAssert(T object) { T copy = reserialize(object); new EqualsTester() .addEqualityGroup(object, copy) .testEquals(); Assert.assertEquals(object.getClass(), copy.getClass()); return copy; } }
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.Beta; import com.google.common.annotations.GwtCompatible; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * A {@code TearDownStack} contains a stack of {@link TearDown} instances. * * @author Kevin Bourrillion * @since 10.0 */ @Beta @GwtCompatible public class TearDownStack implements TearDownAccepter { public static final Logger logger = Logger.getLogger(TearDownStack.class.getName()); final LinkedList<TearDown> stack = new LinkedList<TearDown>(); private final boolean suppressThrows; public TearDownStack() { this.suppressThrows = false; } public TearDownStack(boolean suppressThrows) { this.suppressThrows = suppressThrows; } @Override public final void addTearDown(TearDown tearDown) { stack.addFirst(tearDown); } /** * Causes teardown to execute. */ public final void runTearDown() { List<Throwable> exceptions = new ArrayList<Throwable>(); for (TearDown tearDown : stack) { try { tearDown.tearDown(); } catch (Throwable t) { if (suppressThrows) { TearDownStack.logger.log(Level.INFO, "exception thrown during tearDown: " + t.getMessage(), t); } else { exceptions.add(t); } } } stack.clear(); if ((!suppressThrows) && (exceptions.size() > 0)) { throw ClusterException.create(exceptions); } } }
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 java.util.concurrent.TimeUnit.SECONDS; import com.google.common.annotations.Beta; import java.lang.ref.WeakReference; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; /** * Testing utilities relating to garbage collection finalization. * * <p>Use this class to test code triggered by <em>finalization</em>, that is, one of the * following actions taken by the java garbage collection system: * * <ul> * <li>invoking the {@code finalize} methods of unreachable objects * <li>clearing weak references to unreachable referents * <li>enqueuing weak references to unreachable referents in their reference queue * </ul> * * <p>This class uses (possibly repeated) invocations of {@link java.lang.System#gc()} to cause * finalization to happen. However, a call to {@code System.gc()} is specified to be no more * than a hint, so this technique may fail at the whim of the JDK implementation, for example if * a user specified the JVM flag {@code -XX:+DisableExplicitGC}. But in practice, it works very * well for ordinary tests. * * <p>Failure of the expected event to occur within an implementation-defined "reasonable" time * period or an interrupt while waiting for the expected event will result in a {@link * RuntimeException}. * * <p>Here's an example that tests a {@code finalize} method: * * <pre> {@code * final CountDownLatch latch = new CountDownLatch(1); * Object x = new MyClass() { * ... * protected void finalize() { latch.countDown(); ... } * }; * x = null; // Hint to the JIT that x is stack-unreachable * GcFinalization.await(latch); * }</pre> * * <p>Here's an example that uses a user-defined finalization predicate: * * <pre> {@code * final WeakHashMap<Object, Object> map = new WeakHashMap<Object, Object>(); * map.put(new Object(), Boolean.TRUE); * GcFinalization.awaitDone(new FinalizationPredicate() { * public boolean isDone() { * return map.isEmpty(); * } * }); * }</pre> * * <p>Even if your non-test code does not use finalization, you can * use this class to test for leaks, by ensuring that objects are no * longer strongly referenced: * * <pre> {@code * // Helper function keeps victim stack-unreachable. * private WeakReference<Foo> fooWeakRef() { * Foo x = ....; * WeakReference<Foo> weakRef = new WeakReference<Foo>(x); * // ... use x ... * x = null; // Hint to the JIT that x is stack-unreachable * return weakRef; * } * public void testFooLeak() { * GcFinalization.awaitClear(fooWeakRef()); * }</pre> * * <p>This class cannot currently be used to test soft references, since this class does not try to * create the memory pressure required to cause soft references to be cleared. * * <p>This class only provides testing utilities. It is not designed for direct use in production * or for benchmarking. * * @author schmoe@google.com (mike nonemacher) * @author martinrb@google.com (Martin Buchholz) * @since 11.0 */ @Beta public final class GcFinalization { private GcFinalization() {} /** * 10 seconds ought to be long enough for any object to be GC'ed and finalized. Unless we have a * gigantic heap, in which case we scale by heap size. */ private static long timeoutSeconds() { // This class can make no hard guarantees. The methods in this class are inherently flaky, but // we try hard to make them robust in practice. We could additionally try to add in a system // load timeout multiplier. Or we could try to use a CPU time bound instead of wall clock time // bound. But these ideas are harder to implement. We do not try to detect or handle a // user-specified -XX:+DisableExplicitGC. // // TODO(user): Consider using // java/lang/management/OperatingSystemMXBean.html#getSystemLoadAverage() // // TODO(user): Consider scaling by number of mutator threads, // e.g. using Thread#activeCount() return Math.max(10L, Runtime.getRuntime().totalMemory() / (32L * 1024L * 1024L)); } /** * Waits until the given future {@linkplain Future#isDone is done}, invoking the garbage * collector as necessary to try to ensure that this will happen. * * @throws RuntimeException if timed out or interrupted while waiting */ public static void awaitDone(Future<?> future) { if (future.isDone()) { return; } final long timeoutSeconds = timeoutSeconds(); final long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds); do { System.runFinalization(); if (future.isDone()) { return; } System.gc(); try { future.get(1L, SECONDS); return; } catch (CancellationException ok) { return; } catch (ExecutionException ok) { return; } catch (InterruptedException ie) { throw new RuntimeException("Unexpected interrupt while waiting for future", ie); } catch (TimeoutException tryHarder) { /* OK */ } } while (System.nanoTime() - deadline < 0); throw new RuntimeException( String.format("Future not done within %d second timeout", timeoutSeconds)); } /** * Waits until the given latch has {@linkplain CountDownLatch#countDown counted down} to zero, * invoking the garbage collector as necessary to try to ensure that this will happen. * * @throws RuntimeException if timed out or interrupted while waiting */ public static void await(CountDownLatch latch) { if (latch.getCount() == 0) { return; } final long timeoutSeconds = timeoutSeconds(); final long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds); do { System.runFinalization(); if (latch.getCount() == 0) { return; } System.gc(); try { if (latch.await(1L, SECONDS)) { return; } } catch (InterruptedException ie) { throw new RuntimeException("Unexpected interrupt while waiting for latch", ie); } } while (System.nanoTime() - deadline < 0); throw new RuntimeException( String.format("Latch failed to count down within %d second timeout", timeoutSeconds)); } /** * Creates a garbage object that counts down the latch in its finalizer. Sequestered into a * separate method to make it somewhat more likely to be unreachable. */ private static void createUnreachableLatchFinalizer(final CountDownLatch latch) { new Object() { @Override protected void finalize() { latch.countDown(); }}; } /** * A predicate that is expected to return true subsequent to <em>finalization</em>, that is, one * of the following actions taken by the garbage collector when performing a full collection in * response to {@link System#gc()}: * * <ul> * <li>invoking the {@code finalize} methods of unreachable objects * <li>clearing weak references to unreachable referents * <li>enqueuing weak references to unreachable referents in their reference queue * </ul> */ public interface FinalizationPredicate { boolean isDone(); } /** * Waits until the given predicate returns true, invoking the garbage collector as necessary to * try to ensure that this will happen. * * @throws RuntimeException if timed out or interrupted while waiting */ public static void awaitDone(FinalizationPredicate predicate) { if (predicate.isDone()) { return; } final long timeoutSeconds = timeoutSeconds(); final long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds); do { System.runFinalization(); if (predicate.isDone()) { return; } CountDownLatch done = new CountDownLatch(1); createUnreachableLatchFinalizer(done); await(done); if (predicate.isDone()) { return; } } while (System.nanoTime() - deadline < 0); throw new RuntimeException( String.format("Predicate did not become true within %d second timeout", timeoutSeconds)); } /** * Waits until the given weak reference is cleared, invoking the garbage collector as necessary * to try to ensure that this will happen. * * <p>This is a convenience method, equivalent to: * <pre> {@code * awaitDone(new FinalizationPredicate() { * public boolean isDone() { * return ref.get() == null; * } * }); * }</pre> * * @throws RuntimeException if timed out or interrupted while waiting */ public static void awaitClear(final WeakReference<?> ref) { awaitDone(new FinalizationPredicate() { public boolean isDone() { return ref.get() == null; } }); } /** * Tries to perform a "full" garbage collection cycle (including processing of weak references * and invocation of finalize methods) and waits for it to complete. Ensures that at least one * weak reference has been cleared and one {@code finalize} method has been run before this * method returns. This method may be useful when testing the garbage collection mechanism * itself, or inhibiting a spontaneous GC initiation in subsequent code. * * <p>In contrast, a plain call to {@link java.lang.System#gc()} does not ensure finalization * processing and may run concurrently, for example, if the JVM flag {@code * -XX:+ExplicitGCInvokesConcurrent} is used. * * <p>Whenever possible, it is preferable to test directly for some observable change resulting * from GC, as with {@link #awaitClear}. Because there are no guarantees for the order of GC * finalization processing, there may still be some unfinished work for the GC to do after this * method returns. * * <p>This method does not create any memory pressure as would be required to cause soft * references to be processed. * * @throws RuntimeException if timed out or interrupted while waiting * @since 12.0 */ public static void awaitFullGc() { final CountDownLatch finalizerRan = new CountDownLatch(1); WeakReference<Object> ref = new WeakReference<Object>( new Object() { @Override protected void finalize() { finalizerRan.countDown(); } }); await(finalizerRan); awaitClear(ref); // Hope to catch some stragglers queued up behind our finalizable object System.runFinalization(); } }
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.Beta; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Handler; import java.util.logging.LogRecord; /** * Tests may use this to intercept messages that are logged by the code under * test. Example: * <pre> * TestLogHandler handler; * * protected void setUp() throws Exception { * super.setUp(); * handler = new TestLogHandler(); * SomeClass.logger.addHandler(handler); * addTearDown(new TearDown() { * public void tearDown() throws Exception { * SomeClass.logger.removeHandler(handler); * } * }); * } * * public void test() { * SomeClass.foo(); * LogRecord firstRecord = handler.getStoredLogRecords().get(0); * assertEquals("some message", firstRecord.getMessage()); * } * </pre> * * @author Kevin Bourrillion * @since 10.0 */ @Beta public class TestLogHandler extends Handler { /** We will keep a private list of all logged records */ private final List<LogRecord> list = Collections.synchronizedList(new ArrayList<LogRecord>()); /** * Adds the most recently logged record to our list. */ @Override public void publish(LogRecord record) { list.add(record); } @Override public void flush() { } @Override public void close() { } public void clear() { list.clear(); } /** * Fetch the list of logged records * @return unmodifiable LogRecord list of all logged records */ public List<LogRecord> getStoredLogRecords() { List<LogRecord> result = new ArrayList<LogRecord>(list); return Collections.unmodifiableList(result); } }
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; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Equivalence; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.testing.RelationshipTester.RelationshipAssertion; import java.util.List; /** * Tester for {@link Equivalence} relationships between groups of objects. * * <p> * To use, create a new {@link EquivalenceTester} and add equivalence groups * where each group contains objects that are supposed to be equal to each * other. Objects of different groups are expected to be unequal. For example: * * <pre> * {@code * EquivalenceTester.of(someStringEquivalence) * .addEquivalenceGroup("hello", "h" + "ello") * .addEquivalenceGroup("world", "wor" + "ld") * .test(); * } * </pre> * * <p> * Note that testing {@link Objects#equals(Object)} is more simply done using * the {@link EqualsTester}. It includes an extra test against an instance of an * arbitrary class without having to explicitly add another equivalence group. * * @author Gregory Kick * @since 10.0 * * TODO(gak): turn this into a test suite so that each test can fail * independently */ @Beta @GwtCompatible public final class EquivalenceTester<T> { private static final int REPETITIONS = 3; private final Equivalence<? super T> equivalence; private final RelationshipTester<T> delegate; private final List<T> items = Lists.newArrayList(); EquivalenceTester(final Equivalence<? super T> equivalence) { this.equivalence = checkNotNull(equivalence); this.delegate = new RelationshipTester<T>(new RelationshipAssertion<T>() { @Override public void assertRelated(T item, T related) { assertTrue("$ITEM must be equivalent to $RELATED", equivalence.equivalent(item, related)); int itemHash = equivalence.hash(item); int relatedHash = equivalence.hash(related); assertEquals("the hash (" + itemHash + ") of $ITEM must be equal to the hash (" + relatedHash + ") of $RELATED", itemHash, relatedHash); } @Override public void assertUnrelated(T item, T unrelated) { assertTrue("$ITEM must be inequivalent to $UNRELATED", !equivalence.equivalent(item, unrelated)); } }); } public static <T> EquivalenceTester<T> of(Equivalence<? super T> equivalence) { return new EquivalenceTester<T>(equivalence); } /** * Adds a group of objects that are supposed to be equivalent to each other * and not equivalent to objects in any other equivalence group added to this * tester. */ public EquivalenceTester<T> addEquivalenceGroup(T first, T... rest) { addEquivalenceGroup(Lists.asList(first, rest)); return this; } public EquivalenceTester<T> addEquivalenceGroup(Iterable<T> group) { delegate.addRelatedGroup(group); items.addAll(ImmutableList.copyOf(group)); return this; } /** Run tests on equivalence methods, throwing a failure on an invalid test */ public EquivalenceTester<T> test() { for (int run = 0; run < REPETITIONS; run++) { testItems(); delegate.test(); } return this; } private void testItems() { for (T item : items) { assertTrue(item + " must be inequivalent to null", !equivalence.equivalent(item, null)); assertTrue("null must be inequivalent to " + item, !equivalence.equivalent(null, item)); assertTrue(item + " must be equivalent to itself", equivalence.equivalent(item, item)); assertEquals("the hash of " + item + " must be consistent", equivalence.hash(item), equivalence.hash(item)); } } }
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.Beta; import com.google.common.annotations.GwtCompatible; /** * An object that can perform a {@link #tearDown} operation. * * @author Kevin Bourrillion * @since 10.0 */ @Beta @GwtCompatible public interface TearDown { /** * Performs a <b>single</b> tear-down operation. See test-libraries-for-java's * {@code com.google.common.testing.junit3.TearDownTestCase} and * {@code com.google.common.testing.junit4.TearDownTestCase} for example. * * <p>A failing {@link TearDown} may or may not fail a tl4j test, depending on * the version of JUnit test case you are running under. To avoid failing in * the face of an exception regardless of JUnit version, implement a {@link * SloppyTearDown} instead. * * <p>tl4j details: For backwards compatibility, {@code * junit3.TearDownTestCase} currently does not fail a test when an exception * is thrown from one of its {@link TearDown}s, but this is subject to * change. Also, {@code junit4.TearDownTestCase} will. * * @throws Exception for any reason. {@code TearDownTestCase} ensures that * any exception thrown will not interfere with other TearDown * operations. */ void tearDown() throws Exception; }
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; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import junit.framework.AssertionFailedError; import java.util.List; /** * Tests a collection of objects according to the rules specified in a * {@link RelationshipAssertion}. * * @author Gregory Kick */ @GwtCompatible final class RelationshipTester<T> { private final List<ImmutableList<T>> groups = Lists.newArrayList(); private final RelationshipAssertion<T> assertion; RelationshipTester(RelationshipAssertion<T> assertion) { this.assertion = checkNotNull(assertion); } public RelationshipTester<T> addRelatedGroup(Iterable<? extends T> group) { groups.add(ImmutableList.copyOf(group)); return this; } public void test() { for (int groupNumber = 0; groupNumber < groups.size(); groupNumber++) { ImmutableList<T> group = groups.get(groupNumber); for (int itemNumber = 0; itemNumber < group.size(); itemNumber++) { // check related items in same group for (int relatedItemNumber = 0; relatedItemNumber < group.size(); relatedItemNumber++) { if (itemNumber != relatedItemNumber) { assertRelated(groupNumber, itemNumber, relatedItemNumber); } } // check unrelated items in all other groups for (int unrelatedGroupNumber = 0; unrelatedGroupNumber < groups.size(); unrelatedGroupNumber++) { if (groupNumber != unrelatedGroupNumber) { ImmutableList<T> unrelatedGroup = groups.get(unrelatedGroupNumber); for (int unrelatedItemNumber = 0; unrelatedItemNumber < unrelatedGroup.size(); unrelatedItemNumber++) { assertUnrelated(groupNumber, itemNumber, unrelatedGroupNumber, unrelatedItemNumber); } } } } } } private void assertRelated(int groupNumber, int itemNumber, int relatedItemNumber) { ImmutableList<T> group = groups.get(groupNumber); T item = group.get(itemNumber); T related = group.get(relatedItemNumber); try { assertion.assertRelated(item, related); } catch (AssertionFailedError e) { // TODO(gak): special handling for ComparisonFailure? throw new AssertionFailedError(e.getMessage() .replace("$ITEM", itemString(item, groupNumber, itemNumber)) .replace("$RELATED", itemString(related, groupNumber, relatedItemNumber))); } } private void assertUnrelated(int groupNumber, int itemNumber, int unrelatedGroupNumber, int unrelatedItemNumber) { T item = groups.get(groupNumber).get(itemNumber); T unrelated = groups.get(unrelatedGroupNumber).get(unrelatedItemNumber); try { assertion.assertUnrelated(item, unrelated); } catch (AssertionFailedError e) { // TODO(gak): special handling for ComparisonFailure? throw new AssertionFailedError(e.getMessage() .replace("$ITEM", itemString(item, groupNumber, itemNumber)) .replace("$UNRELATED", itemString(unrelated, unrelatedGroupNumber, unrelatedItemNumber))); } } private static String itemString(Object item, int groupNumber, int itemNumber) { return new StringBuilder() .append(item) .append(" [group ") .append(groupNumber + 1) .append(", item ") .append(itemNumber + 1) .append(']') .toString(); } /** * A strategy for testing the relationship between objects. Methods are expected to throw * {@link AssertionFailedError} whenever the relationship is violated. * * <p>As a convenience, any occurrence of {@code $ITEM}, {@code $RELATED} or {@code $UNRELATED} in * the error message will be replaced with a string that combines the {@link Object#toString()}, * item number and group number of the respective item. * */ interface RelationshipAssertion<T> { void assertRelated(T item, T related); void assertUnrelated(T item, T unrelated); } }
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.testing; import static com.google.common.base.Preconditions.checkNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Methods factored out so that they can be emulated differently in GWT. * * @author Chris Povirk */ final class Platform { /** * Serializes and deserializes the specified object. */ @SuppressWarnings("unchecked") static <T> T reserialize(T object) { checkNotNull(object); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try { ObjectOutputStream out = new ObjectOutputStream(bytes); out.writeObject(object); ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(bytes.toByteArray())); return (T) in.readObject(); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } private Platform() {} }
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.testing; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.logging.Level; import java.util.logging.Logger; /** * Simple utility for when you want to create a {@link TearDown} that may throw * an exception but should not fail a test when it does. (The behavior of a * {@code TearDown} that throws an exception varies; see its documentation for * details.) Use it just like a {@code TearDown}, except override {@link * #sloppyTearDown()} instead. * * @author Luiz-Otavio Zorzella * @since 10.0 */ @Beta @GwtCompatible public abstract class SloppyTearDown implements TearDown { public static final Logger logger = Logger.getLogger(SloppyTearDown.class.getName()); @Override public final void tearDown() { try { sloppyTearDown(); } catch (Throwable t) { logger.log(Level.INFO, "exception thrown during tearDown: " + t.getMessage(), t); } } public abstract void sloppyTearDown() throws Exception; }
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.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Ticker; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * A Ticker whose value can be advanced programmatically in test. * <p> * This class is thread-safe. * * @author Jige Yu * @since 10.0 */ @Beta @GwtCompatible public class FakeTicker extends Ticker { private final AtomicLong nanos = new AtomicLong(); /** Advances the ticker value by {@code time} in {@code timeUnit}. */ public FakeTicker advance(long time, TimeUnit timeUnit) { return advance(timeUnit.toNanos(time)); } /** Advances the ticker value by {@code nanoseconds}. */ public FakeTicker advance(long nanoseconds) { nanos.addAndGet(nanoseconds); return this; } @Override public long read() { return nanos.get(); } }
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.Beta; import com.google.common.annotations.GwtCompatible; /** * Any object which can accept registrations of {@link TearDown} instances. * * @author Kevin Bourrillion * @since 10.0 */ @Beta @GwtCompatible public interface TearDownAccepter { /** * Registers a TearDown implementor which will be run after the test proper. * * <p>In JUnit4 language, that means as an {@code @After}. * * <p>In JUnit3 language, that means during the * {@link junit.framework.TestCase#tearDown()} step. */ void addTearDown(TearDown tearDown); }
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.testing; import static com.google.common.base.Preconditions.checkNotNull; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.testing.RelationshipTester.RelationshipAssertion; import java.util.List; /** * Tester for equals() and hashCode() methods of a class. * * <p>To use, create a new EqualsTester and add equality groups where each group * contains objects that are supposed to be equal to each other, and objects of * different groups are expected to be unequal. For example: * <pre> * new EqualsTester() * .addEqualityGroup("hello", "h" + "ello") * .addEqualityGroup("world", "wor" + "ld") * .addEqualityGroup(2, 1 + 1) * .testEquals(); * </pre> * This tests: * <ul> * <li>comparing each object against itself returns true * <li>comparing each object against null returns false * <li>comparing each object an instance of an incompatible class returns false * <li>comparing each pair of objects within the same equality group returns * true * <li>comparing each pair of objects from different equality groups returns * false * <li>the hash code of any two equal objects are equal * </ul> * * <p>When a test fails, the error message labels the objects involved in * the failed comparison as follows: * <ul> * <li>"{@code [group }<i>i</i>{@code , item }<i>j</i>{@code ]}" refers to the * <i>j</i><sup>th</sup> item in the <i>i</i><sup>th</sup> equality group, * where both equality groups and the items within equality groups are * numbered starting from 1. When either a constructor argument or an * equal object is provided, that becomes group 1. * </ul> * * @author Jim McMaster * @author Jige Yu * @since 10.0 */ @Beta @GwtCompatible public final class EqualsTester { private static final int REPETITIONS = 3; private final List<List<Object>> equalityGroups = Lists.newArrayList(); /** * Constructs an empty EqualsTester instance */ public EqualsTester() {} /** * Adds {@code equalityGroup} with objects that are supposed to be equal to * each other and not equal to any other equality groups added to this tester. */ public EqualsTester addEqualityGroup(Object... equalityGroup) { checkNotNull(equalityGroup); equalityGroups.add(ImmutableList.copyOf(equalityGroup)); return this; } /** * Run tests on equals method, throwing a failure on an invalid test */ public EqualsTester testEquals() { RelationshipTester<Object> delegate = new RelationshipTester<Object>( new RelationshipAssertion<Object>() { @Override public void assertRelated(Object item, Object related) { assertEquals("$ITEM must be equal to $RELATED", item, related); int itemHash = item.hashCode(); int relatedHash = related.hashCode(); assertEquals("the hash (" + itemHash + ") of $ITEM must be equal to the hash (" + relatedHash +") of $RELATED", itemHash, relatedHash); } @Override public void assertUnrelated(Object item, Object unrelated) { // TODO(cpovirk): should this implementation (and // RelationshipAssertions in general) accept null inputs? assertTrue("$ITEM must be unequal to $UNRELATED", !Objects.equal(item, unrelated)); } }); for (List<Object> group : equalityGroups) { delegate.addRelatedGroup(group); } for (int run = 0; run < REPETITIONS; run++) { testItems(); delegate.test(); } return this; } private void testItems() { for (Object item : Iterables.concat(equalityGroups)) { assertTrue(item + " must be unequal to null", !item.equals(null)); assertTrue(item + " must be unequal to an arbitrary object of another class", !item.equals(NotAnInstance.EQUAL_TO_NOTHING)); assertEquals(item + " must be equal to itself", item, item); assertEquals("the hash of " + item + " must be consistent", item.hashCode(), item.hashCode()); } } /** * Class used to test whether equals() correctly handles an instance * of an incompatible class. Since it is a private inner class, the * invoker can never pass in an instance to the tester */ private enum NotAnInstance { EQUAL_TO_NOTHING; } }
Java
/* * Copyright (C) 2005 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.Beta; import com.google.common.base.Defaults; 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.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ClassToInstanceMap; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableTable; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Multiset; import com.google.common.collect.MutableClassToInstanceMap; import com.google.common.collect.Table; import com.google.common.primitives.Primitives; import junit.framework.Assert; import junit.framework.AssertionFailedError; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import javax.annotation.Nullable; /** * A test utility that verifies that your methods throw {@link * NullPointerException} or {@link UnsupportedOperationException} whenever any * of their parameters are null. To use it, you must first provide valid default * values for the parameter types used by the class. * * @author Kevin Bourrillion * @since 10.0 */ @Beta public final class NullPointerTester { private final ClassToInstanceMap<Object> defaults = MutableClassToInstanceMap.create(); private final List<Member> ignoredMembers = Lists.newArrayList(); public NullPointerTester() { setCommonDefaults(); } private final void setCommonDefaults() { // miscellaneous value types setDefault(Object.class, new Object()); setDefault(Appendable.class, new StringBuilder()); setDefault(CharSequence.class, ""); setDefault(String.class, ""); setDefault(Class.class, Class.class); setDefault(Pattern.class, Pattern.compile("")); setDefault(TimeUnit.class, TimeUnit.SECONDS); setDefault(Throwable.class, new Exception()); // Collections setDefault(Collection.class, Collections.emptySet()); setDefault(Iterable.class, Collections.emptySet()); setDefault(Iterator.class, Iterators.emptyIterator()); setDefault(List.class, Collections.emptyList()); setDefault(ImmutableList.class, ImmutableList.of()); setDefault(Set.class, Collections.emptySet()); setDefault(ImmutableSet.class, ImmutableSet.of()); // TODO(benyu): should this be ImmutableSortedSet? Not type safe. setDefault(SortedSet.class, new TreeSet()); setDefault(ImmutableSortedSet.class, ImmutableSortedSet.of()); setDefault(ImmutableCollection.class, ImmutableList.of()); setDefault(Map.class, Collections.emptyMap()); setDefault(ImmutableMap.class, ImmutableMap.of()); setDefault(SortedMap.class, ImmutableSortedMap.of()); setDefault(ImmutableSortedMap.class, ImmutableSortedMap.of()); setDefault(Multimap.class, ImmutableMultimap.of()); setDefault(ImmutableMultimap.class, ImmutableMultimap.of()); setDefault(Multiset.class, ImmutableMultiset.of()); setDefault(ImmutableMultiset.class, ImmutableMultiset.of()); setDefault(Table.class, ImmutableTable.of()); setDefault(ImmutableTable.class, ImmutableTable.of()); // Function object types setDefault(Comparator.class, Collections.reverseOrder()); setDefault(Predicate.class, Predicates.alwaysTrue()); // The following 3 aren't really safe generically // For example, Comparable<String> can't be 0 setDefault(Comparable.class, 0); setDefault(Function.class, Functions.identity()); setDefault(Supplier.class, Suppliers.ofInstance(1)); // TODO(benyu): We would have delegated to Defaults.getDefault() // By changing it now risks breaking existing clients, and we don't really // care the default value anyway. setDefault(char.class, 'a'); } /** * Sets a default value that can be used for any parameter of type * {@code type}. Returns this object. */ public <T> NullPointerTester setDefault(Class<T> type, T value) { defaults.put(type, value); return this; } /** * Ignore a member (constructor or method) in testAllXxx methods. Returns * this object. */ public NullPointerTester ignore(Member member) { ignoredMembers.add(member); return this; } /** * Runs {@link #testConstructor} on every constructor in class {@code c} that * has at least {@code minimalVisibility}. */ public void testConstructors(Class<?> c, Visibility minimalVisibility) { for (Constructor<?> constructor : c.getDeclaredConstructors()) { if (minimalVisibility.isVisible(constructor) && !isIgnored(constructor)) { testConstructor(constructor); } } } /** * Runs {@link #testConstructor} on every public constructor in class {@code * c}. */ public void testAllPublicConstructors(Class<?> c) { testConstructors(c, Visibility.PUBLIC); } /** * Runs {@link #testMethod} on every static method declared in class {@code c} * that has at least {@code minimalVisibility}. */ public void testStaticMethods(Class<?> c, Visibility minimalVisibility) { for (Method method : c.getDeclaredMethods()) { if (minimalVisibility.isVisible(method) && isStatic(method) && !isIgnored(method)) { testMethod(null, method); } } } /** * Runs {@link #testMethod} on every public static method declared by class * {@code c}. */ public void testAllPublicStaticMethods(Class<?> c) { testStaticMethods(c, Visibility.PUBLIC); } /** * Runs {@link #testMethod} on every instance method declared by the class * of {@code instance} with at least {@code minimalVisibility}. */ public void testInstanceMethods( Object instance, Visibility minimalVisibility) { Class<?> c = instance.getClass(); for (Method method : c.getDeclaredMethods()) { if (minimalVisibility.isVisible(method) && !isStatic(method) && !isIgnored(method)) { testMethod(instance, method); } } } /** * Runs {@link #testMethod} on every public instance method declared by the * class of {@code instance}. */ public void testAllPublicInstanceMethods(Object instance) { testInstanceMethods(instance, Visibility.PUBLIC); } /** * Verifies that {@code method} produces a {@link NullPointerException} * or {@link UnsupportedOperationException} whenever <i>any</i> of its * non-{@link Nullable} parameters are null. * * @param instance the instance to invoke {@code method} on, or null if * {@code method} is static */ public void testMethod(Object instance, Method method) { Class<?>[] types = method.getParameterTypes(); for (int nullIndex = 0; nullIndex < types.length; nullIndex++) { testMethodParameter(instance, method, nullIndex); } } /** * Verifies that {@code ctor} produces a {@link NullPointerException} or * {@link UnsupportedOperationException} whenever <i>any</i> of its * non-{@link Nullable} parameters are null. */ public void testConstructor(Constructor<?> ctor) { Class<?>[] types = ctor.getParameterTypes(); for (int nullIndex = 0; nullIndex < types.length; nullIndex++) { testConstructorParameter(ctor, nullIndex); } } /** * Verifies that {@code method} produces a {@link NullPointerException} or * {@link UnsupportedOperationException} when the parameter in position {@code * paramIndex} is null. If this parameter is marked {@link Nullable}, this * method does nothing. * * @param instance the instance to invoke {@code method} on, or null if * {@code method} is static */ public void testMethodParameter(Object instance, final Method method, int paramIndex) { method.setAccessible(true); testFunctorParameter(instance, new Functor() { @Override public Class<?>[] getParameterTypes() { return method.getParameterTypes(); } @Override public Annotation[][] getParameterAnnotations() { return method.getParameterAnnotations(); } @Override public void invoke(Object instance, Object[] params) throws InvocationTargetException, IllegalAccessException { method.invoke(instance, params); } @Override public String toString() { return method.getName() + "(" + Arrays.toString(getParameterTypes()) + ")"; } }, paramIndex, method.getDeclaringClass()); } /** * Verifies that {@code ctor} produces a {@link NullPointerException} or * {@link UnsupportedOperationException} when the parameter in position {@code * paramIndex} is null. If this parameter is marked {@link Nullable}, this * method does nothing. */ public void testConstructorParameter(final Constructor<?> ctor, int paramIndex) { ctor.setAccessible(true); testFunctorParameter(null, new Functor() { @Override public Class<?>[] getParameterTypes() { return ctor.getParameterTypes(); } @Override public Annotation[][] getParameterAnnotations() { return ctor.getParameterAnnotations(); } @Override public void invoke(Object instance, Object[] params) throws InvocationTargetException, IllegalAccessException, InstantiationException { ctor.newInstance(params); } }, paramIndex, ctor.getDeclaringClass()); } /** Visibility of any method or constructor. */ public enum Visibility { PACKAGE { @Override boolean isVisible(int modifiers) { return !Modifier.isPrivate(modifiers); } }, PROTECTED { @Override boolean isVisible(int modifiers) { return Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers); } }, PUBLIC { @Override boolean isVisible(int modifiers) { return Modifier.isPublic(modifiers); } }; abstract boolean isVisible(int modifiers); /** * Returns {@code true} if {@code member} is visible under {@code this} * visibility. */ final boolean isVisible(Member member) { return isVisible(member.getModifiers()); } } /** * Verifies that {@code func} produces a {@link NullPointerException} or * {@link UnsupportedOperationException} when the parameter in position {@code * paramIndex} is null. If this parameter is marked {@link Nullable}, this * method does nothing. * * @param instance the instance to invoke {@code func} on, or null if * {@code func} is static */ private void testFunctorParameter(Object instance, Functor func, int paramIndex, Class<?> testedClass) { if (parameterIsPrimitiveOrNullable(func, paramIndex)) { return; // there's nothing to test } Object[] params = buildParamList(func, paramIndex); try { func.invoke(instance, params); Assert.fail("No exception thrown from " + func + Arrays.toString(params) + " for " + testedClass); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof NullPointerException || cause instanceof UnsupportedOperationException) { return; } AssertionFailedError error = new AssertionFailedError( "wrong exception thrown from " + func + ": " + cause); error.initCause(cause); throw error; } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } } private static boolean parameterIsPrimitiveOrNullable( Functor func, int paramIndex) { if (func.getParameterTypes()[paramIndex].isPrimitive()) { return true; } Annotation[] annotations = func.getParameterAnnotations()[paramIndex]; for (Annotation annotation : annotations) { if (annotation instanceof Nullable) { return true; } } return false; } private Object[] buildParamList(Functor func, int indexOfParamToSetToNull) { Class<?>[] types = func.getParameterTypes(); Object[] params = new Object[types.length]; for (int i = 0; i < types.length; i++) { if (i != indexOfParamToSetToNull) { Class<?> type = types[i]; params[i] = getDefaultValue(type); if (!parameterIsPrimitiveOrNullable(func, i)) { Assert.assertTrue("No default value found for " + type.getName(), params[i] != null); } } } return params; } private <T> T getDefaultValue(Class<T> type) { T value = defaults.getInstance(type); if (value != null) { return value; } if (type.isEnum()) { T[] constants = type.getEnumConstants(); if (constants.length > 0) { return constants[0]; } } else if (type.isArray()) { @SuppressWarnings("unchecked") // T[].componentType[] == T[] T emptyArray = (T) Array.newInstance(type.getComponentType(), 0); return emptyArray; } return Defaults.defaultValue(Primitives.unwrap(type)); } private interface Functor { Class<?>[] getParameterTypes(); Annotation[][] getParameterAnnotations(); void invoke(Object o, Object[] params) throws InvocationTargetException, IllegalAccessException, InstantiationException; } private static boolean isStatic(Member member) { return Modifier.isStatic(member.getModifiers()); } private boolean isIgnored(Member member) { return member.isSynthetic() || ignoredMembers.contains(member); } }
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.testing; import com.google.common.annotations.GwtCompatible; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; /** * An {@link ClusterException} is a data structure that allows for some code to * "throw multiple exceptions", or something close to it. The prototypical code * that calls for this class is presented below: * * <pre> * void runManyThings(List&lt;ThingToRun&gt; thingsToRun) { * for (ThingToRun thingToRun : thingsToRun) { * thingToRun.run(); // <-- say this may throw an exception, but you want to * // always run all thingsToRun * } * } * </pre> * * This is what the code would become: * * <pre> * void runManyThings(List&lt;ThingToRun&gt; thingsToRun) { * List&lt;Exception&gt; exceptions = Lists.newArrayList(); * for (ThingToRun thingToRun : thingsToRun) { * try { * thingToRun.run(); * } catch (Exception e) { * exceptions.add(e); * } * } * if (exceptions.size() > 0) { * throw ClusterException.create(exceptions); * } * } * </pre> * * <p>See semantic details at {@link #create(Collection)}. * * @author Luiz-Otavio Zorzella */ @GwtCompatible final class ClusterException extends RuntimeException { public final Collection<? extends Throwable> exceptions; private ClusterException(Collection<? extends Throwable> exceptions) { super( exceptions.size() + " exceptions were thrown. The first exception is listed as a cause.", exceptions.iterator().next()); ArrayList<Throwable> temp = new ArrayList<Throwable>(); temp.addAll(exceptions); this.exceptions = Collections.unmodifiableCollection(temp); } /** * @see #create(Collection) */ public static RuntimeException create(Throwable... exceptions) { ArrayList<Throwable> temp = new ArrayList<Throwable>(); for (Throwable exception : exceptions) { temp.add(exception); } return create(temp); } /** * Given a collection of exceptions, returns a {@link RuntimeException}, with * the following rules: * * <ul> * <li>If {@code exceptions} has a single exception and that exception is a * {@link RuntimeException}, return it * <li>If {@code exceptions} has a single exceptions and that exceptions is * <em>not</em> a {@link RuntimeException}, return a simple * {@code RuntimeException} that wraps it * <li>Otherwise, return an instance of {@link ClusterException} that wraps * the first exception in the {@code exceptions} collection. * </ul> * * <p>Though this method takes any {@link Collection}, it often makes most * sense to pass a {@link java.util.List} or some other collection that * preserves the order in which the exceptions got added. * * @throws NullPointerException if {@code exceptions} is null * @throws IllegalArgumentException if {@code exceptions} is empty */ public static RuntimeException create(Collection<? extends Throwable> exceptions) { if (exceptions.size() == 0) { throw new IllegalArgumentException( "Can't create an ExceptionCollection with no exceptions"); } if (exceptions.size() == 1) { Throwable temp = exceptions.iterator().next(); if (temp instanceof RuntimeException) { return (RuntimeException)temp; } else { return new RuntimeException(temp); } } return new ClusterException(exceptions); } }
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.util.concurrent.testing; import com.google.common.annotations.Beta; import com.google.common.util.concurrent.ListenableFuture; import junit.framework.TestCase; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Abstract test case parent for anything implementing {@link ListenableFuture}. * Tests the two get methods and the addListener method. * * @author Sven Mawson * @since 10.0 */ @Beta public abstract class AbstractListenableFutureTest extends TestCase { protected CountDownLatch latch; protected ListenableFuture<Boolean> future; @Override protected void setUp() throws Exception { // Create a latch and a future that waits on the latch. latch = new CountDownLatch(1); future = createListenableFuture(Boolean.TRUE, null, latch); } @Override protected void tearDown() throws Exception { // Make sure we have no waiting threads. latch.countDown(); } /** * Constructs a listenable future with a value available after the latch * has counted down. */ protected abstract <V> ListenableFuture<V> createListenableFuture( V value, Exception except, CountDownLatch waitOn); /** * Tests that the {@link Future#get()} method blocks until a value is * available. */ public void testGetBlocksUntilValueAvailable() throws Throwable { assertFalse(future.isDone()); assertFalse(future.isCancelled()); final CountDownLatch successLatch = new CountDownLatch(1); final Throwable[] badness = new Throwable[1]; // Wait on the future in a separate thread. new Thread(new Runnable() { @Override public void run() { try { assertSame(Boolean.TRUE, future.get()); successLatch.countDown(); } catch (Throwable t) { t.printStackTrace(); badness[0] = t; } }}).start(); // Release the future value. latch.countDown(); assertTrue(successLatch.await(10, TimeUnit.SECONDS)); if (badness[0] != null) { throw badness[0]; } assertTrue(future.isDone()); assertFalse(future.isCancelled()); } /** * Tests that the {@link Future#get(long, TimeUnit)} method times out * correctly. */ public void testTimeoutOnGetWorksCorrectly() throws InterruptedException, ExecutionException { // The task thread waits for the latch, so we expect a timeout here. try { future.get(20, TimeUnit.MILLISECONDS); fail("Should have timed out trying to get the value."); } catch (TimeoutException expected) { // Expected. } finally { latch.countDown(); } } /** * Tests that a canceled future throws a cancellation exception. * * This method checks the cancel, isCancelled, and isDone methods. */ public void testCanceledFutureThrowsCancellation() throws Exception { assertFalse(future.isDone()); assertFalse(future.isCancelled()); final CountDownLatch successLatch = new CountDownLatch(1); // Run cancellation in a separate thread as an extra thread-safety test. new Thread(new Runnable() { @Override public void run() { try { future.get(); } catch (CancellationException expected) { successLatch.countDown(); } catch (Exception ignored) { // All other errors are ignored, we expect a cancellation. } } }).start(); assertFalse(future.isDone()); assertFalse(future.isCancelled()); future.cancel(true); assertTrue(future.isDone()); assertTrue(future.isCancelled()); assertTrue(successLatch.await(200, TimeUnit.MILLISECONDS)); latch.countDown(); } public void testListenersNotifiedOnError() throws Exception { final CountDownLatch successLatch = new CountDownLatch(1); final CountDownLatch listenerLatch = new CountDownLatch(1); ExecutorService exec = Executors.newCachedThreadPool(); future.addListener(new Runnable() { @Override public void run() { listenerLatch.countDown(); } }, exec); new Thread(new Runnable() { @Override public void run() { try { future.get(); } catch (CancellationException expected) { successLatch.countDown(); } catch (Exception ignored) { // No success latch count down. } } }).start(); future.cancel(true); assertTrue(future.isCancelled()); assertTrue(future.isDone()); assertTrue(successLatch.await(200, TimeUnit.MILLISECONDS)); assertTrue(listenerLatch.await(200, TimeUnit.MILLISECONDS)); latch.countDown(); exec.shutdown(); exec.awaitTermination(100, TimeUnit.MILLISECONDS); } /** * Tests that all listeners complete, even if they were added before or after * the future was finishing. Also acts as a concurrency test to make sure the * locking is done correctly when a future is finishing so that no listeners * can be lost. */ public void testAllListenersCompleteSuccessfully() throws InterruptedException, ExecutionException { ExecutorService exec = Executors.newCachedThreadPool(); int listenerCount = 20; final CountDownLatch listenerLatch = new CountDownLatch(listenerCount); // Test that listeners added both before and after the value is available // get called correctly. for (int i = 0; i < 20; i++) { // Right in the middle start up a thread to close the latch. if (i == 10) { new Thread(new Runnable() { @Override public void run() { latch.countDown(); } }).start(); } future.addListener(new Runnable() { @Override public void run() { listenerLatch.countDown(); } }, exec); } assertSame(Boolean.TRUE, future.get()); // Wait for the listener latch to complete. listenerLatch.await(500, TimeUnit.MILLISECONDS); exec.shutdown(); exec.awaitTermination(500, TimeUnit.MILLISECONDS); } }
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.util.concurrent.testing; import com.google.common.annotations.Beta; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import junit.framework.Assert; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** * A simple mock implementation of {@code Runnable} that can be used for * testing ListenableFutures. * * @author Nishant Thakkar * @since 10.0 */ @Beta public class MockFutureListener implements Runnable { private final CountDownLatch countDownLatch; private final ListenableFuture<?> future; public MockFutureListener(ListenableFuture<?> future) { this.countDownLatch = new CountDownLatch(1); this.future = future; future.addListener(this, MoreExecutors.sameThreadExecutor()); } @Override public void run() { countDownLatch.countDown(); } /** * Verify that the listener completes in a reasonable amount of time, and * Asserts that the future returns the expected data. * @throws Throwable if the listener isn't called or if it resulted in a * throwable or if the result doesn't match the expected value. */ public void assertSuccess(Object expectedData) throws Throwable { // Verify that the listener executed in a reasonable amount of time. Assert.assertTrue(countDownLatch.await(1L, TimeUnit.SECONDS)); try { Assert.assertEquals(expectedData, future.get()); } catch (ExecutionException e) { throw e.getCause(); } } /** * Verify that the listener completes in a reasonable amount of time, and * Asserts that the future throws an {@code ExecutableException} and that the * cause of the {@code ExecutableException} is {@code expectedCause}. */ public void assertException(Throwable expectedCause) throws Exception { // Verify that the listener executed in a reasonable amount of time. Assert.assertTrue(countDownLatch.await(1L, TimeUnit.SECONDS)); try { future.get(); Assert.fail("This call was supposed to throw an ExecutionException"); } catch (ExecutionException expected) { Assert.assertSame(expectedCause, expected.getCause()); } } public void assertTimeout() throws Exception { // Verify that the listener does not get called in a reasonable amount of // time. Assert.assertFalse(countDownLatch.await(1L, TimeUnit.SECONDS)); } }
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.util.concurrent.testing; import com.google.common.annotations.Beta; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.ListenableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Test case to make sure the {@link CheckedFuture#checkedGet()} and * {@link CheckedFuture#checkedGet(long, TimeUnit)} methods work correctly. * * @author Sven Mawson * @since 10.0 */ @Beta public abstract class AbstractCheckedFutureTest extends AbstractListenableFutureTest { /** * More specific type for the create method. */ protected abstract <V> CheckedFuture<V, ?> createCheckedFuture(V value, Exception except, CountDownLatch waitOn); /** * Checks that the exception is the correct type of cancellation exception. */ protected abstract void checkCancelledException(Exception e); /** * Checks that the exception is the correct type of execution exception. */ protected abstract void checkExecutionException(Exception e); /** * Checks that the exception is the correct type of interruption exception. */ protected abstract void checkInterruptedException(Exception e); @Override protected <V> ListenableFuture<V> createListenableFuture(V value, Exception except, CountDownLatch waitOn) { return createCheckedFuture(value, except, waitOn); } /** * Tests that the {@link CheckedFuture#checkedGet()} method throws the correct * type of cancellation exception when it is cancelled. */ public void testCheckedGetThrowsApplicationExceptionOnCancellation() { final CheckedFuture<Boolean, ?> future = createCheckedFuture(Boolean.TRUE, null, latch); assertFalse(future.isDone()); assertFalse(future.isCancelled()); new Thread(new Runnable() { @Override public void run() { future.cancel(true); } }).start(); try { future.checkedGet(); fail("RPC Should have been cancelled."); } catch (Exception e) { checkCancelledException(e); } assertTrue(future.isDone()); assertTrue(future.isCancelled()); } public void testCheckedGetThrowsApplicationExceptionOnInterruption() throws InterruptedException { final CheckedFuture<Boolean, ?> future = createCheckedFuture(Boolean.TRUE, null, latch); final CountDownLatch startingGate = new CountDownLatch(1); final CountDownLatch successLatch = new CountDownLatch(1); assertFalse(future.isDone()); assertFalse(future.isCancelled()); Thread getThread = new Thread(new Runnable() { @Override public void run() { startingGate.countDown(); try { future.checkedGet(); } catch (Exception e) { checkInterruptedException(e); // This only gets hit if the original call throws an exception and // the check call above passes. successLatch.countDown(); } } }); getThread.start(); assertTrue(startingGate.await(500, TimeUnit.MILLISECONDS)); getThread.interrupt(); assertTrue(successLatch.await(500, TimeUnit.MILLISECONDS)); assertFalse(future.isDone()); assertFalse(future.isCancelled()); } public void testCheckedGetThrowsApplicationExceptionOnError() { final CheckedFuture<Boolean, ?> future = createCheckedFuture(Boolean.TRUE, new Exception("Error"), latch); assertFalse(future.isDone()); assertFalse(future.isCancelled()); new Thread(new Runnable() { @Override public void run() { latch.countDown(); } }).start(); try { future.checkedGet(); fail(); } catch (Exception e) { checkExecutionException(e); } assertTrue(future.isDone()); assertFalse(future.isCancelled()); } }
Java
package com.rrd.intellij.idea.plugins.gca; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorAction; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.psi.PsiClass; /** * An {@link com.intellij.openapi.editor.actionSystem.EditorAction} that displays * a "Generate Chained Accessors" option when a user is editing a Java file * and allows the user to generate such accessors * * @author erachitskiy */ public class GenerateChainedAccessors extends EditorAction { public GenerateChainedAccessors(){ super(new GenerateChainedAccessorsActionHandler()); } protected GenerateChainedAccessors(EditorActionHandler defaultHandler) { super(defaultHandler); } public void update(Editor editor, Presentation presentation, DataContext dataContext) { IdeaUtil util=ApplicationManager.getApplication() .getComponent(IdeaUtil.class); /* figure out when to display the option to generate chained accessors */ if(editor==null){ presentation.setVisible(false); return; } PsiClass javaClass=util.getCurrentClass(editor); if(javaClass==null||javaClass.isInterface()){ presentation.setVisible(false); }else{ presentation.setVisible(true); } } }
Java
package com.rrd.intellij.idea.plugins.gca; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiField; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiJavaFile; import com.intellij.psi.PsiManager; import org.jetbrains.annotations.NotNull; /** * A simple set of IntelliJ Idea utilitiy methods * @author erachitskiy */ @SuppressWarnings({"ConstantConditions"}) public class IdeaUtil implements ApplicationComponent { public IdeaUtil() { } public void initComponent() { } public void disposeComponent() { } @NotNull public String getComponentName() { return "IdeaUtil"; } public String getCapitalizedPropertyName(PsiField field){ return getCapitalizedPropertyName(field.getName()); } public String getCapitalizedPropertyName(String fieldName) { return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); } public PsiClass getCurrentClass(final Editor editor){ if(editor==null){ return null; } PsiManager psiManager=PsiManager.getInstance(editor.getProject()); VirtualFile vFile = FileDocumentManager.getInstance().getFile(editor.getDocument()); PsiFile psiFile=psiManager.findFile(vFile); if(!(psiFile instanceof PsiJavaFile)){ return null; } PsiJavaFile javaFile=(PsiJavaFile)psiFile; PsiElement element = javaFile.findElementAt(editor.getCaretModel().getOffset()); while(!(element instanceof PsiClass)&&element!=null){ element=element.getParent(); } if(element==null){ return null; }else{ return (PsiClass)element; } } }
Java
package com.rrd.intellij.idea.plugins.gca; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElementFactory; import com.intellij.psi.PsiField; import com.intellij.psi.PsiMethod; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class GenerateChainedAccessorsActionHandler extends EditorWriteActionHandler { @Override public void executeWriteAction(final Editor editor, final DataContext dataContext) { IdeaUtil util = ApplicationManager.getApplication().getComponent(IdeaUtil.class); JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(editor.getProject()); PsiElementFactory psiElementFactory = psiFacade.getElementFactory(); PsiClass clazz = util.getCurrentClass(editor); List<PsiMethod> clazzMethods = Arrays.asList(clazz.getMethods()); List<String> clazzMethodNames = new ArrayList<String>(clazzMethods.size()); for (PsiMethod clazzMethod : clazzMethods) { clazzMethodNames.add(clazzMethod.getName()); } for (PsiField field : clazz.getFields()) { String methodNameSuffix = util.getCapitalizedPropertyName(field); String fieldType = field.getType().getCanonicalText(); String fieldName = field.getName(); String getterMethodName = "get" + methodNameSuffix; if (!clazzMethodNames.contains(getterMethodName)) { clazz.add(psiElementFactory.createMethodFromText(getGetterText(fieldName, getterMethodName, fieldType), clazz)); } String setterMethodName = "set" + methodNameSuffix; boolean isFinalMethod=true; try{ isFinalMethod=field.getModifierList().hasModifierProperty("final"); }catch(Exception e){ /* swallow */ } if (!isFinalMethod && !clazzMethodNames.contains(setterMethodName)) { clazz.add(psiElementFactory.createMethodFromText(getSetterText(fieldName, setterMethodName, fieldType, clazz.getName()), clazz)); } } } protected String getGetterText(String fieldName, String methodName, String fieldType) { return new StringBuffer().append("public ").append(fieldType).append(" ").append(methodName).append("(){\nreturn this.").append(fieldName).append(";\n}").toString(); } protected String getSetterText(String fieldName, String methodName, String fieldType, String className) { return new StringBuffer(). append("public ").append(className) .append(" ") .append(methodName).append("(").append(fieldType).append(" ").append(fieldName).append("){\nthis.").append(fieldName).append("=").append(fieldName).append(";").append("return this;\n}").toString(); } }
Java
/* * Copyright (c) 2012 Google Inc. * * 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.drive.samples.dredit; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.auth.oauth2.CredentialStore; import com.google.api.client.extensions.appengine.auth.oauth2.AppEngineCredentialStore; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.services.oauth2.Oauth2; import com.google.api.services.oauth2.model.Userinfo; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import javax.servlet.http.HttpServletRequest; /** * Object that manages credentials associated with this Drive application and * its users. Performs all OAuth 2.0 authorization, authorization code * upgrades, and token storage/retrieval. * * @author vicfryzel@google.com (Vic Fryzel) */ public class CredentialMediator { /** * The HTTP request used to make a request to this Drive application. * Required so that we can manage a session for the active user, and keep * track of their email address which is used to identify their credentials. * We also need this in order to access a bunch of request parameters like * {@code state} and {@code code}. */ private HttpServletRequest request; /** * Scopes for which to request authorization. */ private Collection<String> scopes; /** * Loaded data from war/WEB-INF/client_secrets.json. */ private GoogleClientSecrets secrets; /** * CredentialStore at which Credential objects are stored. */ private CredentialStore credentialStore; /** * JsonFactory to use in parsing JSON. */ private static final JsonFactory JSON_FACTORY = new JacksonFactory(); /** * HttpTransport to use for external requests. */ private static final HttpTransport TRANSPORT = new NetHttpTransport(); /** * Key of session variable to store user IDs. */ private static final String USER_ID_KEY = "userId"; /** * Key of session variable to store user email addresses. */ private static final String EMAIL_KEY = "emailAddress"; /** * Creates a new CredentialsManager for the given HTTP request. * * @param request Request in which session credentials are stored. * @param clientSecretsStream Stream of client_secrets.json. * @throws InvalidClientSecretsException */ public CredentialMediator(HttpServletRequest request, InputStream clientSecretsStream, Collection<String> scopes) throws InvalidClientSecretsException { this.request = request; this.scopes = scopes; this.credentialStore = new AppEngineCredentialStore(); try { secrets = GoogleClientSecrets.load( JSON_FACTORY, clientSecretsStream); } catch (IOException e) { throw new InvalidClientSecretsException( "client_secrets.json is missing or invalid."); } } /** * @return Client information parsed from client_secrets.json. */ protected GoogleClientSecrets getClientSecrets() { return secrets; } /** * Builds an empty GoogleCredential, configured with appropriate * HttpTransport, JsonFactory, and client information. */ private Credential buildEmptyCredential() { return new GoogleCredential.Builder() .setClientSecrets(this.secrets) .setTransport(TRANSPORT) .setJsonFactory(JSON_FACTORY) .build(); } /** * Retrieves stored credentials for the provided email address. * * @param userId User's Google ID. * @return Stored GoogleCredential if found, {@code null} otherwise. */ private Credential getStoredCredential(String userId) { Credential credential = buildEmptyCredential(); if(credentialStore.load(userId, credential)) { return credential; } return null; } /** * Deletes stored credentials for the provided email address. * * @param userId User's Google ID. */ private void deleteStoredCredential(String userId) { if (userId != null) { Credential credential = getStoredCredential(userId); credentialStore.delete(userId, credential); } } /** * Exchange an authorization code for a credential. * * @param authorizationCode Authorization code to exchange for OAuth 2.0 * credentials. * @return Credential representing the upgraded authorizationCode. * @throws CodeExchangeException An error occurred. */ private Credential exchangeCode(String authorizationCode) throws CodeExchangeException { // Talk to Google and upgrade the given authorization code to an access // token and hopefully a refresh token. try { GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest( TRANSPORT, JSON_FACTORY, secrets.getWeb().getClientId(), secrets.getWeb().getClientSecret(), authorizationCode, secrets.getWeb().getRedirectUris().get(0)).execute(); return buildEmptyCredential().setFromTokenResponse(response); } catch (IOException e) { e.printStackTrace(); throw new CodeExchangeException(); } } /** * Send a request to the UserInfo API to retrieve user e-mail address * associated with the given credential. * * @param credential Credential to authorize the request. * @return User's e-mail address. * @throws NoUserIdException An error occurred, and the retrieved email * address was null. */ private Userinfo getUserInfo(Credential credential) throws NoUserIdException { Userinfo userInfo = null; // Create a user info service, and make a request to get the user's info. Oauth2 userInfoService = Oauth2.builder(TRANSPORT, JSON_FACTORY) .setHttpRequestInitializer(credential).build(); try { userInfo = userInfoService.userinfo().get().execute(); if (userInfo == null) { throw new NoUserIdException(); } } catch (IOException e) { e.printStackTrace(); } return userInfo; } /** * Retrieve the authorization URL to authorize the user with the given * email address. * * @param emailAddress User's e-mail address. * @return Authorization URL to redirect the user to. */ private String getAuthorizationUrl(String emailAddress) { // Generate an authorization URL based on our client settings, // the user's email address, and the state parameter, if present. GoogleAuthorizationCodeRequestUrl urlBuilder = new GoogleAuthorizationCodeRequestUrl( secrets.getWeb().getClientId(), secrets.getWeb().getRedirectUris().get(0), scopes) .setAccessType("offline") .setApprovalPrompt("force"); // Propagate through the current state parameter, so that when the // user gets redirected back to our app, they see the file(s) they // were originally supposed to see before we realized we weren't // authorized. if (request.getParameter("state") != null) { urlBuilder.set("state", request.getParameter("state")); } if (emailAddress != null) { urlBuilder.set("user_id", emailAddress); } return urlBuilder.build(); } /** * Deletes the credential of the active session. */ public void deleteActiveCredential() { String userId = (String) request.getSession().getAttribute(USER_ID_KEY); this.deleteStoredCredential(userId); } /** * Retrieve credentials using the provided authorization code. * * This function exchanges the authorization code for an access token and * queries the UserInfo API to retrieve the user's e-mail address. If a * refresh token has been retrieved along with an access token, it is stored * in the application database using the user's e-mail address as key. If no * refresh token has been retrieved, the function checks in the application * database for one and returns it if found or throws a * NoRefreshTokenException with the authorization URL to redirect the user * to. * * @return Credential containing an access and refresh token. * @throws NoRefreshTokenException No refresh token could be retrieved from * the available sources. */ public Credential getActiveCredential() throws NoRefreshTokenException { String userId = (String) request.getSession().getAttribute(USER_ID_KEY); Credential credential = null; try { // Only bother looking for a Credential if the user has an existing // session with their email address stored. if (userId != null) { credential = getStoredCredential(userId); } // No Credential was stored for the current user or no refresh token is // available. // If an authorizationCode is present, upgrade it into an // access token and hopefully a refresh token. if ((credential == null || credential.getRefreshToken() == null) && request.getParameter("code") != null) { credential = exchangeCode(request.getParameter("code")); if (credential != null) { Userinfo userInfo = getUserInfo(credential); userId = userInfo.getId(); request.getSession().setAttribute(USER_ID_KEY, userId); request.getSession().setAttribute(EMAIL_KEY, userInfo.getEmail()); // Sometimes we won't get a refresh token after upgrading a code. // This won't work for our app, because the user can land directly // at our app without first visiting Google Drive. Therefore, // only bother to store the Credential if it has a refresh token. // If it doesn't, we'll get one below. if (credential.getRefreshToken() != null) { credentialStore.store(userId, credential); } } } if (credential == null || credential.getRefreshToken() == null) { // No refresh token has been retrieved. // Start a "fresh" OAuth 2.0 flow so that we can get a refresh token. String email = (String) request.getSession().getAttribute(EMAIL_KEY); String authorizationUrl = getAuthorizationUrl(email); throw new NoRefreshTokenException(authorizationUrl); } } catch (CodeExchangeException e) { // The code the user arrived here with was bad. This pretty much never // happens. In a production application, we'd either redirect the user // somewhere like a home page, or show them a vague error mentioning // that they probably didn't arrive to our app from Google Drive. e.printStackTrace(); } catch (NoUserIdException e) { // This is bad because it means the user either denied us access // to their email address, or we couldn't fetch it for some reason. // This is unrecoverable. In a production application, we'd show the // user a message saying that we need access to their email address // to work. e.printStackTrace(); } return credential; } /** * Exception thrown when no refresh token has been found. */ public static class NoRefreshTokenException extends Exception { /** * Authorization URL to which to redirect the user. */ private String authorizationUrl; /** * Construct a NoRefreshTokenException. * * @param authorizationUrl The authorization URL to redirect the user to. */ public NoRefreshTokenException(String authorizationUrl) { this.authorizationUrl = authorizationUrl; } /** * @return Authorization URL to which to redirect the user. */ public String getAuthorizationUrl() { return authorizationUrl; } } /** * Exception thrown when client_secrets.json is missing or invalid. */ public static class InvalidClientSecretsException extends Exception { /** * Construct an InvalidClientSecretsException with a message. * * @param message Message to escalate. */ public InvalidClientSecretsException(String message) { super(message); } } /** * Exception thrown when no email address could be retrieved. */ private static class NoUserIdException extends Exception {} /** * Exception thrown when a code exchange has failed. */ private static class CodeExchangeException extends Exception {} }
Java
/* * Copyright (c) 2012 Google Inc. * * 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.drive.samples.dredit; import com.google.drive.samples.dredit.model.State; import com.google.gson.Gson; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet to check that the current user is authorized and to serve the * start page for DrEdit. * * @author vicfryzel@google.com (Vic Fryzel) */ public class StartPageServlet extends DrEditServlet { /** * Ensure that the user is authorized, and setup the required values for * index.jsp. */ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // Deserialize the state in order to specify some values to the DrEdit // JavaScript client below. Collection<String> ids = new ArrayList<String>(); // Assume an empty ID in the list if no IDs were set. ids.add(""); if (req.getParameter("state") != null) { State state = new State(req.getParameter("state")); if (state.ids != null && state.ids.size() > 0) { ids = state.ids; } } req.setAttribute("ids", new Gson().toJson(ids).toString()); req.setAttribute("client_id", new Gson().toJson(getClientId(req, resp))); req.getRequestDispatcher("/index.jsp").forward(req, resp); } }
Java
/* * Copyright (c) 2012 Google Inc. * * 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.drive.samples.dredit; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson.JacksonFactory; import com.google.drive.samples.dredit.CredentialMediator.InvalidClientSecretsException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Abstract servlet that sets up credentials and provides some convenience * methods. * * @author vicfryzel@google.com (Vic Fryzel) */ public abstract class DrEditServlet extends HttpServlet { protected static final HttpTransport TRANSPORT = new NetHttpTransport(); protected static final JsonFactory JSON_FACTORY = new JacksonFactory(); /** * Default MIME type of files created or handled by DrEdit. * * This is also set in the Google APIs Console under the Drive SDK tab. */ public static final String DEFAULT_MIMETYPE = "text/plain"; /** * MIME type to use when sending responses back to DrEdit JavaScript client. */ public static final String JSON_MIMETYPE = "application/json"; /** * Path component under war/ to locate client_secrets.json file. */ public static final String CLIENT_SECRETS_FILE_PATH = "/WEB-INF/client_secrets.json"; /** * Scopes for which to request access from the user. */ public static final List<String> SCOPES = Arrays.asList( // Required to access and manipulate files. "https://www.googleapis.com/auth/drive.file", // Required to identify the user in our data store. "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"); protected void sendError(HttpServletResponse resp, int code, String message) { try { resp.sendError(code, message); } catch (IOException e) { throw new RuntimeException(message); } } protected InputStream getClientSecretsStream() { return getServletContext().getResourceAsStream(CLIENT_SECRETS_FILE_PATH); } protected CredentialMediator getCredentialMediator( HttpServletRequest req, HttpServletResponse resp) { // Authorize or fetch credentials. Required here to ensure this happens // on first page load. Then, credentials will be stored in the user's // session. CredentialMediator mediator; try { mediator = new CredentialMediator(req, getClientSecretsStream(), SCOPES); mediator.getActiveCredential(); return mediator; } catch (CredentialMediator.NoRefreshTokenException e) { try { resp.sendRedirect(e.getAuthorizationUrl()); } catch (IOException ioe) { throw new RuntimeException("Failed to redirect user for authorization"); } throw new RuntimeException("No refresh token found. Re-authorizing."); } catch (InvalidClientSecretsException e) { String message = String.format( "This application is not properly configured: %s", e.getMessage()); sendError(resp, 500, message); throw new RuntimeException(message); } } protected Credential getCredential( HttpServletRequest req, HttpServletResponse resp) { try { CredentialMediator mediator = getCredentialMediator(req, resp); return mediator.getActiveCredential(); } catch(CredentialMediator.NoRefreshTokenException e) { try { resp.sendRedirect(e.getAuthorizationUrl()); } catch (IOException ioe) { ioe.printStackTrace(); throw new RuntimeException("Failed to redirect for authorization."); } } return null; } protected String getClientId( HttpServletRequest req, HttpServletResponse resp) { return getCredentialMediator(req, resp).getClientSecrets().getWeb() .getClientId(); } protected void deleteCredential(HttpServletRequest req, HttpServletResponse resp) { CredentialMediator mediator = getCredentialMediator(req, resp); mediator.deleteActiveCredential(); } }
Java
/* * Copyright (c) 2012 Google Inc. * * 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.drive.samples.dredit; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.ByteArrayContent; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpResponse; import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.File; import com.google.drive.samples.dredit.model.ClientFile; import com.google.gson.Gson; import java.io.IOException; import java.util.Scanner; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet providing a small API for the DrEdit JavaScript client to use in * manipulating files. Each operation (GET, POST, PUT) issues requests to the * Google Drive API. * * @author vicfryzel@google.com (Vic Fryzel) */ public class FileServlet extends DrEditServlet { /** * Given a {@code file_id} URI parameter, return a JSON representation * of the given file. */ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Drive service = getDriveService(req, resp); String fileId = req.getParameter("file_id"); if (fileId == null) { sendError(resp, 400, "The `file_id` URI parameter must be specified."); return; } File file = null; try { file = service.files().get(fileId).execute(); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 401) { // The user has revoked our token or it is otherwise bad. // Delete the local copy so that their next page load will recover. deleteCredential(req, resp); sendError(resp, 401, "Unauthorized"); return; } } if (file != null) { String content = downloadFileContent(service, file); if (content == null) { content = ""; } resp.setContentType(JSON_MIMETYPE); resp.getWriter().print(new ClientFile(file, content).toJson()); } else { sendError(resp, 404, "File not found"); } } /** * Create a new file given a JSON representation, and return the JSON * representation of the created file. */ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Drive service = getDriveService(req, resp); ClientFile clientFile = new ClientFile(req.getReader()); File file = clientFile.toFile(); if (!clientFile.content.equals("")) { file = service.files().insert(file, ByteArrayContent.fromString(clientFile.mimeType, clientFile.content)) .execute(); } else { file = service.files().insert(file).execute(); } resp.setContentType(JSON_MIMETYPE); resp.getWriter().print(new Gson().toJson(file.getId()).toString()); } /** * Update a file given a JSON representation, and return the JSON * representation of the created file. */ @Override public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException { Drive service = getDriveService(req, resp); ClientFile clientFile = new ClientFile(req.getReader()); File file = clientFile.toFile(); file = service.files().update( clientFile.resource_id, file, ByteArrayContent.fromString(clientFile.mimeType, clientFile.content)) .execute(); resp.setContentType(JSON_MIMETYPE); resp.getWriter().print(new Gson().toJson(file.getId()).toString()); } /** * Download the content of the given file. * * @param service Drive service to use for downloading. * @param file File metadata object whose content to download. * @return String representation of file content. String is returned here * because this app is setup for text/plain files. * @throws IOException Thrown if the request fails for whatever reason. */ private String downloadFileContent(Drive service, File file) throws IOException { GenericUrl url = new GenericUrl(file.getDownloadUrl()); HttpResponse response = service.getRequestFactory().buildGetRequest(url) .execute(); try { return new Scanner(response.getContent()).useDelimiter("\\A").next(); } catch (java.util.NoSuchElementException e) { return ""; } } /** * Build and return a Drive service object based on given request parameters. * * @param req Request to use to fetch code parameter or accessToken session * attribute. * @param resp HTTP response to use for redirecting for authorization if * needed. * @return Drive service object that is ready to make requests, or null if * there was a problem. */ private Drive getDriveService(HttpServletRequest req, HttpServletResponse resp) { Credential credentials = getCredential(req, resp); return Drive.builder(TRANSPORT, JSON_FACTORY) .setHttpRequestInitializer(credentials).build(); } }
Java
/* * Copyright (c) 2012 Google Inc. * * 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.drive.samples.dredit.model; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.Collection; /** * An object representing the state parameter passed into this application * from the Drive UI integration (i.e. Open With or Create New). Required * for Gson to deserialize the JSON into POJO form. * * @author vicfryzel@google.com (Vic Fryzel) */ public class State { /** * Action intended by the state. */ public String action; /** * IDs of files on which to take action. */ public Collection<String> ids; /** * Parent ID related to the given action. */ public String parentId; /** * Empty constructor required by Gson. */ public State() {} /** * Create a new State given its JSON representation. * * @param json Serialized representation of a State. */ public State(String json) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); State other = gson.fromJson(json, State.class); this.action = other.action; this.ids = other.ids; this.parentId = other.parentId; } }
Java
/* * Copyright (c) 2012 Google Inc. * * 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.drive.samples.dredit.model; import com.google.api.services.drive.model.File; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.Reader; /** * An object representing a File and its content, for use while interacting * with a DrEdit JavaScript client. Can be serialized and deserialized using * Gson. * * @author vicfryzel@google.com (Vic Fryzel) */ public class ClientFile { /** * ID of file. */ public String resource_id; /** * Title of file. */ public String title; /** * Description of file. */ public String description; /** * MIME type of file. */ public String mimeType; /** * Content body of file. */ public String content; /** * Empty constructor required by Gson. */ public ClientFile() {} /** * Creates a new ClientFile based on the given File and content. */ public ClientFile(File file, String content) { this.resource_id = file.getId(); this.title = file.getTitle(); this.description = file.getDescription(); this.mimeType = file.getMimeType(); this.content = content; } /** * Construct a new ClientFile from its JSON representation. * * @param in Reader of JSON string to parse. */ public ClientFile(Reader in) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); ClientFile other = gson.fromJson(in, ClientFile.class); this.resource_id = other.resource_id; this.title = other.title; this.description = other.description; this.mimeType = other.mimeType; this.content = other.content; } /** * @return JSON representation of this ClientFile. */ public String toJson() { return new Gson().toJson(this).toString(); } /** * @return Representation of this ClientFile as a Drive file. */ public File toFile() { File file = new File(); file.setId(this.resource_id); file.setTitle(this.title); file.setDescription(this.description); file.setMimeType(this.mimeType); return file; } }
Java