code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
/**
* Tests for {@code Multiset#count}.
*
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
public class MultisetCountTester<E> extends AbstractMultisetTester<E> {
public void testCount_0() {
assertEquals("multiset.count(missing) didn't return 0",
0, getMultiset().count(samples.e3));
}
@CollectionSize.Require(absent = ZERO)
public void testCount_1() {
assertEquals("multiset.count(present) didn't return 1",
1, getMultiset().count(samples.e0));
}
@CollectionSize.Require(SEVERAL)
public void testCount_3() {
initThreeCopies();
assertEquals("multiset.count(thriceContained) didn't return 3",
3, getMultiset().count(samples.e0));
}
@CollectionFeature.Require(ALLOWS_NULL_QUERIES)
public void testCount_nullAbsent() {
assertEquals("multiset.count(null) didn't return 0",
0, getMultiset().count(null));
}
@CollectionFeature.Require(absent = ALLOWS_NULL_QUERIES)
public void testCount_null_forbidden() {
try {
getMultiset().count(null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {}
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testCount_nullPresent() {
initCollectionWithNullElement();
assertEquals(1, getMultiset().count(null));
}
public void testCount_wrongType() {
assertEquals("multiset.count(wrongType) didn't return 0",
0, getMultiset().count(WrongType.VALUE));
}
/**
* Returns {@link Method} instances for the read tests that assume multisets
* support duplicates so that the test of {@code Multisets.forSet()} can
* suppress them.
*/
@GwtIncompatible("reflection")
public static List<Method> getCountDuplicateInitializingMethods() {
return Arrays.asList(
Helpers.getMethod(MultisetCountTester.class, "testCount_3"));
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultisetCountTester.java | Java | asf20 | 3,332 |
/*
* 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.SetMultimap;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.SampleElements;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* A skeleton generator for a {@code SetMultimap} implementation.
*
* @author Louis Wasserman
*/
@GwtCompatible
public abstract class TestStringSetMultimapGenerator
implements TestSetMultimapGenerator<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 SampleElements<String> sampleKeys() {
return new SampleElements<String>("one", "two", "three", "four", "five");
}
@Override
public SampleElements<String> sampleValues() {
return new SampleElements<String>("January", "February", "March", "April", "May");
}
@Override
public Collection<String> createCollection(Iterable<? extends String> values) {
return Helpers.copyToSet(values);
}
@Override
public final SetMultimap<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 SetMultimap<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;
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/TestStringSetMultimapGenerator.java | Java | asf20 | 3,009 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.SortedSetMultimap;
import com.google.common.collect.testing.features.MapFeature;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.SortedSet;
/**
* Testers for {@link SortedSetMultimap#asMap}.
*
* @author Louis Wasserman
* @param <K> The key type of the tested multimap.
* @param <V> The value type of the tested multimap.
*/
@GwtCompatible
public class SortedSetMultimapAsMapTester<K, V>
extends AbstractMultimapTester<K, V, SortedSetMultimap<K, V>> {
public void testAsMapValuesImplementSortedSet() {
for (Collection<V> valueCollection : multimap().asMap().values()) {
SortedSet<V> valueSet = (SortedSet<V>) valueCollection;
assertEquals(multimap().valueComparator(), valueSet.comparator());
}
}
public void testAsMapGetImplementsSortedSet() {
for (K key : multimap().keySet()) {
SortedSet<V> valueSet = (SortedSet<V>) multimap().asMap().get(key);
assertEquals(multimap().valueComparator(), valueSet.comparator());
}
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testAsMapRemoveImplementsSortedSet() {
List<K> keys = new ArrayList<K>(multimap().keySet());
for (K key : keys) {
resetCollection();
SortedSet<V> valueSet = (SortedSet<V>) multimap().asMap().remove(key);
assertEquals(multimap().valueComparator(), valueSet.comparator());
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/SortedSetMultimapAsMapTester.java | Java | asf20 | 2,216 |
/*
* 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.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_ANY_NULL_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collection;
/**
* Tests for {@link Multimap#removeAll(Object)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapRemoveAllTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemoveAllAbsentKey() {
ASSERT.that(multimap().removeAll(sampleKeys().e3)).isEmpty();
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemoveAllPresentKey() {
ASSERT.that(multimap().removeAll(sampleKeys().e0))
.has().exactly(sampleValues().e0).inOrder();
expectMissing(samples.e0);
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemoveAllPropagatesToGet() {
Collection<V> getResult = multimap().get(sampleKeys().e0);
multimap().removeAll(sampleKeys().e0);
ASSERT.that(getResult).isEmpty();
expectMissing(samples.e0);
}
@CollectionSize.Require(SEVERAL)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemoveAllMultipleValues() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e1),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e2));
ASSERT.that(multimap().removeAll(sampleKeys().e0))
.has().exactly(sampleValues().e0, sampleValues().e1, sampleValues().e2);
assertTrue(multimap().isEmpty());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({ SUPPORTS_REMOVE, ALLOWS_NULL_KEYS })
public void testRemoveAllNullKeyPresent() {
initMultimapWithNullKey();
ASSERT.that(multimap().removeAll(null)).has().exactly(getValueForNullKey()).inOrder();
expectMissing(Helpers.mapEntry((K) null, getValueForNullKey()));
}
@MapFeature.Require({ SUPPORTS_REMOVE, ALLOWS_ANY_NULL_QUERIES})
public void testRemoveAllNullKeyAbsent() {
ASSERT.that(multimap().removeAll(null)).isEmpty();
expectUnchanged();
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapRemoveAllTester.java | Java | asf20 | 3,418 |
/*
* 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.
*
* @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;
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/TestStringBiMapGenerator.java | Java | asf20 | 2,631 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
/**
* Tests for {@link Multimap#clear()}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapClearTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(absent = SUPPORTS_REMOVE)
public void testClearUnsupported() {
try {
multimap().clear();
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {}
}
private void assertCleared() {
assertEquals(0, multimap().size());
assertTrue(multimap().isEmpty());
assertEquals(multimap(), getSubjectGenerator().create());
ASSERT.that(multimap().entries().isEmpty());
ASSERT.that(multimap().asMap().isEmpty());
ASSERT.that(multimap().keySet().isEmpty());
ASSERT.that(multimap().keys().isEmpty());
ASSERT.that(multimap().values().isEmpty());
for (K key : sampleKeys()) {
assertGet(key);
}
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClear() {
multimap().clear();
assertCleared();
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearThroughEntries() {
multimap().entries().clear();
assertCleared();
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearThroughAsMap() {
multimap().asMap().clear();
assertCleared();
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearThroughKeySet() {
multimap().keySet().clear();
assertCleared();
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearThroughKeys() {
multimap().keys().clear();
assertCleared();
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearThroughValues() {
multimap().values().clear();
assertCleared();
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testClearPropagatesToGet() {
for (K key : sampleKeys()) {
resetContainer();
Collection<V> collection = multimap().get(key);
multimap().clear();
ASSERT.that(collection).isEmpty();
}
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testClearPropagatesToAsMapGet() {
for (K key : sampleKeys()) {
resetContainer();
Collection<V> collection = multimap().asMap().get(key);
if (collection != null) {
multimap().clear();
ASSERT.that(collection).isEmpty();
}
}
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearPropagatesToAsMap() {
Map<K, Collection<V>> asMap = multimap().asMap();
multimap().clear();
ASSERT.that(asMap).isEmpty();
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearPropagatesToEntries() {
Collection<Entry<K, V>> entries = multimap().entries();
multimap().clear();
ASSERT.that(entries).isEmpty();
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapClearTester.java | Java | asf20 | 4,018 |
/*
* 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.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEY_QUERIES;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
/**
* Tester for the {@code containsKey} methods of {@code Multimap} and its {@code asMap()} view.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapContainsKeyTester<K, V>
extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@CollectionSize.Require(absent = ZERO)
public void testContainsKeyYes() {
assertTrue(multimap().containsKey(sampleKeys().e0));
}
public void testContainsKeyNo() {
assertFalse(multimap().containsKey(sampleKeys().e3));
}
public void testContainsKeysFromKeySet() {
for (K k : multimap().keySet()) {
assertTrue(multimap().containsKey(k));
}
}
public void testContainsKeyAgreesWithGet() {
for (K k : sampleKeys()) {
assertEquals(!multimap().get(k).isEmpty(), multimap().containsKey(k));
}
}
public void testContainsKeyAgreesWithAsMap() {
for (K k : sampleKeys()) {
assertEquals(multimap().containsKey(k), multimap().asMap().containsKey(k));
}
}
public void testContainsKeyAgreesWithKeySet() {
for (K k : sampleKeys()) {
assertEquals(multimap().containsKey(k), multimap().keySet().contains(k));
}
}
@MapFeature.Require(ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testContainsKeyNullPresent() {
initMultimapWithNullKey();
assertTrue(multimap().containsKey(null));
}
@MapFeature.Require(ALLOWS_NULL_KEY_QUERIES)
public void testContainsKeyNullAbsent() {
assertFalse(multimap().containsKey(null));
}
@MapFeature.Require(absent = ALLOWS_NULL_KEY_QUERIES)
public void testContainsKeyNullDisallowed() {
try {
multimap().containsKey(null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapContainsKeyTester.java | Java | asf20 | 2,898 |
/*
* 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.Multimap;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestContainerGenerator;
import java.util.Collection;
import java.util.Map;
/**
* Creates multimaps, containing sample elements, to be tested.
*
* @author Louis Wasserman
*/
@GwtCompatible
public interface TestMultimapGenerator<K, V, M extends Multimap<K, V>>
extends TestContainerGenerator<M, Map.Entry<K, V>> {
K[] createKeyArray(int length);
V[] createValueArray(int length);
SampleElements<K> sampleKeys();
SampleElements<V> sampleValues();
Collection<V> createCollection(Iterable<? extends V> values);
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/TestMultimapGenerator.java | Java | asf20 | 1,379 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEY_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
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 java.util.Iterator;
import java.util.Map;
/**
* Tester for {@code Multimap.keySet}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapKeySetTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
public void testKeySet() {
for (Map.Entry<K, V> entry : getSampleElements()) {
assertTrue(multimap().keySet().contains(entry.getKey()));
}
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_KEYS)
public void testKeySetContainsNullKeyPresent() {
initMultimapWithNullKey();
assertTrue(multimap().keySet().contains(null));
}
@MapFeature.Require(ALLOWS_NULL_KEY_QUERIES)
public void testKeySetContainsNullKeyAbsent() {
assertFalse(multimap().keySet().contains(null));
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testKeySetRemovePropagatesToMultimap() {
int key0Count = multimap().get(sampleKeys().e0).size();
assertEquals(key0Count > 0, multimap().keySet().remove(sampleKeys().e0));
assertEquals(getNumElements() - key0Count, multimap().size());
assertGet(sampleKeys().e0);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE)
public void testKeySetIteratorRemove() {
int key0Count = multimap().get(sampleKeys().e0).size();
Iterator<K> keyItr = multimap().keySet().iterator();
while (keyItr.hasNext()) {
if (keyItr.next().equals(sampleKeys().e0)) {
keyItr.remove();
}
}
assertEquals(getNumElements() - key0Count, multimap().size());
assertGet(sampleKeys().e0);
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapKeySetTester.java | Java | asf20 | 2,982 |
/*
* 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);
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/TestBiMapGenerator.java | Java | asf20 | 1,129 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEY_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUE_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
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.MapFeature;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map.Entry;
/**
* Tester for {@code Multimap.entries}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapEntriesTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
public void testEntries() {
ASSERT.that(multimap().entries()).has().exactlyAs(getSampleElements());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_KEYS)
public void testContainsEntryWithNullKeyPresent() {
initMultimapWithNullKey();
ASSERT.that(multimap().entries()).has().allOf(
Helpers.mapEntry((K) null, getValueForNullKey()));
}
@MapFeature.Require(ALLOWS_NULL_KEY_QUERIES)
public void testContainsEntryWithNullKeyAbsent() {
assertFalse(multimap().entries().contains(Helpers.mapEntry(null, sampleValues().e0)));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_VALUES)
public void testContainsEntryWithNullValuePresent() {
initMultimapWithNullValue();
ASSERT.that(multimap().entries()).has().allOf(
Helpers.mapEntry(getKeyForNullValue(), (V) null));
}
@MapFeature.Require(ALLOWS_NULL_VALUE_QUERIES)
public void testContainsEntryWithNullValueAbsent() {
assertFalse(multimap().entries().contains(
Helpers.mapEntry(sampleKeys().e0, null)));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemovePropagatesToMultimap() {
assertTrue(multimap().entries().remove(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0)));
expectMissing(Helpers.mapEntry(sampleKeys().e0, sampleValues().e0));
assertEquals(getNumElements() - 1, multimap().size());
assertFalse(multimap().containsEntry(sampleKeys().e0, sampleValues().e0));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemoveAllPropagatesToMultimap() {
assertTrue(multimap().entries().removeAll(
Collections.singleton(Helpers.mapEntry(sampleKeys().e0, sampleValues().e0))));
expectMissing(Helpers.mapEntry(sampleKeys().e0, sampleValues().e0));
assertEquals(getNumElements() - 1, multimap().size());
assertFalse(multimap().containsEntry(sampleKeys().e0, sampleValues().e0));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRetainAllPropagatesToMultimap() {
multimap().entries().retainAll(
Collections.singleton(Helpers.mapEntry(sampleKeys().e0, sampleValues().e0)));
assertEquals(
getSubjectGenerator().create(Helpers.mapEntry(sampleKeys().e0, sampleValues().e0)),
multimap());
assertEquals(1, multimap().size());
assertTrue(multimap().containsEntry(sampleKeys().e0, sampleValues().e0));
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE)
public void testIteratorRemovePropagatesToMultimap() {
Iterator<Entry<K, V>> iterator = multimap().entries().iterator();
assertEquals(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
iterator.next());
iterator.remove();
assertTrue(multimap().isEmpty());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testEntriesRemainValidAfterRemove() {
Iterator<Entry<K, V>> iterator = multimap().entries().iterator();
Entry<K, V> entry = iterator.next();
K key = entry.getKey();
V value = entry.getValue();
multimap().removeAll(key);
assertEquals(key, entry.getKey());
assertEquals(value, entry.getValue());
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapEntriesTester.java | Java | asf20 | 5,359 |
/*
* 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);
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountUnconditionallyTester.java | Java | asf20 | 1,442 |
/*
* 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.base.Preconditions.checkState;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
/**
* Tests for {@link Multimap#putAll(Object, Iterable)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapPutIterableTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllNonEmptyIterableOnPresentKey() {
assertTrue(multimap().putAll(sampleKeys().e0, new Iterable<V>() {
@Override
public Iterator<V> iterator() {
return Lists.newArrayList(sampleValues().e3, sampleValues().e4).iterator();
}
}));
assertGet(sampleKeys().e0, sampleValues().e0, sampleValues().e3, sampleValues().e4);
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllNonEmptyCollectionOnPresentKey() {
assertTrue(multimap().putAll(
sampleKeys().e0, Lists.newArrayList(sampleValues().e3, sampleValues().e4)));
assertGet(sampleKeys().e0, sampleValues().e0, sampleValues().e3, sampleValues().e4);
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllNonEmptyIterableOnAbsentKey() {
assertTrue(multimap().putAll(sampleKeys().e3, new Iterable<V>() {
@Override
public Iterator<V> iterator() {
return Lists.newArrayList(sampleValues().e3, sampleValues().e4).iterator();
}
}));
assertGet(sampleKeys().e3, sampleValues().e3, sampleValues().e4);
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllNonEmptyCollectionOnAbsentKey() {
assertTrue(multimap().putAll(
sampleKeys().e3, Lists.newArrayList(sampleValues().e3, sampleValues().e4)));
assertGet(sampleKeys().e3, sampleValues().e3, sampleValues().e4);
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
public void testPutAllNullValueOnPresentKey_supported() {
assertTrue(multimap().putAll(sampleKeys().e0, Lists.newArrayList(sampleValues().e3, null)));
assertGet(sampleKeys().e0, sampleValues().e0, sampleValues().e3, null);
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
public void testPutAllNullValueOnAbsentKey_supported() {
assertTrue(multimap().putAll(sampleKeys().e3, Lists.newArrayList(sampleValues().e3, null)));
assertGet(sampleKeys().e3, sampleValues().e3, null);
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
public void testPutAllNullValueSingle_unsupported() {
multimap().putAll(sampleKeys().e1, Lists.newArrayList((V) null));
expectUnchanged();
}
// In principle, it would be nice to apply these two tests to keys with existing values, too.
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
public void testPutAllNullValueNullLast_unsupported() {
int size = getNumElements();
try {
multimap().putAll(sampleKeys().e3, Lists.newArrayList(sampleValues().e3, null));
fail();
} catch (NullPointerException expected) {
}
Collection<V> values = multimap().get(sampleKeys().e3);
if (values.size() == 0) {
expectUnchanged();
// Be extra thorough in case internal state was corrupted by the expected null.
assertEquals(Lists.newArrayList(), Lists.newArrayList(values));
assertEquals(size, multimap().size());
} else {
assertEquals(Lists.newArrayList(sampleValues().e3), Lists.newArrayList(values));
assertEquals(size + 1, multimap().size());
}
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
public void testPutAllNullValueNullFirst_unsupported() {
int size = getNumElements();
try {
multimap().putAll(sampleKeys().e3, Lists.newArrayList(null, sampleValues().e3));
fail();
} catch (NullPointerException expected) {
}
/*
* In principle, a Multimap implementation could add e3 first before failing on the null. But
* that seems unlikely enough to be worth complicating the test over, especially if there's any
* chance that a permissive test could mask a bug.
*/
expectUnchanged();
// Be extra thorough in case internal state was corrupted by the expected null.
assertEquals(Lists.newArrayList(), Lists.newArrayList(multimap().get(sampleKeys().e3)));
assertEquals(size, multimap().size());
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS})
public void testPutAllOnPresentNullKey() {
assertTrue(multimap().putAll(null, Lists.newArrayList(sampleValues().e3, sampleValues().e4)));
assertGet(null, sampleValues().e3, sampleValues().e4);
}
@MapFeature.Require(absent = ALLOWS_NULL_KEYS)
public void testPutAllNullForbidden() {
try {
multimap().putAll(null, Collections.singletonList(sampleValues().e3));
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
}
private static final Object[] EMPTY = new Object[0];
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllEmptyCollectionOnAbsentKey() {
assertFalse(multimap().putAll(sampleKeys().e3, Collections.<V>emptyList()));
expectUnchanged();
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllEmptyIterableOnAbsentKey() {
Iterable<V> iterable = new Iterable<V>() {
@Override
public Iterator<V> iterator() {
return Iterators.emptyIterator();
}
};
assertFalse(multimap().putAll(sampleKeys().e3, iterable));
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllEmptyIterableOnPresentKey() {
multimap().putAll(sampleKeys().e0, Collections.<V>emptyList());
expectUnchanged();
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllOnlyCallsIteratorOnce() {
Iterable<V> iterable = new Iterable<V>() {
private boolean calledIteratorAlready = false;
@Override
public Iterator<V> iterator() {
checkState(!calledIteratorAlready);
calledIteratorAlready = true;
return Iterators.forArray(sampleValues().e3);
}
};
multimap().putAll(sampleKeys().e3, iterable);
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllPropagatesToGet() {
Collection<V> getCollection = multimap().get(sampleKeys().e0);
int getCollectionSize = getCollection.size();
assertTrue(multimap().putAll(
sampleKeys().e0, Lists.newArrayList(sampleValues().e3, sampleValues().e4)));
assertEquals(getCollectionSize + 2, getCollection.size());
ASSERT.that(getCollection).has().allOf(sampleValues().e3, sampleValues().e4);
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapPutIterableTester.java | Java | asf20 | 8,075 |
/*
* 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.Helpers.copyToList;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Arrays;
import java.util.List;
/**
* Testers for {@link ListMultimap#putAll(Object, Iterable)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class ListMultimapPutAllTester<K, V> extends AbstractListMultimapTester<K, V> {
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllAddsAtEndInOrder() {
@SuppressWarnings("unchecked")
List<V> values = Arrays.asList(
sampleValues().e3,
sampleValues().e1,
sampleValues().e4);
for (K k : sampleKeys()) {
resetContainer();
List<V> expectedValues = copyToList(multimap().get(k));
assertTrue(multimap().putAll(k, values));
expectedValues.addAll(values);
assertGet(k, expectedValues);
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/ListMultimapPutAllTester.java | Java | asf20 | 1,699 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.testing.EqualsTester;
/**
* Testers for {@link ListMultimap#equals(Object)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class ListMultimapEqualsTester<K, V> extends AbstractListMultimapTester<K, V> {
@CollectionSize.Require(SEVERAL)
public void testOrderingAffectsEqualsComparisons() {
ListMultimap<K, V> multimap1 = getSubjectGenerator().create(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e1),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0));
ListMultimap<K, V> multimap2 = getSubjectGenerator().create(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e1),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0));
new EqualsTester()
.addEqualityGroup(multimap1)
.addEqualityGroup(multimap2)
.testEquals();
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/ListMultimapEqualsTester.java | Java | asf20 | 1,904 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Tests for {@code Multiset#remove}, {@code Multiset.removeAll}, and {@code Multiset.retainAll}
* not already covered by the corresponding Collection testers.
*
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
public class MultisetRemoveTester<E> extends AbstractMultisetTester<E> {
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemoveNegative() {
try {
getMultiset().remove(samples.e0, -1);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
expectUnchanged();
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testRemoveUnsupported() {
try {
getMultiset().remove(samples.e0, 2);
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemoveZeroNoOp() {
int originalCount = getMultiset().count(samples.e0);
assertEquals("old count", originalCount, getMultiset().remove(samples.e0, 0));
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_present() {
assertEquals("multiset.remove(present, 2) didn't return the old count",
1, getMultiset().remove(samples.e0, 2));
assertFalse("multiset contains present after multiset.remove(present, 2)",
getMultiset().contains(samples.e0));
assertEquals(0, getMultiset().count(samples.e0));
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_some_occurrences_present() {
initThreeCopies();
assertEquals("multiset.remove(present, 2) didn't return the old count",
3, getMultiset().remove(samples.e0, 2));
assertTrue("multiset contains present after multiset.remove(present, 2)",
getMultiset().contains(samples.e0));
assertEquals(1, getMultiset().count(samples.e0));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_absent() {
assertEquals("multiset.remove(absent, 0) didn't return 0",
0, getMultiset().remove(samples.e3, 2));
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testRemove_occurrences_unsupported_absent() {
// notice: we don't care whether it succeeds, or fails with UOE
try {
assertEquals(
"multiset.remove(absent, 2) didn't return 0 or throw an exception",
0, getMultiset().remove(samples.e3, 2));
} catch (UnsupportedOperationException ok) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_0() {
int oldCount = getMultiset().count(samples.e0);
assertEquals("multiset.remove(E, 0) didn't return the old count",
oldCount, getMultiset().remove(samples.e0, 0));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_negative() {
try {
getMultiset().remove(samples.e0, -1);
fail("multiset.remove(E, -1) didn't throw an exception");
} catch (IllegalArgumentException required) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_wrongType() {
assertEquals("multiset.remove(wrongType, 1) didn't return 0",
0, getMultiset().remove(WrongType.VALUE, 1));
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES})
public void testRemove_nullPresent() {
initCollectionWithNullElement();
assertEquals(1, getMultiset().remove(null, 2));
assertFalse("multiset contains present after multiset.remove(present, 2)",
getMultiset().contains(null));
assertEquals(0, getMultiset().count(null));
}
@CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_QUERIES})
public void testRemove_nullAbsent() {
assertEquals(0, getMultiset().remove(null, 2));
}
@CollectionFeature.Require(value = SUPPORTS_REMOVE, absent = ALLOWS_NULL_QUERIES)
public void testRemove_nullForbidden() {
try {
getMultiset().remove(null, 2);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {}
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemoveAllIgnoresCount() {
initThreeCopies();
assertTrue(getMultiset().removeAll(Collections.singleton(samples.e0)));
ASSERT.that(getMultiset()).isEmpty();
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRetainAllIgnoresCount() {
initThreeCopies();
List<E> contents = Helpers.copyToList(getMultiset());
assertFalse(getMultiset().retainAll(Collections.singleton(samples.e0)));
expectContents(contents);
}
/**
* Returns {@link Method} instances for the remove tests that assume multisets
* support duplicates so that the test of {@code Multisets.forSet()} can
* suppress them.
*/
@GwtIncompatible("reflection")
public static List<Method> getRemoveDuplicateInitializingMethods() {
return Arrays.asList(
Helpers.getMethod(MultisetRemoveTester.class, "testRemove_some_occurrences_present"));
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultisetRemoveTester.java | Java | asf20 | 6,822 |
/*
* 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.annotations.GwtIncompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.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(emulated = true)
public abstract class AbstractMultisetSetCountTester<E>
extends AbstractMultisetTester<E> {
/*
* TODO: consider adding MultisetFeatures.SUPPORTS_SET_COUNT. Currently we
* assume that using setCount() to increase the count is permitted iff add()
* is permitted and similarly for decrease/remove(). We assume that a
* setCount() no-op is permitted if either add() or remove() is permitted,
* though we also allow it to "succeed" if neither is permitted.
*/
private void assertSetCount(E element, int count) {
setCountCheckReturnValue(element, count);
assertEquals(
"multiset.count() should return the value passed to setCount()",
count, getMultiset().count(element));
int size = 0;
for (Multiset.Entry<E> entry : getMultiset().entrySet()) {
size += entry.getCount();
}
assertEquals(
"multiset.size() should be the sum of the counts of all entries",
size, getMultiset().size());
}
/**
* Call the {@code setCount()} method under test, and check its return value.
*/
abstract void setCountCheckReturnValue(E element, int count);
/**
* Call the {@code setCount()} method under test, but do not check its return
* value. Callers should use this method over
* {@link #setCountCheckReturnValue(Object, int)} when they expect
* {@code setCount()} to throw an exception, as checking the return value
* could produce an incorrect error message like
* "setCount() should return the original count" instead of the message passed
* to a later invocation of {@code fail()}, like "setCount should throw
* UnsupportedOperationException."
*/
abstract void setCountNoCheckReturnValue(E element, int count);
private void assertSetCountIncreasingFailure(E element, int count) {
try {
setCountNoCheckReturnValue(element, count);
fail("a call to multiset.setCount() to increase an element's count "
+ "should throw");
} catch (UnsupportedOperationException expected) {
}
}
private void assertSetCountDecreasingFailure(E element, int count) {
try {
setCountNoCheckReturnValue(element, count);
fail("a call to multiset.setCount() to decrease an element's count "
+ "should throw");
} catch (UnsupportedOperationException expected) {
}
}
// Unconditional setCount no-ops.
private void assertZeroToZero() {
assertSetCount(samples.e3, 0);
}
private void assertOneToOne() {
assertSetCount(samples.e0, 1);
}
private void assertThreeToThree() {
initThreeCopies();
assertSetCount(samples.e0, 3);
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_zeroToZero_addSupported() {
assertZeroToZero();
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_zeroToZero_removeSupported() {
assertZeroToZero();
}
@CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCount_zeroToZero_unsupported() {
try {
assertZeroToZero();
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_oneToOne_addSupported() {
assertOneToOne();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_oneToOne_removeSupported() {
assertOneToOne();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCount_oneToOne_unsupported() {
try {
assertOneToOne();
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_threeToThree_addSupported() {
assertThreeToThree();
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_threeToThree_removeSupported() {
assertThreeToThree();
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCount_threeToThree_unsupported() {
try {
assertThreeToThree();
} catch (UnsupportedOperationException tolerated) {
}
}
// Unconditional setCount size increases:
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_zeroToOne_supported() {
assertSetCount(samples.e3, 1);
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
public void testSetCountZeroToOneConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertSetCount(samples.e3, 1);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
public void testSetCountZeroToOneConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator();
assertSetCount(samples.e3, 1);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_zeroToThree_supported() {
assertSetCount(samples.e3, 3);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_oneToThree_supported() {
assertSetCount(samples.e0, 3);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCount_zeroToOne_unsupported() {
assertSetCountIncreasingFailure(samples.e3, 1);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCount_zeroToThree_unsupported() {
assertSetCountIncreasingFailure(samples.e3, 3);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCount_oneToThree_unsupported() {
assertSetCountIncreasingFailure(samples.e3, 3);
}
// Unconditional setCount size decreases:
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_oneToZero_supported() {
assertSetCount(samples.e0, 0);
}
@CollectionFeature.Require({SUPPORTS_REMOVE,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testSetCountOneToZeroConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertSetCount(samples.e0, 0);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require({SUPPORTS_REMOVE,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testSetCountOneToZeroConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator();
assertSetCount(samples.e0, 0);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_threeToZero_supported() {
initThreeCopies();
assertSetCount(samples.e0, 0);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_threeToOne_supported() {
initThreeCopies();
assertSetCount(samples.e0, 1);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_oneToZero_unsupported() {
assertSetCountDecreasingFailure(samples.e0, 0);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_threeToZero_unsupported() {
initThreeCopies();
assertSetCountDecreasingFailure(samples.e0, 0);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_threeToOne_unsupported() {
initThreeCopies();
assertSetCountDecreasingFailure(samples.e0, 1);
}
// setCount with nulls:
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES})
public void testSetCount_removeNull_nullSupported() {
initCollectionWithNullElement();
assertSetCount(null, 0);
}
@CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES},
absent = RESTRICTS_ELEMENTS)
public void testSetCount_addNull_nullSupported() {
assertSetCount(null, 1);
}
@CollectionFeature.Require(value = SUPPORTS_ADD, absent = ALLOWS_NULL_VALUES)
public void testSetCount_addNull_nullUnsupported() {
try {
setCountNoCheckReturnValue(null, 1);
fail("adding null with setCount() should throw NullPointerException");
} catch (NullPointerException expected) {
}
}
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testSetCount_noOpNull_nullSupported() {
try {
assertSetCount(null, 0);
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
public void testSetCount_noOpNull_nullUnsupported() {
try {
assertSetCount(null, 0);
} catch (NullPointerException tolerated) {
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testSetCount_existingNoNopNull_nullSupported() {
initCollectionWithNullElement();
try {
assertSetCount(null, 1);
} catch (UnsupportedOperationException tolerated) {
}
}
// Negative count.
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_negative_removeSupported() {
try {
setCountNoCheckReturnValue(samples.e3, -1);
fail("calling setCount() with a negative count should throw "
+ "IllegalArgumentException");
} catch (IllegalArgumentException expected) {
}
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_negative_removeUnsupported() {
try {
setCountNoCheckReturnValue(samples.e3, -1);
fail("calling setCount() with a negative count should throw "
+ "IllegalArgumentException or UnsupportedOperationException");
} catch (IllegalArgumentException expected) {
} catch (UnsupportedOperationException expected) {
}
}
// TODO: test adding element of wrong type
/**
* 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.
*/
@GwtIncompatible("reflection")
public static List<Method> getSetCountDuplicateInitializingMethods() {
return Arrays.asList(
getMethod("testSetCount_threeToThree_removeSupported"),
getMethod("testSetCount_threeToZero_supported"),
getMethod("testSetCount_threeToOne_supported"));
}
@GwtIncompatible("reflection")
private static Method getMethod(String methodName) {
return Helpers.getMethod(AbstractMultisetSetCountTester.class, methodName);
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/AbstractMultisetSetCountTester.java | Java | asf20 | 13,714 |
/*
* 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.checkArgument;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;
import com.google.common.collect.Multisets;
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.SetTestSuiteBuilder;
import com.google.common.collect.testing.TestSetGenerator;
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.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
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
*/
public class MultisetTestSuiteBuilder<E> extends
AbstractCollectionTestSuiteBuilder<MultisetTestSuiteBuilder<E>, E> {
public static <E> MultisetTestSuiteBuilder<E> using(
TestMultisetGenerator<E> generator) {
return new MultisetTestSuiteBuilder<E>().usingGenerator(generator);
}
public enum NoRecurse implements Feature<Void> {
NO_ENTRY_SET;
@Override
public Set<Feature<? super Void>> getImpliedFeatures() {
return Collections.emptySet();
}
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers
= Helpers.copyToList(super.getTesters());
testers.add(CollectionSerializationEqualTester.class);
testers.add(MultisetAddTester.class);
testers.add(MultisetContainsTester.class);
testers.add(MultisetCountTester.class);
testers.add(MultisetElementSetTester.class);
testers.add(MultisetEqualsTester.class);
testers.add(MultisetReadsTester.class);
testers.add(MultisetSetCountConditionallyTester.class);
testers.add(MultisetSetCountUnconditionallyTester.class);
testers.add(MultisetRemoveTester.class);
testers.add(MultisetEntrySetTester.class);
testers.add(MultisetIteratorTester.class);
testers.add(MultisetSerializationTester.class);
return testers;
}
private static Set<Feature<?>> computeEntrySetFeatures(
Set<Feature<?>> features) {
Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>();
derivedFeatures.addAll(features);
derivedFeatures.remove(CollectionFeature.GENERAL_PURPOSE);
derivedFeatures.remove(CollectionFeature.SUPPORTS_ADD);
derivedFeatures.remove(CollectionFeature.ALLOWS_NULL_VALUES);
derivedFeatures.add(CollectionFeature.REJECTS_DUPLICATES_AT_CREATION);
if (!derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) {
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
}
return derivedFeatures;
}
static Set<Feature<?>> computeElementSetFeatures(
Set<Feature<?>> features) {
Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>();
derivedFeatures.addAll(features);
derivedFeatures.remove(CollectionFeature.GENERAL_PURPOSE);
derivedFeatures.remove(CollectionFeature.SUPPORTS_ADD);
if (!derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) {
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
}
return derivedFeatures;
}
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));
derivedSuites.add(createElementSetTestSuite(parentBuilder));
if (!parentBuilder.getFeatures().contains(NoRecurse.NO_ENTRY_SET)) {
derivedSuites.add(
SetTestSuiteBuilder.using(new EntrySetGenerator<E>(parentBuilder.getSubjectGenerator()))
.named(getName() + ".entrySet")
.withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
}
if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {
derivedSuites.add(MultisetTestSuiteBuilder
.using(new ReserializedMultisetGenerator<E>(parentBuilder.getSubjectGenerator()))
.named(getName() + " reserialized")
.withFeatures(computeReserializedMultisetFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
}
return derivedSuites;
}
TestSuite createElementSetTestSuite(FeatureSpecificTestSuiteBuilder<
?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) {
return SetTestSuiteBuilder
.using(new ElementSetGenerator<E>(parentBuilder.getSubjectGenerator()))
.named(getName() + ".elementSet")
.withFeatures(computeElementSetFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
static class ElementSetGenerator<E> implements TestSetGenerator<E> {
final OneSizeTestContainerGenerator<Collection<E>, E> gen;
ElementSetGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) {
this.gen = gen;
}
@Override
public SampleElements<E> samples() {
return gen.samples();
}
@Override
public Set<E> create(Object... elements) {
Object[] duplicated = new Object[elements.length * 2];
for (int i = 0; i < elements.length; i++) {
duplicated[i] = elements[i];
duplicated[i + elements.length] = elements[i];
}
return ((Multiset<E>) gen.create(duplicated)).elementSet();
}
@Override
public E[] createArray(int length) {
return gen.createArray(length);
}
@Override
public Iterable<E> order(List<E> insertionOrder) {
return gen.order(new ArrayList<E>(new LinkedHashSet<E>(insertionOrder)));
}
}
static class EntrySetGenerator<E> implements TestSetGenerator<Multiset.Entry<E>> {
final OneSizeTestContainerGenerator<Collection<E>, E> gen;
private EntrySetGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) {
this.gen = gen;
}
@Override
public SampleElements<Multiset.Entry<E>> samples() {
SampleElements<E> samples = gen.samples();
return new SampleElements<Multiset.Entry<E>>(
Multisets.immutableEntry(samples.e0, 3),
Multisets.immutableEntry(samples.e1, 4),
Multisets.immutableEntry(samples.e2, 1),
Multisets.immutableEntry(samples.e3, 5),
Multisets.immutableEntry(samples.e4, 2));
}
@Override
public Set<Multiset.Entry<E>> create(Object... entries) {
List<Object> contents = new ArrayList<Object>();
Set<E> elements = new HashSet<E>();
for (Object o : entries) {
@SuppressWarnings("unchecked")
Multiset.Entry<E> entry = (Entry<E>) o;
checkArgument(elements.add(entry.getElement()),
"Duplicate keys not allowed in EntrySetGenerator");
for (int i = 0; i < entry.getCount(); i++) {
contents.add(entry.getElement());
}
}
return ((Multiset<E>) gen.create(contents.toArray())).entrySet();
}
@SuppressWarnings("unchecked")
@Override
public Multiset.Entry<E>[] createArray(int length) {
return new Multiset.Entry[length];
}
@Override
public Iterable<Entry<E>> order(List<Entry<E>> insertionOrder) {
// We mimic the order from gen.
Map<E, Entry<E>> map = new LinkedHashMap<E, Entry<E>>();
for (Entry<E> entry : insertionOrder) {
map.put(entry.getElement(), entry);
}
Set<E> seen = new HashSet<E>();
List<Entry<E>> order = new ArrayList<Entry<E>>();
for (E e : gen.order(new ArrayList<E>(map.keySet()))) {
if (seen.add(e)) {
order.add(map.get(e));
}
}
return order;
}
}
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);
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultisetTestSuiteBuilder.java | Java | asf20 | 10,372 |
/*
* 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.base.Preconditions.checkArgument;
import static com.google.common.collect.testing.Helpers.mapEntry;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.AbstractTester;
import com.google.common.collect.testing.CollectionTestSuiteBuilder;
import com.google.common.collect.testing.DerivedGenerator;
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.TestCollectionGenerator;
import com.google.common.collect.testing.TestMapGenerator;
import com.google.common.collect.testing.TestSubjectGenerator;
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.ListFeature;
import com.google.common.collect.testing.features.MapFeature;
import com.google.common.testing.SerializableTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a {@code Multimap} implementation.
*
* @author Louis Wasserman
*/
public class MultimapTestSuiteBuilder<K, V, M extends Multimap<K, V>> extends
PerCollectionSizeTestSuiteBuilder<
MultimapTestSuiteBuilder<K, V, M>,
TestMultimapGenerator<K, V, M>, M, Map.Entry<K, V>> {
public static <K, V, M extends Multimap<K, V>> MultimapTestSuiteBuilder<K, V, M> using(
TestMultimapGenerator<K, V, M> generator) {
return new MultimapTestSuiteBuilder<K, V, M>().usingGenerator(generator);
}
// Class parameters must be raw.
@Override
protected List<Class<? extends AbstractTester>> getTesters() {
return ImmutableList.<Class<? extends AbstractTester>> of(
MultimapAsMapGetTester.class,
MultimapAsMapTester.class,
MultimapSizeTester.class,
MultimapClearTester.class,
MultimapContainsKeyTester.class,
MultimapContainsValueTester.class,
MultimapContainsEntryTester.class,
MultimapEntriesTester.class,
MultimapEqualsTester.class,
MultimapGetTester.class,
MultimapKeySetTester.class,
MultimapKeysTester.class,
MultimapPutTester.class,
MultimapPutAllMultimapTester.class,
MultimapPutIterableTester.class,
MultimapReplaceValuesTester.class,
MultimapRemoveEntryTester.class,
MultimapRemoveAllTester.class,
MultimapToStringTester.class,
MultimapValuesTester.class);
}
@Override
protected List<TestSuite> createDerivedSuites(
FeatureSpecificTestSuiteBuilder<
?,
? extends OneSizeTestContainerGenerator<M, 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(MultimapTestSuiteBuilder.using(
new ReserializedMultimapGenerator<K, V, M>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeReserializedMultimapFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + " reserialized")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
}
derivedSuites.add(MapTestSuiteBuilder.using(
new AsMapGenerator<K, V, M>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeAsMapFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".asMap")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
derivedSuites.add(computeEntriesTestSuite(parentBuilder));
derivedSuites.add(computeMultimapGetTestSuite(parentBuilder));
derivedSuites.add(computeMultimapAsMapGetTestSuite(parentBuilder));
derivedSuites.add(computeKeysTestSuite(parentBuilder));
derivedSuites.add(computeValuesTestSuite(parentBuilder));
return derivedSuites;
}
TestSuite computeValuesTestSuite(
FeatureSpecificTestSuiteBuilder<?, ?
extends OneSizeTestContainerGenerator<M, Map.Entry<K, V>>> parentBuilder) {
return CollectionTestSuiteBuilder.using(
new ValuesGenerator<K, V, M>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeValuesFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".values")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
TestSuite computeEntriesTestSuite(
FeatureSpecificTestSuiteBuilder<?, ?
extends OneSizeTestContainerGenerator<M, Map.Entry<K, V>>> parentBuilder) {
return CollectionTestSuiteBuilder.using(
new EntriesGenerator<K, V, M>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeEntriesFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".entries")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
TestSuite computeMultimapGetTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<M, Map.Entry<K, V>>> parentBuilder) {
return CollectionTestSuiteBuilder.using(
new MultimapGetGenerator<K, V, M>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeMultimapGetFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".get[key]")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
TestSuite computeMultimapAsMapGetTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<M, Map.Entry<K, V>>> parentBuilder) {
Set<Feature<?>> features = computeMultimapAsMapGetFeatures(parentBuilder.getFeatures());
if (Collections.disjoint(features, EnumSet.allOf(CollectionSize.class))) {
return new TestSuite();
} else {
return CollectionTestSuiteBuilder.using(
new MultimapAsMapGetGenerator<K, V, M>(parentBuilder.getSubjectGenerator()))
.withFeatures(features)
.named(parentBuilder.getName() + ".asMap[].get[key]")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
}
TestSuite computeKeysTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<M, Map.Entry<K, V>>> parentBuilder) {
return MultisetTestSuiteBuilder.using(
new KeysGenerator<K, V, M>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeKeysFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".keys")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
static Set<Feature<?>> computeDerivedCollectionFeatures(Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> derivedFeatures = Helpers.copyToSet(multimapFeatures);
if (!derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) {
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
}
if (derivedFeatures.remove(MapFeature.SUPPORTS_REMOVE)) {
derivedFeatures.add(CollectionFeature.SUPPORTS_REMOVE);
}
return derivedFeatures;
}
static Set<Feature<?>> computeEntriesFeatures(
Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> result = computeDerivedCollectionFeatures(multimapFeatures);
if (multimapFeatures.contains(MapFeature.ALLOWS_NULL_ENTRY_QUERIES)) {
result.add(CollectionFeature.ALLOWS_NULL_QUERIES);
}
return result;
}
static Set<Feature<?>> computeValuesFeatures(
Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> result = computeDerivedCollectionFeatures(multimapFeatures);
if (multimapFeatures.contains(MapFeature.ALLOWS_NULL_VALUES)) {
result.add(CollectionFeature.ALLOWS_NULL_VALUES);
}
if (multimapFeatures.contains(MapFeature.ALLOWS_NULL_VALUE_QUERIES)) {
result.add(CollectionFeature.ALLOWS_NULL_QUERIES);
}
return result;
}
static Set<Feature<?>> computeKeysFeatures(
Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> result = computeDerivedCollectionFeatures(multimapFeatures);
if (multimapFeatures.contains(MapFeature.ALLOWS_NULL_KEYS)) {
result.add(CollectionFeature.ALLOWS_NULL_VALUES);
}
if (multimapFeatures.contains(MapFeature.ALLOWS_NULL_KEY_QUERIES)) {
result.add(CollectionFeature.ALLOWS_NULL_QUERIES);
}
return result;
}
private static Set<Feature<?>> computeReserializedMultimapFeatures(
Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> derivedFeatures = Helpers.copyToSet(multimapFeatures);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);
return derivedFeatures;
}
private static Set<Feature<?>> computeAsMapFeatures(
Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> derivedFeatures = Helpers.copyToSet(multimapFeatures);
derivedFeatures.remove(MapFeature.GENERAL_PURPOSE);
derivedFeatures.remove(MapFeature.SUPPORTS_PUT);
derivedFeatures.remove(MapFeature.ALLOWS_NULL_VALUES);
derivedFeatures.add(MapFeature.ALLOWS_NULL_VALUE_QUERIES);
derivedFeatures.add(MapFeature.REJECTS_DUPLICATES_AT_CREATION);
if (!derivedFeatures.contains(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) {
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
}
return derivedFeatures;
}
private static final Multimap<Feature<?>, Feature<?>> GET_FEATURE_MAP = ImmutableMultimap
.<Feature<?>, Feature<?>> builder()
.put(
MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION)
.put(MapFeature.GENERAL_PURPOSE, ListFeature.SUPPORTS_ADD_WITH_INDEX)
.put(MapFeature.GENERAL_PURPOSE, ListFeature.SUPPORTS_REMOVE_WITH_INDEX)
.put(MapFeature.GENERAL_PURPOSE, ListFeature.SUPPORTS_SET)
.put(MapFeature.ALLOWS_NULL_VALUE_QUERIES,
CollectionFeature.ALLOWS_NULL_QUERIES)
.put(MapFeature.ALLOWS_NULL_VALUES, CollectionFeature.ALLOWS_NULL_VALUES)
.put(MapFeature.SUPPORTS_REMOVE, CollectionFeature.SUPPORTS_REMOVE)
.put(MapFeature.SUPPORTS_PUT, CollectionFeature.SUPPORTS_ADD)
.build();
Set<Feature<?>> computeMultimapGetFeatures(
Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> derivedFeatures = Helpers.copyToSet(multimapFeatures);
for (Map.Entry<Feature<?>, Feature<?>> entry : GET_FEATURE_MAP.entries()) {
if (derivedFeatures.contains(entry.getKey())) {
derivedFeatures.add(entry.getValue());
}
}
if (derivedFeatures.remove(MultimapFeature.VALUE_COLLECTIONS_SUPPORT_ITERATOR_REMOVE)) {
derivedFeatures.add(CollectionFeature.SUPPORTS_ITERATOR_REMOVE);
}
if (!derivedFeatures.contains(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) {
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
}
derivedFeatures.removeAll(GET_FEATURE_MAP.keySet());
return derivedFeatures;
}
Set<Feature<?>> computeMultimapAsMapGetFeatures(
Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> derivedFeatures = Helpers.copyToSet(
computeMultimapGetFeatures(multimapFeatures));
if (derivedFeatures.remove(CollectionSize.ANY)) {
derivedFeatures.addAll(CollectionSize.ANY.getImpliedFeatures());
}
derivedFeatures.remove(CollectionSize.ZERO);
return derivedFeatures;
}
private static class AsMapGenerator<K, V, M extends Multimap<K, V>> implements
TestMapGenerator<K, Collection<V>>, DerivedGenerator {
private final OneSizeTestContainerGenerator<M, Map.Entry<K, V>> multimapGenerator;
public AsMapGenerator(
OneSizeTestContainerGenerator<M, Entry<K, V>> multimapGenerator) {
this.multimapGenerator = multimapGenerator;
}
@Override
public TestSubjectGenerator<?> getInnerGenerator() {
return multimapGenerator;
}
private Collection<V> createCollection(V v) {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.createCollection(Collections.singleton(v));
}
@Override
public SampleElements<Entry<K, Collection<V>>> samples() {
SampleElements<K> sampleKeys =
((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator()).sampleKeys();
SampleElements<V> sampleValues =
((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator()).sampleValues();
return new SampleElements<Entry<K, Collection<V>>>(
mapEntry(sampleKeys.e0, createCollection(sampleValues.e0)),
mapEntry(sampleKeys.e1, createCollection(sampleValues.e1)),
mapEntry(sampleKeys.e2, createCollection(sampleValues.e2)),
mapEntry(sampleKeys.e3, createCollection(sampleValues.e3)),
mapEntry(sampleKeys.e4, createCollection(sampleValues.e4)));
}
@Override
public Map<K, Collection<V>> create(Object... elements) {
Set<K> keySet = new HashSet<K>();
List<Map.Entry<K, V>> builder = new ArrayList<Entry<K, V>>();
for (Object o : elements) {
Map.Entry<K, Collection<V>> entry = (Entry<K, Collection<V>>) o;
keySet.add(entry.getKey());
for (V v : entry.getValue()) {
builder.add(mapEntry(entry.getKey(), v));
}
}
checkArgument(keySet.size() == elements.length, "Duplicate keys");
return multimapGenerator.create(builder.toArray()).asMap();
}
@SuppressWarnings("unchecked")
@Override
public Entry<K, Collection<V>>[] createArray(int length) {
return new Entry[length];
}
@Override
public Iterable<Entry<K, Collection<V>>> order(List<Entry<K, Collection<V>>> insertionOrder) {
Map<K, Collection<V>> map = new HashMap<K, Collection<V>>();
List<Map.Entry<K, V>> builder = new ArrayList<Entry<K, V>>();
for (Entry<K, Collection<V>> entry : insertionOrder) {
for (V v : entry.getValue()) {
builder.add(mapEntry(entry.getKey(), v));
}
map.put(entry.getKey(), entry.getValue());
}
Iterable<Map.Entry<K, V>> ordered = multimapGenerator.order(builder);
LinkedHashMap<K, Collection<V>> orderedMap = new LinkedHashMap<K, Collection<V>>();
for (Map.Entry<K, V> entry : ordered) {
orderedMap.put(entry.getKey(), map.get(entry.getKey()));
}
return orderedMap.entrySet();
}
@Override
public K[] createKeyArray(int length) {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.createKeyArray(length);
}
@SuppressWarnings("unchecked")
@Override
public Collection<V>[] createValueArray(int length) {
return new Collection[length];
}
}
static class EntriesGenerator<K, V, M extends Multimap<K, V>>
implements TestCollectionGenerator<Entry<K, V>>, DerivedGenerator {
private final OneSizeTestContainerGenerator<M, Map.Entry<K, V>> multimapGenerator;
public EntriesGenerator(
OneSizeTestContainerGenerator<M, Entry<K, V>> multimapGenerator) {
this.multimapGenerator = multimapGenerator;
}
@Override
public TestSubjectGenerator<?> getInnerGenerator() {
return multimapGenerator;
}
@Override
public SampleElements<Entry<K, V>> samples() {
return multimapGenerator.samples();
}
@Override
public Collection<Entry<K, V>> create(Object... elements) {
return multimapGenerator.create(elements).entries();
}
@SuppressWarnings("unchecked")
@Override
public Entry<K, V>[] createArray(int length) {
return new Entry[length];
}
@Override
public Iterable<Entry<K, V>> order(List<Entry<K, V>> insertionOrder) {
return multimapGenerator.order(insertionOrder);
}
}
static class ValuesGenerator<K, V, M extends Multimap<K, V>>
implements TestCollectionGenerator<V> {
private final OneSizeTestContainerGenerator<M, Map.Entry<K, V>> multimapGenerator;
public ValuesGenerator(
OneSizeTestContainerGenerator<M, Entry<K, V>> multimapGenerator) {
this.multimapGenerator = multimapGenerator;
}
@Override
public SampleElements<V> samples() {
return
((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator()).sampleValues();
}
@Override
public Collection<V> create(Object... elements) {
K k =
((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator()).sampleKeys().e0;
Entry<K, V>[] entries = new Entry[elements.length];
for (int i = 0; i < elements.length; i++) {
entries[i] = mapEntry(k, (V) elements[i]);
}
return multimapGenerator.create(entries).values();
}
@SuppressWarnings("unchecked")
@Override
public V[] createArray(int length) {
return ((TestMultimapGenerator<K, V, M>)
multimapGenerator.getInnerGenerator()).createValueArray(length);
}
@Override
public Iterable<V> order(List<V> insertionOrder) {
K k =
((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator()).sampleKeys().e0;
List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>();
for (V v : insertionOrder) {
entries.add(mapEntry(k, v));
}
Iterable<Entry<K, V>> ordered = multimapGenerator.order(entries);
List<V> orderedValues = new ArrayList<V>();
for (Entry<K, V> entry : ordered) {
orderedValues.add(entry.getValue());
}
return orderedValues;
}
}
static class KeysGenerator<K, V, M extends Multimap<K, V>> implements
TestMultisetGenerator<K>, DerivedGenerator {
private final OneSizeTestContainerGenerator<M, Map.Entry<K, V>> multimapGenerator;
public KeysGenerator(
OneSizeTestContainerGenerator<M, Entry<K, V>> multimapGenerator) {
this.multimapGenerator = multimapGenerator;
}
@Override
public TestSubjectGenerator<?> getInnerGenerator() {
return multimapGenerator;
}
@Override
public SampleElements<K> samples() {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator()).sampleKeys();
}
@Override
public Multiset<K> create(Object... elements) {
/*
* This is nasty and complicated, but it's the only way to make sure keys get mapped to enough
* distinct values.
*/
Map.Entry[] entries = new Map.Entry[elements.length];
Map<K, Iterator<V>> valueIterators = new HashMap<K, Iterator<V>>();
for (int i = 0; i < elements.length; i++) {
@SuppressWarnings("unchecked")
K key = (K) elements[i];
Iterator<V> valueItr = valueIterators.get(key);
if (valueItr == null) {
valueIterators.put(key, valueItr = sampleValuesIterator());
}
entries[i] = mapEntry((K) elements[i], valueItr.next());
}
return multimapGenerator.create(entries).keys();
}
private Iterator<V> sampleValuesIterator() {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator
.getInnerGenerator()).sampleValues().iterator();
}
@SuppressWarnings("unchecked")
@Override
public K[] createArray(int length) {
return ((TestMultimapGenerator<K, V, M>)
multimapGenerator.getInnerGenerator()).createKeyArray(length);
}
@Override
public Iterable<K> order(List<K> insertionOrder) {
Iterator<V> valueIter = sampleValuesIterator();
List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>();
for (K k : insertionOrder) {
entries.add(mapEntry(k, valueIter.next()));
}
Iterable<Entry<K, V>> ordered = multimapGenerator.order(entries);
List<K> orderedValues = new ArrayList<K>();
for (Entry<K, V> entry : ordered) {
orderedValues.add(entry.getKey());
}
return orderedValues;
}
}
static class MultimapGetGenerator<K, V, M extends Multimap<K, V>>
implements TestCollectionGenerator<V> {
final OneSizeTestContainerGenerator<M, Map.Entry<K, V>> multimapGenerator;
public MultimapGetGenerator(
OneSizeTestContainerGenerator<
M, Map.Entry<K, V>> multimapGenerator) {
this.multimapGenerator = multimapGenerator;
}
@Override
public SampleElements<V> samples() {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.sampleValues();
}
@Override
public V[] createArray(int length) {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.createValueArray(length);
}
@Override
public Iterable<V> order(List<V> insertionOrder) {
K k = ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.sampleKeys().e0;
List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>();
for (V v : insertionOrder) {
entries.add(mapEntry(k, v));
}
Iterable<Entry<K, V>> orderedEntries = multimapGenerator.order(entries);
List<V> values = new ArrayList<V>();
for (Entry<K, V> entry : orderedEntries) {
values.add(entry.getValue());
}
return values;
}
@Override
public Collection<V> create(Object... elements) {
Entry<K, V>[] array = multimapGenerator.createArray(elements.length);
K k = ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.sampleKeys().e0;
for (int i = 0; i < elements.length; i++) {
array[i] = mapEntry(k, (V) elements[i]);
}
return multimapGenerator.create(array).get(k);
}
}
static class MultimapAsMapGetGenerator<K, V, M extends Multimap<K, V>>
extends MultimapGetGenerator<K, V, M> {
public MultimapAsMapGetGenerator(
OneSizeTestContainerGenerator<
M, Map.Entry<K, V>> multimapGenerator) {
super(multimapGenerator);
}
@Override
public Collection<V> create(Object... elements) {
Entry<K, V>[] array = multimapGenerator.createArray(elements.length);
K k = ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.sampleKeys().e0;
for (int i = 0; i < elements.length; i++) {
array[i] = mapEntry(k, (V) elements[i]);
}
return multimapGenerator.create(array).asMap().get(k);
}
}
private static class ReserializedMultimapGenerator<K, V, M extends Multimap<K, V>>
implements TestMultimapGenerator<K, V, M> {
private final OneSizeTestContainerGenerator<M, Map.Entry<K, V>> multimapGenerator;
public ReserializedMultimapGenerator(
OneSizeTestContainerGenerator<
M, Map.Entry<K, V>> multimapGenerator) {
this.multimapGenerator = multimapGenerator;
}
@Override
public SampleElements<Map.Entry<K, V>> samples() {
return multimapGenerator.samples();
}
@Override
public Map.Entry<K, V>[] createArray(int length) {
return multimapGenerator.createArray(length);
}
@Override
public Iterable<Map.Entry<K, V>> order(
List<Map.Entry<K, V>> insertionOrder) {
return multimapGenerator.order(insertionOrder);
}
@Override
public M create(Object... elements) {
return SerializableTester.reserialize(((TestMultimapGenerator<K, V, M>) multimapGenerator
.getInnerGenerator()).create(elements));
}
@Override
public K[] createKeyArray(int length) {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.createKeyArray(length);
}
@Override
public V[] createValueArray(int length) {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.createValueArray(length);
}
@Override
public SampleElements<K> sampleKeys() {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.sampleKeys();
}
@Override
public SampleElements<V> sampleValues() {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.sampleValues();
}
@Override
public Collection<V> createCollection(Iterable<? extends V> values) {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.createCollection(values);
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapTestSuiteBuilder.java | Java | asf20 | 26,053 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Tester for {@code Multimap.values}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapValuesTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
public void testValues() {
List<V> expected = Lists.newArrayList();
for (Map.Entry<K, V> entry : getSampleElements()) {
expected.add(entry.getValue());
}
ASSERT.that(multimap().values()).has().exactlyAs(expected);
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testValuesInOrder() {
List<V> expected = Lists.newArrayList();
for (Map.Entry<K, V> entry : getOrderedElements()) {
expected.add(entry.getValue());
}
ASSERT.that(multimap().values()).has().exactlyAs(expected).inOrder();
}
@CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE)
@CollectionSize.Require(ONE)
public void testValuesIteratorRemove() {
Iterator<V> valuesItr = multimap().values().iterator();
valuesItr.next();
valuesItr.remove();
assertTrue(multimap().isEmpty());
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapValuesTester.java | Java | asf20 | 2,316 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collection;
/**
* Tester for {@link Multimap#putAll(Multimap)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapPutAllMultimapTester<K, V>
extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@MapFeature.Require(absent = SUPPORTS_PUT)
public void testPutUnsupported() {
try {
multimap().putAll(getSubjectGenerator().create(
Helpers.mapEntry(sampleKeys().e3, sampleValues().e3)));
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {}
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllIntoEmpty() {
Multimap<K, V> target = getSubjectGenerator().create();
assertEquals(!multimap().isEmpty(), target.putAll(multimap()));
assertEquals(multimap(), target);
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAll() {
Multimap<K, V> source = getSubjectGenerator().create(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3),
Helpers.mapEntry(sampleKeys().e3, sampleValues().e3));
assertTrue(multimap().putAll(source));
assertTrue(multimap().containsEntry(sampleKeys().e0, sampleValues().e3));
assertTrue(multimap().containsEntry(sampleKeys().e3, sampleValues().e3));
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
public void testPutAllWithNullValue() {
Multimap<K, V> source = getSubjectGenerator().create(
Helpers.mapEntry(sampleKeys().e0, null));
assertTrue(multimap().putAll(source));
assertTrue(multimap().containsEntry(sampleKeys().e0, null));
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS})
public void testPutAllWithNullKey() {
Multimap<K, V> source = getSubjectGenerator().create(
Helpers.mapEntry(null, sampleValues().e0));
assertTrue(multimap().putAll(source));
assertTrue(multimap().containsEntry(null, sampleValues().e0));
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
public void testPutAllRejectsNullValue() {
Multimap<K, V> source = getSubjectGenerator().create(
Helpers.mapEntry(sampleKeys().e0, null));
try {
multimap().putAll(source);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {}
expectUnchanged();
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_KEYS)
public void testPutAllRejectsNullKey() {
Multimap<K, V> source = getSubjectGenerator().create(
Helpers.mapEntry(null, sampleValues().e0));
try {
multimap().putAll(source);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {}
expectUnchanged();
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllPropagatesToGet() {
Multimap<K, V> source = getSubjectGenerator().create(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3),
Helpers.mapEntry(sampleKeys().e3, sampleValues().e3));
Collection<V> getCollection = multimap().get(sampleKeys().e0);
int getCollectionSize = getCollection.size();
assertTrue(multimap().putAll(source));
assertEquals(getCollectionSize + 1, getCollection.size());
ASSERT.that(getCollection).has().allOf(sampleValues().e3);
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapPutAllMultimapTester.java | Java | asf20 | 4,409 |
/*
* 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.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()));
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultisetNavigationTester.java | Java | asf20 | 26,553 |
/*
* 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()));
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/AbstractBiMapTester.java | Java | asf20 | 2,624 |
/*
* 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);
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/AbstractMultisetTester.java | Java | asf20 | 1,208 |
/*
* 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.ListMultimap;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.SampleElements;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* A skeleton generator for a {@code ListMultimap} implementation.
*
* @author Louis Wasserman
*/
@GwtCompatible
public abstract class TestStringListMultimapGenerator
implements TestListMultimapGenerator<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 SampleElements<String> sampleKeys() {
return new SampleElements<String>("one", "two", "three", "four", "five");
}
@Override
public SampleElements<String> sampleValues() {
return new SampleElements<String>("January", "February", "March", "April", "May");
}
@Override
public Collection<String> createCollection(Iterable<? extends String> values) {
return Helpers.copyToList(values);
}
@Override
public final ListMultimap<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 ListMultimap<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;
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/TestStringListMultimapGenerator.java | Java | asf20 | 3,017 |
/*
* 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.SortedSetMultimap;
/**
* Tester for {@link SortedSetMultimap#get(Object)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class SortedSetMultimapGetTester<K, V>
extends AbstractMultimapTester<K, V, SortedSetMultimap<K, V>> {
public void testValueComparator() {
assertEquals(
multimap().valueComparator(),
multimap().get(sampleKeys().e0).comparator());
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/SortedSetMultimapGetTester.java | Java | asf20 | 1,133 |
/*
* 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);
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/BiMapPutTester.java | Java | asf20 | 3,265 |
/*
* 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.annotations.GwtIncompatible;
import com.google.common.collect.BiMap;
import com.google.common.collect.testing.Helpers;
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(emulated = true)
public class BiMapInverseTester<K, V> extends AbstractBiMapTester<K, V> {
public void testInverseSame() {
assertSame(getMap(), getMap().inverse().inverse());
}
@CollectionFeature.Require(SERIALIZABLE)
public void testInverseSerialization() {
BiMapPair<K, V> pair = new BiMapPair<K, V>(getMap());
BiMapPair<K, V> copy = SerializableTester.reserialize(pair);
assertEquals(pair.forward, copy.forward);
assertEquals(pair.backward, copy.backward);
assertSame(copy.backward, copy.forward.inverse());
assertSame(copy.forward, copy.backward.inverse());
}
private static class BiMapPair<K, V> implements Serializable {
final BiMap<K, V> forward;
final BiMap<V, K> backward;
BiMapPair(BiMap<K, V> original) {
this.forward = original;
this.backward = original.inverse();
}
private static final long serialVersionUID = 0;
}
/**
* Returns {@link Method} instances for the tests that assume that the inverse will be the same
* after serialization.
*/
@GwtIncompatible("reflection")
public static List<Method> getInverseSameAfterSerializingMethods() {
return Collections.singletonList(getMethod("testInverseSerialization"));
}
@GwtIncompatible("reflection")
private static Method getMethod(String methodName) {
return Helpers.getMethod(BiMapInverseTester.class, methodName);
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/BiMapInverseTester.java | Java | asf20 | 2,834 |
/*
* 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.Helpers.mapEntry;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.collect.testing.AnEnum;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestEnumMapGenerator;
import com.google.common.collect.testing.TestListGenerator;
import com.google.common.collect.testing.TestStringListGenerator;
import com.google.common.collect.testing.TestStringMapGenerator;
import com.google.common.collect.testing.TestUnhashableCollectionGenerator;
import com.google.common.collect.testing.UnhashableObject;
import java.util.Collection;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* 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) {
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (Entry<String, String> entry : entries) {
builder.put(entry.getKey(), entry.getValue());
}
return builder.build();
}
}
public static class ImmutableMapCopyOfGenerator
extends TestStringMapGenerator {
@Override protected Map<String, String> create(Entry<String, String>[] entries) {
Map<String, String> builder = Maps.newLinkedHashMap();
for (Entry<String, String> entry : entries) {
builder.put(entry.getKey(), entry.getValue());
}
return ImmutableMap.copyOf(builder);
}
}
public static class ImmutableMapUnhashableValuesGenerator
extends TestUnhashableCollectionGenerator<Collection<UnhashableObject>> {
@Override public Collection<UnhashableObject> create(
UnhashableObject[] elements) {
ImmutableMap.Builder<Integer, UnhashableObject> builder = ImmutableMap.builder();
int key = 1;
for (UnhashableObject value : elements) {
builder.put(key++, value);
}
return builder.build().values();
}
}
public static class ImmutableMapKeyListGenerator extends TestStringListGenerator {
@Override
public List<String> create(String[] elements) {
ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder();
for (int i = 0; i < elements.length; i++) {
builder.put(elements[i], i);
}
return builder.build().keySet().asList();
}
}
public static class ImmutableMapValueListGenerator extends TestStringListGenerator {
@Override
public List<String> create(String[] elements) {
ImmutableMap.Builder<Integer, String> builder = ImmutableMap.builder();
for (int i = 0; i < elements.length; i++) {
builder.put(i, elements[i]);
}
return builder.build().values().asList();
}
}
public static class ImmutableMapEntryListGenerator
implements TestListGenerator<Entry<String, Integer>> {
@Override
public SampleElements<Entry<String, Integer>> samples() {
return new SampleElements<Entry<String, Integer>>(
mapEntry("foo", 5),
mapEntry("bar", 3),
mapEntry("baz", 17),
mapEntry("quux", 1),
mapEntry("toaster", -2));
}
@SuppressWarnings("unchecked")
@Override
public Entry<String, Integer>[] createArray(int length) {
return new Entry[length];
}
@Override
public Iterable<Entry<String, Integer>> order(List<Entry<String, Integer>> insertionOrder) {
return insertionOrder;
}
@Override
public List<Entry<String, Integer>> create(Object... elements) {
ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder();
for (Object o : elements) {
@SuppressWarnings("unchecked")
Entry<String, Integer> entry = (Entry<String, Integer>) o;
builder.put(entry);
}
return builder.build().entrySet().asList();
}
}
public static class ImmutableEnumMapGenerator extends TestEnumMapGenerator {
@Override
protected Map<AnEnum, String> create(Entry<AnEnum, String>[] entries) {
Map<AnEnum, String> map = Maps.newHashMap();
for (Entry<AnEnum, String> entry : entries) {
// checkArgument(!map.containsKey(entry.getKey()));
map.put(entry.getKey(), entry.getValue());
}
return Maps.immutableEnumMap(map);
}
}
public static class ImmutableMapCopyOfEnumMapGenerator extends TestEnumMapGenerator {
@Override
protected Map<AnEnum, String> create(Entry<AnEnum, String>[] entries) {
EnumMap<AnEnum, String> map = new EnumMap<AnEnum, String>(AnEnum.class);
for (Entry<AnEnum, String> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
return ImmutableMap.copyOf(map);
}
@Override
public Iterable<Entry<AnEnum, String>> order(List<Entry<AnEnum, String>> insertionOrder) {
return new Ordering<Entry<AnEnum, String>>() {
@Override
public int compare(Entry<AnEnum, String> left, Entry<AnEnum, String> right) {
return left.getKey().compareTo(right.getKey());
}
}.sortedCopy(insertionOrder);
}
}
private static String toStringOrNull(Object o) {
return (o == null) ? null : o.toString();
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MapGenerators.java | Java | asf20 | 6,221 |
/*
* 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_PUT;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Arrays;
import java.util.List;
/**
* Testers for {@link ListMultimap#replaceValues(Object, Iterable)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class ListMultimapReplaceValuesTester<K, V> extends AbstractListMultimapTester<K, V> {
@MapFeature.Require({SUPPORTS_PUT, SUPPORTS_REMOVE})
public void testReplaceValuesPreservesOrder() {
@SuppressWarnings("unchecked")
List<V> values = Arrays.asList(
sampleValues().e3,
sampleValues().e1,
sampleValues().e4);
for (K k : sampleKeys()) {
resetContainer();
multimap().replaceValues(k, values);
assertGet(k, values);
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/ListMultimapReplaceValuesTester.java | Java | asf20 | 1,639 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import com.google.common.testing.EqualsTester;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Testers for {@link com.google.common.collect.ListMultimap#asMap}.
*
* @author Louis Wasserman
* @param <K> The key type of the tested multimap.
* @param <V> The value type of the tested multimap.
*/
@GwtCompatible
public class ListMultimapAsMapTester<K, V> extends AbstractListMultimapTester<K, V> {
public void testAsMapValuesImplementList() {
for (Collection<V> valueCollection : multimap().asMap().values()) {
assertTrue(valueCollection instanceof List);
}
}
public void testAsMapGetImplementsList() {
for (K key : multimap().keySet()) {
assertTrue(multimap().asMap().get(key) instanceof List);
}
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testAsMapRemoveImplementsList() {
List<K> keys = new ArrayList<K>(multimap().keySet());
for (K key : keys) {
resetCollection();
assertTrue(multimap().asMap().remove(key) instanceof List);
}
}
@CollectionSize.Require(SEVERAL)
public void testEquals() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e1, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3));
Map<K, Collection<V>> expected = Maps.newHashMap();
expected.put(sampleKeys().e0, Lists.newArrayList(sampleValues().e0, sampleValues().e3));
expected.put(sampleKeys().e1, Lists.newArrayList(sampleValues().e0));
new EqualsTester()
.addEqualityGroup(expected, multimap().asMap())
.testEquals();
}
@CollectionSize.Require(SEVERAL)
public void testEntrySetEquals() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e1, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3));
Set<Entry<K, Collection<V>>> expected = Sets.newHashSet();
expected.add(Helpers.mapEntry(
sampleKeys().e0,
(Collection<V>) Lists.newArrayList(sampleValues().e0, sampleValues().e3)));
expected.add(Helpers.mapEntry(
sampleKeys().e1,
(Collection<V>) Lists.newArrayList(sampleValues().e0)));
new EqualsTester()
.addEqualityGroup(expected, multimap().asMap().entrySet())
.testEquals();
}
@CollectionSize.Require(SEVERAL)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testValuesRemove() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e1, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3));
assertTrue(multimap().asMap().values().remove(Collections.singletonList(sampleValues().e0)));
assertEquals(2, multimap().size());
assertEquals(
Collections.singletonMap(
sampleKeys().e0, Lists.newArrayList(sampleValues().e0, sampleValues().e3)),
multimap().asMap());
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/ListMultimapAsMapTester.java | Java | asf20 | 4,285 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.testing.EqualsTester;
/**
* Tests for {@code Multiset.equals} and {@code Multiset.hashCode}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultisetEqualsTester<E> extends AbstractMultisetTester<E> {
public void testEqualsSameContents() {
new EqualsTester()
.addEqualityGroup(
getMultiset(),
getSubjectGenerator().create(getSampleElements().toArray()))
.testEquals();
}
@CollectionSize.Require(absent = ZERO)
public void testNotEqualsEmpty() {
new EqualsTester()
.addEqualityGroup(getMultiset())
.addEqualityGroup(getSubjectGenerator().create())
.testEquals();
}
public void testHashCodeMatchesEntrySet() {
assertEquals(getMultiset().entrySet().hashCode(), getMultiset().hashCode());
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testEqualsMultisetWithNullValue() {
new EqualsTester()
.addEqualityGroup(getMultiset())
.addEqualityGroup(
getSubjectGenerator().create(createArrayWithNullElement()),
getSubjectGenerator().create(createArrayWithNullElement()))
.testEquals();
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultisetEqualsTester.java | Java | asf20 | 2,241 |
/*
* 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.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEY_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUE_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
/**
* Tests for {@link Multimap#remove(Object, Object)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapRemoveEntryTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemoveAbsent() {
assertFalse(multimap().remove(sampleKeys().e0, sampleValues().e1));
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemovePresent() {
assertTrue(multimap().remove(sampleKeys().e0, sampleValues().e0));
assertFalse(multimap().containsEntry(sampleKeys().e0, sampleValues().e0));
expectMissing(samples.e0);
assertEquals(getNumElements() - 1, multimap().size());
assertGet(sampleKeys().e0, ImmutableList.<V>of());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({ SUPPORTS_REMOVE, ALLOWS_NULL_KEYS })
public void testRemoveNullKeyPresent() {
initMultimapWithNullKey();
assertTrue(multimap().remove(null, getValueForNullKey()));
expectMissing(Helpers.mapEntry((K) null, getValueForNullKey()));
assertGet(getKeyForNullValue(), ImmutableList.<V>of());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({ SUPPORTS_REMOVE, ALLOWS_NULL_VALUES })
public void testRemoveNullValuePresent() {
initMultimapWithNullValue();
assertTrue(multimap().remove(getKeyForNullValue(), null));
expectMissing(Helpers.mapEntry(getKeyForNullValue(), (V) null));
assertGet(getKeyForNullValue(), ImmutableList.<V>of());
}
@MapFeature.Require({ SUPPORTS_REMOVE, ALLOWS_NULL_KEY_QUERIES})
public void testRemoveNullKeyAbsent() {
assertFalse(multimap().remove(null, sampleValues().e0));
expectUnchanged();
}
@MapFeature.Require({ SUPPORTS_REMOVE, ALLOWS_NULL_VALUE_QUERIES})
public void testRemoveNullValueAbsent() {
assertFalse(multimap().remove(sampleKeys().e0, null));
expectUnchanged();
}
@MapFeature.Require(value = SUPPORTS_REMOVE, absent = ALLOWS_NULL_VALUE_QUERIES)
public void testRemoveNullValueForbidden() {
try {
multimap().remove(sampleKeys().e0, null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
expectUnchanged();
}
@MapFeature.Require(value = SUPPORTS_REMOVE, absent = ALLOWS_NULL_KEY_QUERIES)
public void testRemoveNullKeyForbidden() {
try {
multimap().remove(null, sampleValues().e0);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
expectUnchanged();
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemovePropagatesToGet() {
List<Entry<K, V>> entries = Helpers.copyToList(multimap().entries());
for (Entry<K, V> entry : entries) {
resetContainer();
K key = entry.getKey();
V value = entry.getValue();
Collection<V> collection = multimap().get(key);
assertNotNull(collection);
Collection<V> expectedCollection = Helpers.copyToList(collection);
multimap().remove(key, value);
expectedCollection.remove(value);
ASSERT.that(collection).has().exactlyAs(expectedCollection);
assertEquals(!expectedCollection.isEmpty(), multimap().containsKey(key));
}
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemovePropagatesToAsMap() {
List<Entry<K, V>> entries = Helpers.copyToList(multimap().entries());
for (Entry<K, V> entry : entries) {
resetContainer();
K key = entry.getKey();
V value = entry.getValue();
Collection<V> collection = multimap().asMap().get(key);
assertNotNull(collection);
Collection<V> expectedCollection = Helpers.copyToList(collection);
multimap().remove(key, value);
expectedCollection.remove(value);
ASSERT.that(collection).has().exactlyAs(expectedCollection);
assertEquals(!expectedCollection.isEmpty(), multimap().containsKey(key));
}
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemovePropagatesToAsMapEntrySet() {
List<Entry<K, V>> entries = Helpers.copyToList(multimap().entries());
for (Entry<K, V> entry : entries) {
resetContainer();
K key = entry.getKey();
V value = entry.getValue();
Iterator<Entry<K, Collection<V>>> asMapItr = multimap().asMap().entrySet().iterator();
Collection<V> collection = null;
while (asMapItr.hasNext()) {
Entry<K, Collection<V>> asMapEntry = asMapItr.next();
if (key.equals(asMapEntry.getKey())) {
collection = asMapEntry.getValue();
break;
}
}
assertNotNull(collection);
Collection<V> expectedCollection = Helpers.copyToList(collection);
multimap().remove(key, value);
expectedCollection.remove(value);
ASSERT.that(collection).has().exactlyAs(expectedCollection);
assertEquals(!expectedCollection.isEmpty(), multimap().containsKey(key));
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapRemoveEntryTester.java | Java | asf20 | 6,755 |
/*
* 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.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUE_QUERIES;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
/**
* Tester for {@link Multimap#containsValue}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapContainsValueTester<K, V>
extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@CollectionSize.Require(absent = ZERO)
public void testContainsValueYes() {
assertTrue(multimap().containsValue(sampleValues().e0));
}
public void testContainsValueNo() {
assertFalse(multimap().containsValue(sampleValues().e3));
}
@MapFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testContainsNullValueYes() {
initMultimapWithNullValue();
assertTrue(multimap().containsValue(null));
}
@MapFeature.Require(ALLOWS_NULL_VALUE_QUERIES)
public void testContainsNullValueNo() {
assertFalse(multimap().containsValue(null));
}
@MapFeature.Require(absent = ALLOWS_NULL_VALUE_QUERIES)
public void testContainsNullValueFails() {
try {
multimap().containsValue(null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapContainsValueTester.java | Java | asf20 | 2,223 |
/*
* 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
*/
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountConditionallyTester.java | Java | asf20 | 3,764 |
/*
* 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));
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultisetSerializationTester.java | Java | asf20 | 1,798 |
/*
* 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.Helpers.copyToSet;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* Tests for {@link SetMultimap#replaceValues}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class SetMultimapPutAllTester<K, V>
extends AbstractMultimapTester<K, V, SetMultimap<K, V>> {
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllHandlesDuplicates() {
V v0 = sampleValues().e3;
V v1 = sampleValues().e2;
@SuppressWarnings("unchecked")
List<V> valuesToPut = Arrays.asList(v0, v1, v0);
for (K k : sampleKeys()) {
resetContainer();
Set<V> expectedValues = copyToSet(multimap().get(k));
multimap().putAll(k, valuesToPut);
expectedValues.addAll(valuesToPut);
assertGet(k, expectedValues);
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/SetMultimapPutAllTester.java | Java | asf20 | 1,716 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUE_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collection;
/**
* Tests for {@code Multimap.asMap().get(Object)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapAsMapGetTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@CollectionSize.Require(SEVERAL)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testPropagatesRemoveToMultimap() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e2));
Collection<V> result = multimap().asMap().get(sampleKeys().e0);
assertTrue(result.remove(sampleValues().e0));
assertFalse(multimap().containsEntry(sampleKeys().e0, sampleValues().e0));
assertEquals(2, multimap().size());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testPropagatesRemoveLastElementToMultimap() {
Collection<V> result = multimap().asMap().get(sampleKeys().e0);
assertTrue(result.remove(sampleValues().e0));
assertGet(sampleKeys().e0);
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testPropagatesClearToMultimap() {
Collection<V> result = multimap().asMap().get(sampleKeys().e0);
result.clear();
assertGet(sampleKeys().e0);
ASSERT.that(result).isEmpty();
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
public void testAddNullValue() {
Collection<V> result = multimap().asMap().get(sampleKeys().e0);
assertTrue(result.add(null));
assertTrue(multimap().containsEntry(sampleKeys().e0, null));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUE_QUERIES})
public void testRemoveNullValue() {
Collection<V> result = multimap().asMap().get(sampleKeys().e0);
assertFalse(result.remove(null));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
public void testAddNullValueUnsupported() {
Collection<V> result = multimap().asMap().get(sampleKeys().e0);
try {
result.add(null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {}
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_PUT)
public void testPropagatesAddToMultimap() {
Collection<V> result = multimap().asMap().get(sampleKeys().e0);
result.add(sampleValues().e3);
ASSERT.that(multimap().get(sampleKeys().e0))
.has().exactly(sampleValues().e0, sampleValues().e3);
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({ SUPPORTS_REMOVE, SUPPORTS_PUT })
public void testPropagatesRemoveThenAddToMultimap() {
int oldSize = getNumElements();
K k0 = sampleKeys().e0;
V v0 = sampleValues().e0;
Collection<V> result = multimap().asMap().get(k0);
assertTrue(result.remove(v0));
assertFalse(multimap().containsKey(k0));
assertFalse(multimap().containsEntry(k0, v0));
ASSERT.that(result).isEmpty();
V v1 = sampleValues().e1;
V v2 = sampleValues().e2;
assertTrue(result.add(v1));
assertTrue(result.add(v2));
ASSERT.that(result).has().exactly(v1, v2);
ASSERT.that(multimap().get(k0)).has().exactly(v1, v2);
assertTrue(multimap().containsKey(k0));
assertFalse(multimap().containsEntry(k0, v0));
assertTrue(multimap().containsEntry(k0, v2));
assertEquals(oldSize + 1, multimap().size());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testReflectsMultimapRemove() {
Collection<V> result = multimap().asMap().get(sampleKeys().e0);
multimap().removeAll(sampleKeys().e0);
ASSERT.that(result).isEmpty();
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapAsMapGetTester.java | Java | asf20 | 5,322 |
/*
* 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.collect.SetMultimap;
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.SetTestSuiteBuilder;
import com.google.common.collect.testing.TestSetGenerator;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.Feature;
import junit.framework.TestSuite;
import java.util.Collections;
import java.util.EnumSet;
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 SetMultimap} implementation.
*
* @author Louis Wasserman
*/
public class SetMultimapTestSuiteBuilder<K, V>
extends MultimapTestSuiteBuilder<K, V, SetMultimap<K, V>> {
public static <K, V> SetMultimapTestSuiteBuilder<K, V> using(
TestSetMultimapGenerator<K, V> generator) {
SetMultimapTestSuiteBuilder<K, V> result = new SetMultimapTestSuiteBuilder<K, V>();
result.usingGenerator(generator);
return result;
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters());
testers.add(SetMultimapAsMapTester.class);
testers.add(SetMultimapEqualsTester.class);
testers.add(SetMultimapPutTester.class);
testers.add(SetMultimapPutAllTester.class);
testers.add(SetMultimapReplaceValuesTester.class);
return testers;
}
@Override
TestSuite computeMultimapGetTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<SetMultimap<K, V>, Entry<K, V>>> parentBuilder) {
return SetTestSuiteBuilder.using(
new MultimapGetGenerator<K, V>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeMultimapGetFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".get[key]")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
@Override
TestSuite computeMultimapAsMapGetTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<SetMultimap<K, V>, Entry<K, V>>> parentBuilder) {
Set<Feature<?>> features = computeMultimapAsMapGetFeatures(parentBuilder.getFeatures());
if (Collections.disjoint(features, EnumSet.allOf(CollectionSize.class))) {
return new TestSuite();
} else {
return SetTestSuiteBuilder.using(
new MultimapAsMapGetGenerator<K, V>(parentBuilder.getSubjectGenerator()))
.withFeatures(features)
.named(parentBuilder.getName() + ".asMap[].get[key]")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
}
@Override
TestSuite computeEntriesTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<SetMultimap<K, V>, Map.Entry<K, V>>> parentBuilder) {
return SetTestSuiteBuilder.using(
new EntriesGenerator<K, V>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeEntriesFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".entries")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
private static class EntriesGenerator<K, V>
extends MultimapTestSuiteBuilder.EntriesGenerator<K, V, SetMultimap<K, V>>
implements TestSetGenerator<Entry<K, V>> {
public EntriesGenerator(
OneSizeTestContainerGenerator<SetMultimap<K, V>, Entry<K, V>> multimapGenerator) {
super(multimapGenerator);
}
@Override
public Set<Entry<K, V>> create(Object... elements) {
return (Set<Entry<K, V>>) super.create(elements);
}
}
static class MultimapGetGenerator<K, V>
extends MultimapTestSuiteBuilder.MultimapGetGenerator<K, V, SetMultimap<K, V>>
implements TestSetGenerator<V> {
public MultimapGetGenerator(
OneSizeTestContainerGenerator<SetMultimap<K, V>, Entry<K, V>> multimapGenerator) {
super(multimapGenerator);
}
@Override
public Set<V> create(Object... elements) {
return (Set<V>) super.create(elements);
}
}
static class MultimapAsMapGetGenerator<K, V>
extends MultimapTestSuiteBuilder.MultimapAsMapGetGenerator<K, V, SetMultimap<K, V>>
implements TestSetGenerator<V> {
public MultimapAsMapGetGenerator(
OneSizeTestContainerGenerator<SetMultimap<K, V>, Entry<K, V>> multimapGenerator) {
super(multimapGenerator);
}
@Override
public Set<V> create(Object... elements) {
return (Set<V>) super.create(elements);
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/SetMultimapTestSuiteBuilder.java | Java | asf20 | 5,524 |
/*
* 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());
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/UnmodifiableCollectionTests.java | Java | asf20 | 14,422 |
/*
* 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.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.Maps;
import java.util.Map;
import java.util.Map.Entry;
/**
* 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 ImmutableBiMapGenerator extends TestStringBiMapGenerator {
@Override protected BiMap<String, String> create(Entry<String, String>[] entries) {
ImmutableBiMap.Builder<String, String> builder = ImmutableBiMap.builder();
for (Entry<String, String> entry : entries) {
builder.put(entry.getKey(), entry.getValue());
}
return builder.build();
}
}
public static class ImmutableBiMapCopyOfGenerator extends TestStringBiMapGenerator {
@Override protected BiMap<String, String> create(Entry<String, String>[] entries) {
Map<String, String> builder = Maps.newLinkedHashMap();
for (Entry<String, String> entry : entries) {
builder.put(entry.getKey(), entry.getValue());
}
return ImmutableBiMap.copyOf(builder);
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/BiMapGenerators.java | Java | asf20 | 1,898 |
/*
* 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.DerivedGenerator;
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.TestMapGenerator;
import com.google.common.collect.testing.TestSetGenerator;
import com.google.common.collect.testing.TestSubjectGenerator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Derived suite generators for Guava collection interfaces, split out of the suite builders so that
* they are available to GWT.
*
* @author Louis Wasserman
*/
@GwtCompatible
public final class DerivedGoogleCollectionGenerators {
public static class MapGenerator<K, V> implements TestMapGenerator<K, V>, DerivedGenerator {
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];
}
public TestSubjectGenerator<?> getInnerGenerator() {
return generator;
}
}
public static class InverseBiMapGenerator<K, V>
implements TestBiMapGenerator<V, K>, DerivedGenerator {
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];
}
public TestSubjectGenerator<?> getInnerGenerator() {
return generator;
}
}
public static class BiMapValueSetGenerator<K, V>
implements TestSetGenerator<V>, DerivedGenerator {
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;
}
public TestSubjectGenerator<?> getInnerGenerator() {
return mapGenerator;
}
}
private DerivedGoogleCollectionGenerators() {}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/DerivedGoogleCollectionGenerators.java | Java | asf20 | 6,577 |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.IteratorFeature;
import com.google.common.collect.testing.IteratorTester;
import com.google.common.collect.testing.features.CollectionFeature;
import java.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(emulated = true)
public class MultisetIteratorTester<E> extends AbstractMultisetTester<E> {
@SuppressWarnings("unchecked")
@CollectionFeature.Require({SUPPORTS_ITERATOR_REMOVE, KNOWN_ORDER})
public void testRemovingIteratorKnownOrder() {
new IteratorTester<E>(4, IteratorFeature.MODIFIABLE, getSubjectGenerator().order(
Arrays.asList(samples.e0, samples.e1, samples.e1, samples.e2)),
IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(value = SUPPORTS_ITERATOR_REMOVE, absent = KNOWN_ORDER)
public void testRemovingIteratorUnknownOrder() {
new IteratorTester<E>(4, IteratorFeature.MODIFIABLE, Arrays.asList(samples.e0, samples.e1,
samples.e1, samples.e2), IteratorTester.KnownOrder.UNKNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(value = KNOWN_ORDER, absent = SUPPORTS_ITERATOR_REMOVE)
public void testIteratorKnownOrder() {
new IteratorTester<E>(4, IteratorFeature.UNMODIFIABLE, getSubjectGenerator().order(
Arrays.asList(samples.e0, samples.e1, samples.e1, samples.e2)),
IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(absent = {SUPPORTS_ITERATOR_REMOVE, KNOWN_ORDER})
public void testIteratorUnknownOrder() {
new IteratorTester<E>(4, IteratorFeature.UNMODIFIABLE, Arrays.asList(samples.e0, samples.e1,
samples.e1, samples.e2), IteratorTester.KnownOrder.UNKNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
/**
* Returns {@link Method} instances for the tests that assume multisets support duplicates so that
* the test of {@code Multisets.forSet()} can suppress them.
*/
@GwtIncompatible("reflection")
public static List<Method> getIteratorDuplicateInitializingMethods() {
return Arrays.asList(
Helpers.getMethod(MultisetIteratorTester.class, "testIteratorKnownOrder"),
Helpers.getMethod(MultisetIteratorTester.class, "testIteratorUnknownOrder"),
Helpers.getMethod(MultisetIteratorTester.class, "testRemovingIteratorKnownOrder"),
Helpers.getMethod(MultisetIteratorTester.class, "testRemovingIteratorUnknownOrder"));
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultisetIteratorTester.java | Java | asf20 | 4,486 |
/*
* 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.Helpers.assertContentsAnyOrder;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEY_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collection;
import java.util.Collections;
/**
* Tests for {@link Multimap#get(Object)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapGetTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
public void testGetEmpty() {
Collection<V> result = multimap().get(sampleKeys().e3);
assertTrue(result.isEmpty());
assertEquals(0, result.size());
}
@CollectionSize.Require(absent = ZERO)
public void testGetNonEmpty() {
Collection<V> result = multimap().get(sampleKeys().e0);
assertFalse(result.isEmpty());
assertContentsAnyOrder(result, sampleValues().e0);
}
@CollectionSize.Require(SEVERAL)
public void testGetMultiple() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e1),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e2));
assertGet(sampleKeys().e0,
sampleValues().e0,
sampleValues().e1,
sampleValues().e2);
}
public void testGetAbsentKey() {
assertGet(sampleKeys().e4);
}
@CollectionSize.Require(SEVERAL)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testPropagatesRemoveToMultimap() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e2));
Collection<V> result = multimap().get(sampleKeys().e0);
assertTrue(result.remove(sampleValues().e0));
assertFalse(multimap().containsEntry(sampleKeys().e0, sampleValues().e0));
assertEquals(2, multimap().size());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testPropagatesRemoveLastElementToMultimap() {
Collection<V> result = multimap().get(sampleKeys().e0);
assertTrue(result.remove(sampleValues().e0));
assertGet(sampleKeys().e0);
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPropagatesAddToMultimap() {
Collection<V> result = multimap().get(sampleKeys().e0);
assertTrue(result.add(sampleValues().e3));
assertTrue(multimap().containsKey(sampleKeys().e0));
assertEquals(getNumElements() + 1, multimap().size());
assertTrue(multimap().containsEntry(sampleKeys().e0, sampleValues().e3));
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPropagatesAddAllToMultimap() {
Collection<V> result = multimap().get(sampleKeys().e0);
assertTrue(result.addAll(Collections.singletonList(sampleValues().e3)));
assertTrue(multimap().containsKey(sampleKeys().e0));
assertEquals(getNumElements() + 1, multimap().size());
assertTrue(multimap().containsEntry(sampleKeys().e0, sampleValues().e3));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({ SUPPORTS_REMOVE, SUPPORTS_PUT })
public void testPropagatesRemoveLastThenAddToMultimap() {
int oldSize = getNumElements();
K k0 = sampleKeys().e0;
V v0 = sampleValues().e0;
Collection<V> result = multimap().get(k0);
assertTrue(result.remove(v0));
assertFalse(multimap().containsKey(k0));
assertFalse(multimap().containsEntry(k0, v0));
ASSERT.that(result).isEmpty();
V v1 = sampleValues().e1;
V v2 = sampleValues().e2;
assertTrue(result.add(v1));
assertTrue(result.add(v2));
ASSERT.that(result).has().exactly(v1, v2);
ASSERT.that(multimap().get(k0)).has().exactly(v1, v2);
assertTrue(multimap().containsKey(k0));
assertFalse(multimap().containsEntry(k0, v0));
assertTrue(multimap().containsEntry(k0, v2));
assertEquals(oldSize + 1, multimap().size());
}
@MapFeature.Require(ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testGetNullPresent() {
initMultimapWithNullKey();
ASSERT.that(multimap().get(null)).has().item(getValueForNullKey());
}
@MapFeature.Require(ALLOWS_NULL_KEY_QUERIES)
public void testGetNullAbsent() {
ASSERT.that(multimap().get(null)).isEmpty();
}
@MapFeature.Require(absent = ALLOWS_NULL_KEY_QUERIES)
public void testGetNullForbidden() {
try {
multimap().get(null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
}
@MapFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testGetWithNullValue() {
initMultimapWithNullValue();
ASSERT.that(multimap().get(getKeyForNullValue()))
.has().item(null);
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapGetTester.java | Java | asf20 | 6,175 |
/*
* 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);
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/TestMultisetGenerator.java | Java | asf20 | 1,062 |
/*
* 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.Helpers.copyToList;
import static com.google.common.collect.testing.Helpers.copyToSet;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
/**
* Tests for {@link SetMultimap#replaceValues}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class SetMultimapPutTester<K, V>
extends AbstractMultimapTester<K, V, SetMultimap<K, V>> {
// Tests for non-duplicate values are in MultimapPutTester
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPutDuplicateValuePreservesSize() {
assertFalse(multimap().put(sampleKeys().e0, sampleValues().e0));
assertEquals(getNumElements(), multimap().size());
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutDuplicateValue() {
List<Entry<K, V>> entries = copyToList(multimap().entries());
for (Entry<K, V> entry : entries) {
resetContainer();
K k = entry.getKey();
V v = entry.getValue();
Set<V> values = multimap().get(k);
Set<V> expectedValues = copyToSet(values);
assertFalse(multimap().put(k, v));
assertEquals(expectedValues, values);
assertGet(k, expectedValues);
}
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testPutDuplicateValue_null() {
initMultimapWithNullValue();
assertFalse(multimap().put(getKeyForNullValue(), null));
expectContents(createArrayWithNullValue());
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/SetMultimapPutTester.java | Java | asf20 | 2,637 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEY_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
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.MapFeature;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
/**
* Tests for {@link Multimap#asMap}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapAsMapTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
public void testAsMapGet() {
for (K key : sampleKeys()) {
List<V> expectedValues = new ArrayList<V>();
for (Entry<K, V> entry : getSampleElements()) {
if (entry.getKey().equals(key)) {
expectedValues.add(entry.getValue());
}
}
Collection<V> collection = multimap().asMap().get(key);
if (expectedValues.isEmpty()) {
ASSERT.that(collection).isNull();
} else {
ASSERT.that(collection).has().exactlyAs(expectedValues);
}
}
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_KEYS)
public void testAsMapGetNullKeyPresent() {
initMultimapWithNullKey();
ASSERT.that(multimap().asMap().get(null)).has().exactly(getValueForNullKey());
}
@MapFeature.Require(ALLOWS_NULL_KEY_QUERIES)
public void testAsMapGetNullKeyAbsent() {
ASSERT.that(multimap().asMap().get(null)).isNull();
}
@MapFeature.Require(absent = ALLOWS_NULL_KEY_QUERIES)
public void testAsMapGetNullKeyUnsupported() {
try {
multimap().asMap().get(null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {}
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testAsMapRemove() {
ASSERT.that(multimap().asMap().remove(sampleKeys().e0)).iteratesAs(sampleValues().e0);
assertGet(sampleKeys().e0);
assertEquals(getNumElements() - 1, multimap().size());
}
@CollectionSize.Require(SEVERAL)
@MapFeature.Require(SUPPORTS_PUT)
public void testAsMapEntrySetReflectsPutSameKey() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3));
Set<Entry<K, Collection<V>>> asMapEntrySet = multimap().asMap().entrySet();
Collection<V> valueCollection = Iterables.getOnlyElement(asMapEntrySet).getValue();
ASSERT.that(valueCollection)
.has().exactly(sampleValues().e0, sampleValues().e3);
assertTrue(multimap().put(sampleKeys().e0, sampleValues().e4));
ASSERT.that(valueCollection)
.has().exactly(sampleValues().e0, sampleValues().e3, sampleValues().e4);
}
@CollectionSize.Require(SEVERAL)
@MapFeature.Require(SUPPORTS_PUT)
public void testAsMapEntrySetReflectsPutDifferentKey() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3));
Set<Entry<K, Collection<V>>> asMapEntrySet = multimap().asMap().entrySet();
assertTrue(multimap().put(sampleKeys().e1, sampleValues().e4));
assertEquals(2, asMapEntrySet.size());
}
@CollectionSize.Require(SEVERAL)
@MapFeature.Require({SUPPORTS_PUT, SUPPORTS_REMOVE})
public void testAsMapEntrySetRemovePropagatesToMultimap() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3));
Set<Entry<K, Collection<V>>> asMapEntrySet = multimap().asMap().entrySet();
Entry<K, Collection<V>> asMapEntry0 = Iterables.getOnlyElement(asMapEntrySet);
assertTrue(multimap().put(sampleKeys().e1, sampleValues().e4));
assertTrue(asMapEntrySet.remove(asMapEntry0));
assertEquals(1, multimap().size());
ASSERT.that(multimap().keySet()).iteratesAs(sampleKeys().e1);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE)
public void testAsMapEntrySetIteratorRemovePropagatesToMultimap() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3));
Set<Entry<K, Collection<V>>> asMapEntrySet = multimap().asMap().entrySet();
Iterator<Entry<K, Collection<V>>> asMapEntryItr = asMapEntrySet.iterator();
asMapEntryItr.next();
asMapEntryItr.remove();
assertTrue(multimap().isEmpty());
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapAsMapTester.java | Java | asf20 | 5,946 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_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.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEY_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;
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.MapFeature;
import java.util.Iterator;
/**
* Tester for {@code Multimap.entries}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapKeysTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@CollectionSize.Require(SEVERAL)
public void testKeys() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e1),
Helpers.mapEntry(sampleKeys().e1, sampleValues().e0));
Multiset<K> keys = multimap().keys();
assertEquals(2, keys.count(sampleKeys().e0));
assertEquals(1, keys.count(sampleKeys().e1));
assertEquals(3, keys.size());
ASSERT.that(keys).has().allOf(sampleKeys().e0, sampleKeys().e1);
ASSERT.that(keys.entrySet()).has().allOf(
Multisets.immutableEntry(sampleKeys().e0, 2),
Multisets.immutableEntry(sampleKeys().e1, 1));
}
@MapFeature.Require(ALLOWS_NULL_KEY_QUERIES)
public void testKeysCountAbsentNullKey() {
assertEquals(0, multimap().keys().count(null));
}
@CollectionSize.Require(SEVERAL)
@MapFeature.Require(ALLOWS_NULL_KEYS)
public void testKeysWithNullKey() {
resetContainer(
Helpers.mapEntry((K) null, sampleValues().e0),
Helpers.mapEntry((K) null, sampleValues().e1),
Helpers.mapEntry(sampleKeys().e1, sampleValues().e0));
Multiset<K> keys = multimap().keys();
assertEquals(2, keys.count(null));
assertEquals(1, keys.count(sampleKeys().e1));
assertEquals(3, keys.size());
ASSERT.that(keys).has().allOf(null, sampleKeys().e1);
ASSERT.that(keys.entrySet()).has().allOf(
Multisets.immutableEntry((K) null, 2),
Multisets.immutableEntry(sampleKeys().e1, 1));
}
public void testKeysElementSet() {
assertEquals(multimap().keySet(), multimap().keys().elementSet());
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testKeysRemove() {
int original = multimap().keys().remove(sampleKeys().e0, 1);
assertEquals(Math.max(original - 1, 0), multimap().get(sampleKeys().e0).size());
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE)
public void testKeysEntrySetIteratorRemove() {
Multiset<K> keys = multimap().keys();
Iterator<Multiset.Entry<K>> itr = keys.entrySet().iterator();
assertEquals(Multisets.immutableEntry(sampleKeys().e0, 1),
itr.next());
itr.remove();
assertTrue(multimap().isEmpty());
}
@CollectionSize.Require(SEVERAL)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testKeysEntrySetRemove() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e1),
Helpers.mapEntry(sampleKeys().e1, sampleValues().e0));
assertTrue(multimap().keys().entrySet().remove(
Multisets.immutableEntry(sampleKeys().e0, 2)));
assertEquals(1, multimap().size());
assertTrue(multimap().containsEntry(sampleKeys().e1, sampleValues().e0));
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapKeysTester.java | Java | asf20 | 4,651 |
/*
* 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 org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.AbstractContainerTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.SampleElements;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* Superclass for all {@code Multimap} testers.
*
* @author Louis Wasserman
*/
@GwtCompatible
public abstract class AbstractMultimapTester<K, V, M extends Multimap<K, V>>
extends AbstractContainerTester<M, Map.Entry<K, V>> {
private M multimap;
protected M multimap() {
return multimap;
}
/**
* @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] = Helpers.mapEntry(null, oldEntry.getValue());
return array;
}
/**
* @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] = Helpers.mapEntry(oldEntry.getKey(), null);
return array;
}
/**
* @return an array of the proper size with {@code null} as the key and value of the
* middle element.
*/
protected Map.Entry<K, V>[] createArrayWithNullKeyAndValue() {
Map.Entry<K, V>[] array = createSamplesArray();
final int nullValueLocation = getNullLocation();
array[nullValueLocation] = Helpers.mapEntry(null, null);
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();
}
protected void initMultimapWithNullKey() {
resetContainer(getSubjectGenerator().create(createArrayWithNullKey()));
}
protected void initMultimapWithNullValue() {
resetContainer(getSubjectGenerator().create(createArrayWithNullValue()));
}
protected void initMultimapWithNullKeyAndValue() {
resetContainer(getSubjectGenerator().create(createArrayWithNullKeyAndValue()));
}
protected SampleElements<K> sampleKeys() {
return ((TestMultimapGenerator<K, V, ? extends Multimap<K, V>>) getSubjectGenerator()
.getInnerGenerator()).sampleKeys();
}
protected SampleElements<V> sampleValues() {
return ((TestMultimapGenerator<K, V, ? extends Multimap<K, V>>) getSubjectGenerator()
.getInnerGenerator()).sampleValues();
}
@Override
protected Collection<Entry<K, V>> actualContents() {
return multimap.entries();
}
// TODO: dispose of this once collection is encapsulated.
@Override
protected M resetContainer(M newContents) {
multimap = super.resetContainer(newContents);
return multimap;
}
protected Multimap<K, V> resetContainer(Entry<K, V>... newContents) {
multimap = super.resetContainer(getSubjectGenerator().create(newContents));
return multimap;
}
/** @see AbstractContainerTester#resetContainer() */
protected void resetCollection() {
resetContainer();
}
protected void assertGet(K key, V... values) {
assertGet(key, Arrays.asList(values));
}
protected void assertGet(K key, Collection<V> values) {
ASSERT.that(multimap().get(key)).has().exactlyAs(values);
if (!values.isEmpty()) {
ASSERT.that(multimap().asMap().get(key)).has().exactlyAs(values);
assertFalse(multimap().isEmpty());
} else {
ASSERT.that(multimap().asMap().get(key)).isNull();
}
// TODO(user): Add proper overrides to prevent autoboxing.
// Truth+autoboxing == compile error. Cast int to long to fix:
ASSERT.that(multimap().get(key).size()).is((long) values.size());
assertEquals(values.size() > 0, multimap().containsKey(key));
assertEquals(values.size() > 0, multimap().keySet().contains(key));
assertEquals(values.size() > 0, multimap().keys().contains(key));
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/AbstractMultimapTester.java | Java | asf20 | 5,260 |
/*
* 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.Helpers.copyToList;
import static com.google.common.collect.testing.Helpers.mapEntry;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* Testers for {@link ListMultimap#remove(Object, Object)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class ListMultimapRemoveTester<K, V> extends AbstractListMultimapTester<K, V> {
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testMultimapRemoveDeletesFirstOccurrence() {
K k = sampleKeys().e0;
V v0 = sampleValues().e0;
V v1 = sampleValues().e2;
resetContainer(mapEntry(k, v0), mapEntry(k, v1), mapEntry(k, v0));
List<V> list = multimap().get(k);
multimap().remove(k, v0);
ASSERT.that(list).has().exactly(v1, v0).inOrder();
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testRemoveAtIndexFromGetPropagates() {
K k = sampleKeys().e0;
V v0 = sampleValues().e0;
V v1 = sampleValues().e2;
List<V> values = Arrays.asList(v0, v1, v0);
for (int i = 0; i < 3; i++) {
resetContainer(mapEntry(k, v0), mapEntry(k, v1), mapEntry(k, v0));
List<V> expectedValues = copyToList(values);
multimap().get(k).remove(i);
expectedValues.remove(i);
assertGet(k, expectedValues);
}
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testRemoveAtIndexFromAsMapPropagates() {
K k = sampleKeys().e0;
V v0 = sampleValues().e0;
V v1 = sampleValues().e2;
List<V> values = Arrays.asList(v0, v1, v0);
for (int i = 0; i < 3; i++) {
resetContainer(mapEntry(k, v0), mapEntry(k, v1), mapEntry(k, v0));
List<V> expectedValues = copyToList(values);
List<V> asMapValue = (List<V>) multimap().asMap().get(k);
asMapValue.remove(i);
expectedValues.remove(i);
assertGet(k, expectedValues);
}
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testRemoveAtIndexFromAsMapEntrySetPropagates() {
K k = sampleKeys().e0;
V v0 = sampleValues().e0;
V v1 = sampleValues().e2;
List<V> values = Arrays.asList(v0, v1, v0);
for (int i = 0; i < 3; i++) {
resetContainer(mapEntry(k, v0), mapEntry(k, v1), mapEntry(k, v0));
List<V> expectedValues = copyToList(values);
Map.Entry<K, Collection<V>> asMapEntry = multimap().asMap().entrySet().iterator().next();
List<V> asMapValue = (List<V>) asMapEntry.getValue();
asMapValue.remove(i);
expectedValues.remove(i);
assertGet(k, expectedValues);
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/ListMultimapRemoveTester.java | Java | asf20 | 3,897 |
/*
* 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_PUT;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Arrays;
import java.util.List;
/**
* Tests for {@link SetMultimap#replaceValues}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class SetMultimapReplaceValuesTester<K, V>
extends AbstractMultimapTester<K, V, SetMultimap<K, V>> {
@MapFeature.Require({SUPPORTS_PUT, SUPPORTS_REMOVE})
public void testReplaceValuesHandlesDuplicates() {
V v0 = sampleValues().e3;
V v1 = sampleValues().e2;
@SuppressWarnings("unchecked")
List<V> values = Arrays.asList(v0, v1, v0);
for (K k : sampleKeys()) {
resetContainer();
multimap().replaceValues(k, values);
assertGet(k, v0, v1);
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/SetMultimapReplaceValuesTester.java | Java | asf20 | 1,629 |
/*
* 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.SetMultimap;
/**
* A generator for {@code SetMultimap} implementations based on test data.
*
* @author Louis Wasserman
*/
@GwtCompatible
public interface TestSetMultimapGenerator<K, V>
extends TestMultimapGenerator<K, V, SetMultimap<K, V>> {
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/TestSetMultimapGenerator.java | Java | asf20 | 992 |
/*
* 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.Lists;
import com.google.common.collect.testing.TestCharacterListGenerator;
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 com.google.common.primitives.Chars;
import java.util.Arrays;
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) {
ImmutableList.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);
}
}
public static class CharactersOfStringGenerator
extends TestCharacterListGenerator {
@Override public List<Character> create(Character[] elements) {
char[] chars = Chars.toArray(Arrays.asList(elements));
return Lists.charactersOf(String.copyValueOf(chars));
}
}
public static class CharactersOfCharSequenceGenerator
extends TestCharacterListGenerator {
@Override public List<Character> create(Character[] elements) {
char[] chars = Chars.toArray(Arrays.asList(elements));
StringBuilder str = new StringBuilder();
str.append(chars);
return Lists.charactersOf(str);
}
}
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);
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/ListGenerators.java | Java | asf20 | 5,157 |
/*
* 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.SUPPORTS_ITERATOR_REMOVE;
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.CollectionFeature;
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);
}
@CollectionFeature.Require(SUPPORTS_ITERATOR_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());
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/BiMapRemoveTester.java | Java | asf20 | 3,329 |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newTreeSet;
import static com.google.common.collect.testing.SampleElements.Strings.AFTER_LAST;
import static com.google.common.collect.testing.SampleElements.Strings.AFTER_LAST_2;
import static com.google.common.collect.testing.SampleElements.Strings.BEFORE_FIRST;
import static com.google.common.collect.testing.SampleElements.Strings.BEFORE_FIRST_2;
import static junit.framework.Assert.assertEquals;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.collect.testing.TestCollectionGenerator;
import com.google.common.collect.testing.TestCollidingSetGenerator;
import com.google.common.collect.testing.TestIntegerSortedSetGenerator;
import com.google.common.collect.testing.TestSetGenerator;
import com.google.common.collect.testing.TestStringListGenerator;
import com.google.common.collect.testing.TestStringSetGenerator;
import com.google.common.collect.testing.TestStringSortedSetGenerator;
import com.google.common.collect.testing.TestUnhashableCollectionGenerator;
import com.google.common.collect.testing.UnhashableObject;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
/**
* Generators of different types of sets and derived collections from sets.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @author Hayward Chan
*/
@GwtCompatible(emulated = true)
public class SetGenerators {
public static class ImmutableSetCopyOfGenerator extends TestStringSetGenerator {
@Override protected Set<String> create(String[] elements) {
return ImmutableSet.copyOf(elements);
}
}
public static class ImmutableSetWithBadHashesGenerator
extends TestCollidingSetGenerator
// Work around a GWT compiler bug. Not explicitly listing this will
// cause the createArray() method missing in the generated javascript.
// TODO: Remove this once the GWT bug is fixed.
implements TestCollectionGenerator<Object> {
@Override
public Set<Object> create(Object... elements) {
return ImmutableSet.copyOf(elements);
}
}
public static class DegeneratedImmutableSetGenerator
extends TestStringSetGenerator {
// Make sure we get what we think we're getting, or else this test
// is pointless
@SuppressWarnings("cast")
@Override protected Set<String> create(String[] elements) {
return (ImmutableSet<String>)
ImmutableSet.of(elements[0], elements[0]);
}
}
public static class ImmutableSortedSetCopyOfGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
return ImmutableSortedSet.copyOf(elements);
}
}
public static class ImmutableSortedSetHeadsetGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
List<String> list = Lists.newArrayList(elements);
list.add("zzz");
return ImmutableSortedSet.copyOf(list)
.headSet("zzy");
}
}
public static class ImmutableSortedSetTailsetGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
List<String> list = Lists.newArrayList(elements);
list.add("\0");
return ImmutableSortedSet.copyOf(list)
.tailSet("\0\0");
}
}
public static class ImmutableSortedSetSubsetGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
List<String> list = Lists.newArrayList(elements);
list.add("\0");
list.add("zzz");
return ImmutableSortedSet.copyOf(list)
.subSet("\0\0", "zzy");
}
}
@GwtIncompatible("NavigableSet")
public static class ImmutableSortedSetDescendingGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
return ImmutableSortedSet
.<String>reverseOrder()
.add(elements)
.build()
.descendingSet();
}
}
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();
}
}
@GwtIncompatible("NavigableSet")
public static class ImmutableSortedSetDescendingAsListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements).reverse();
return ImmutableSortedSet
.orderedBy(comparator)
.add(elements)
.build()
.descendingSet()
.asList();
}
}
public static class ImmutableSortedSetAsListSubListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSortedSet.Builder<String> builder
= ImmutableSortedSet.orderedBy(comparator);
builder.add(BEFORE_FIRST);
builder.add(elements);
builder.add(AFTER_LAST);
return builder.build().asList().subList(1, elements.length + 1);
}
}
public static class ImmutableSortedSetSubsetAsListSubListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSortedSet.Builder<String> builder
= ImmutableSortedSet.orderedBy(comparator);
builder.add(BEFORE_FIRST);
builder.add(BEFORE_FIRST_2);
builder.add(elements);
builder.add(AFTER_LAST);
builder.add(AFTER_LAST_2);
return builder.build().subSet(BEFORE_FIRST_2,
AFTER_LAST_2)
.asList().subList(1, elements.length + 1);
}
}
public abstract static class TestUnhashableSetGenerator
extends TestUnhashableCollectionGenerator<Set<UnhashableObject>>
implements TestSetGenerator<UnhashableObject> {
}
private static Ordering<String> createExplicitComparator(
String[] elements) {
// Collapse equal elements, which Ordering.explicit() doesn't support, while
// maintaining the ordering by first occurrence.
Set<String> elementsPlus = Sets.newLinkedHashSet();
elementsPlus.add(BEFORE_FIRST);
elementsPlus.add(BEFORE_FIRST_2);
elementsPlus.addAll(Arrays.asList(elements));
elementsPlus.add(AFTER_LAST);
elementsPlus.add(AFTER_LAST_2);
return Ordering.explicit(Lists.newArrayList(elementsPlus));
}
/*
* All the ContiguousSet generators below manually reject nulls here. In principle, we'd like to
* defer that to Range, since it's ContiguousSet.create() that's used to create the sets. However,
* that gets messy here, and we already have null tests for Range.
*/
/*
* These generators also rely on consecutive integer inputs (not necessarily in order, but no
* holes).
*/
// SetCreationTester has some tests that pass in duplicates. Dedup them.
private static <E extends Comparable<? super E>> SortedSet<E> nullCheckedTreeSet(E[] elements) {
SortedSet<E> set = newTreeSet();
for (E element : elements) {
// Explicit null check because TreeSet wrongly accepts add(null) when empty.
set.add(checkNotNull(element));
}
return set;
}
public static class ContiguousSetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
return checkedCreate(nullCheckedTreeSet(elements));
}
}
public static class ContiguousSetHeadsetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
SortedSet<Integer> set = nullCheckedTreeSet(elements);
int tooHigh = (set.isEmpty()) ? 0 : set.last() + 1;
set.add(tooHigh);
return checkedCreate(set).headSet(tooHigh);
}
}
public static class ContiguousSetTailsetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
SortedSet<Integer> set = nullCheckedTreeSet(elements);
int tooLow = (set.isEmpty()) ? 0 : set.first() - 1;
set.add(tooLow);
return checkedCreate(set).tailSet(tooLow + 1);
}
}
public static class ContiguousSetSubsetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
SortedSet<Integer> set = nullCheckedTreeSet(elements);
if (set.isEmpty()) {
/*
* The (tooLow + 1, tooHigh) arguments below would be invalid because tooLow would be
* greater than tooHigh.
*/
return ContiguousSet.create(Range.openClosed(0, 1), DiscreteDomain.integers()).subSet(0, 1);
}
int tooHigh = set.last() + 1;
int tooLow = set.first() - 1;
set.add(tooHigh);
set.add(tooLow);
return checkedCreate(set).subSet(tooLow + 1, tooHigh);
}
}
@GwtIncompatible("NavigableSet")
public static class ContiguousSetDescendingGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
return checkedCreate(nullCheckedTreeSet(elements)).descendingSet();
}
/** Sorts the elements in reverse natural order. */
@Override public List<Integer> order(List<Integer> insertionOrder) {
Collections.sort(insertionOrder, Ordering.natural().reverse());
return insertionOrder;
}
}
private abstract static class AbstractContiguousSetGenerator
extends TestIntegerSortedSetGenerator {
protected final ContiguousSet<Integer> checkedCreate(SortedSet<Integer> elementsSet) {
List<Integer> elements = newArrayList(elementsSet);
/*
* A ContiguousSet can't have holes. If a test demands a hole, it should be changed so that it
* doesn't need one, or it should be suppressed for ContiguousSet.
*/
for (int i = 0; i < elements.size() - 1; i++) {
assertEquals(elements.get(i) + 1, (int) elements.get(i + 1));
}
Range<Integer> range =
(elements.isEmpty()) ? Range.closedOpen(0, 0) : Range.encloseAll(elements);
return ContiguousSet.create(range, DiscreteDomain.integers());
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/SetGenerators.java | Java | asf20 | 14,515 |
/*
* 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.Helpers.mapEntry;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.*;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collection;
import java.util.Map.Entry;
/**
* Tester for the {@code size} methods of {@code Multimap} and its views.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapSizeTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
public void testSize() {
int expectedSize = getNumElements();
Multimap<K, V> multimap = multimap();
assertEquals(expectedSize, multimap.size());
int size = 0;
for (Entry<K, V> entry : multimap.entries()) {
assertTrue(multimap.containsEntry(entry.getKey(), entry.getValue()));
size++;
}
assertEquals(expectedSize, size);
int size2 = 0;
for (Entry<K, Collection<V>> entry2 : multimap.asMap().entrySet()) {
size2 += entry2.getValue().size();
}
assertEquals(expectedSize, size2);
}
@CollectionSize.Require(ZERO)
public void testIsEmptyYes() {
assertTrue(multimap().isEmpty());
}
@CollectionSize.Require(absent = ZERO)
public void testIsEmptyNo() {
assertFalse(multimap().isEmpty());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_KEYS)
public void testSizeNullKey() {
initMultimapWithNullKey();
assertEquals(getNumElements(), multimap().size());
assertFalse(multimap().isEmpty());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_VALUES)
public void testSizeNullValue() {
initMultimapWithNullValue();
assertEquals(getNumElements(), multimap().size());
assertFalse(multimap().isEmpty());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES})
public void testSizeNullKeyAndValue() {
initMultimapWithNullKeyAndValue();
assertEquals(getNumElements(), multimap().size());
assertFalse(multimap().isEmpty());
}
@CollectionSize.Require(SEVERAL)
public void testSizeMultipleValues() {
resetContainer(
mapEntry(sampleKeys().e0, sampleValues().e0),
mapEntry(sampleKeys().e0, sampleValues().e1),
mapEntry(sampleKeys().e0, sampleValues().e2));
assertEquals(3, multimap().size());
assertEquals(3, multimap().entries().size());
assertEquals(3, multimap().keys().size());
assertEquals(1, multimap().keySet().size());
assertEquals(1, multimap().asMap().size());
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapSizeTester.java | Java | asf20 | 3,505 |
/*
* 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.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEY_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUE_QUERIES;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
/**
* Tester for {@link Multimap#containsEntry}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapContainsEntryTester<K, V>
extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@CollectionSize.Require(absent = ZERO)
public void testContainsEntryYes() {
assertTrue(multimap().containsEntry(sampleKeys().e0, sampleValues().e0));
}
public void testContainsEntryNo() {
assertFalse(multimap().containsEntry(sampleKeys().e3, sampleValues().e3));
}
public void testContainsEntryAgreesWithGet() {
for (K k : sampleKeys()) {
for (V v : sampleValues()) {
assertEquals(multimap().get(k).contains(v),
multimap().containsEntry(k, v));
}
}
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({ ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES })
public void testContainsEntryNullYes() {
initMultimapWithNullKeyAndValue();
assertTrue(multimap().containsEntry(null, null));
}
@MapFeature.Require({ ALLOWS_NULL_KEY_QUERIES, ALLOWS_NULL_VALUE_QUERIES })
public void testContainsEntryNullNo() {
assertFalse(multimap().containsEntry(null, null));
}
@MapFeature.Require(absent = ALLOWS_NULL_KEY_QUERIES)
public void testContainsEntryNullDisallowedBecauseKeyQueriesDisallowed() {
try {
multimap().containsEntry(null, sampleValues().e3);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
}
/**
* Copy of the {@link #testContainsEntryNullDisallowed} test. Needed because
* "optional" feature requirements are not supported.
*/
@MapFeature.Require(absent = ALLOWS_NULL_VALUE_QUERIES)
public void testContainsEntryNullDisallowedBecauseValueQueriesDisallowed() {
try {
multimap().containsEntry(sampleKeys().e3, null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultimapContainsEntryTester.java | Java | asf20 | 3,253 |
/*
* 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.collect.BiMap;
import com.google.common.collect.testing.AbstractTester;
import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder;
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.SetTestSuiteBuilder;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.features.MapFeature;
import com.google.common.collect.testing.google.DerivedGoogleCollectionGenerators.BiMapValueSetGenerator;
import com.google.common.collect.testing.google.DerivedGoogleCollectionGenerators.InverseBiMapGenerator;
import com.google.common.collect.testing.google.DerivedGoogleCollectionGenerators.MapGenerator;
import com.google.common.collect.testing.testers.SetCreationTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
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
*/
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())
.suppressing(SetCreationTester.class.getMethods())
// BiMap.entrySet() duplicate-handling behavior is too confusing for SetCreationTester
.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())
.suppressing(SetCreationTester.class.getMethods())
// BiMap.values() duplicate-handling behavior is too confusing for SetCreationTester
.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);
inverseFeatures.add(MapFeature.REJECTS_DUPLICATES_AT_CREATION);
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);
}
valuesCollectionFeatures.add(CollectionFeature.REJECTS_DUPLICATES_AT_CREATION);
return valuesCollectionFeatures;
}
private static Set<Feature<?>> computeCommonDerivedCollectionFeatures(
Set<Feature<?>> mapFeatures) {
return MapTestSuiteBuilder.computeCommonDerivedCollectionFeatures(mapFeatures);
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/BiMapTestSuiteBuilder.java | Java | asf20 | 6,459 |
/*
* 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.Helpers.copyToList;
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.ListMultimap;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.List;
import java.util.Map.Entry;
/**
* Testers for {@link ListMultimap#put(Object, Object)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class ListMultimapPutTester<K, V> extends AbstractListMultimapTester<K, V> {
// MultimapPutTester tests non-duplicate values, but ignores ordering
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAddsValueAtEnd() {
for (K key : sampleKeys()) {
for (V value : sampleValues()) {
resetContainer();
List<V> values = multimap().get(key);
List<V> expectedValues = Helpers.copyToList(values);
assertTrue(multimap().put(key, value));
expectedValues.add(value);
assertGet(key, expectedValues);
assertEquals(value, values.get(values.size() - 1));
}
}
}
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPutDuplicateValue() {
List<Entry<K, V>> entries = copyToList(multimap().entries());
for (Entry<K, V> entry : entries) {
resetContainer();
K k = entry.getKey();
V v = entry.getValue();
List<V> values = multimap().get(k);
List<V> expectedValues = copyToList(values);
assertTrue(multimap().put(k, v));
expectedValues.add(v);
assertGet(k, expectedValues);
assertEquals(v, values.get(values.size() - 1));
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/ListMultimapPutTester.java | Java | asf20 | 2,532 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.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 static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Collections;
import java.util.Set;
/**
* Tests for {@code Multiset.elementSet()} not covered by the derived {@code SetTestSuiteBuilder}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultisetElementSetTester<E> extends AbstractMultisetTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
public void testElementSetReflectsAddAbsent() {
Set<E> elementSet = getMultiset().elementSet();
assertFalse(elementSet.contains(samples.e3));
getMultiset().add(samples.e3, 4);
assertTrue(elementSet.contains(samples.e3));
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testElementSetReflectsRemove() {
Set<E> elementSet = getMultiset().elementSet();
assertTrue(elementSet.contains(samples.e0));
getMultiset().removeAll(Collections.singleton(samples.e0));
assertFalse(elementSet.contains(samples.e0));
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testElementSetRemovePropagatesToMultiset() {
Set<E> elementSet = getMultiset().elementSet();
assertTrue(elementSet.remove(samples.e0));
assertFalse(getMultiset().contains(samples.e0));
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testElementSetRemoveDuplicatePropagatesToMultiset() {
initThreeCopies();
Set<E> elementSet = getMultiset().elementSet();
assertTrue(elementSet.remove(samples.e0));
ASSERT.that(getMultiset()).isEmpty();
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testElementSetRemoveAbsent() {
Set<E> elementSet = getMultiset().elementSet();
assertFalse(elementSet.remove(samples.e3));
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testElementSetClear() {
getMultiset().elementSet().clear();
ASSERT.that(getMultiset()).isEmpty();
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultisetElementSetTester.java | Java | asf20 | 3,165 |
/*
* 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.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.features.CollectionSize;
/**
* 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> {
@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());
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultisetReadsTester.java | Java | asf20 | 3,916 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.features.TesterAnnotation;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
import java.util.Set;
/**
* Optional features of classes derived from {@link Multiset}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public enum MultisetFeature implements Feature<Multiset> {
/**
* Indicates that elements from {@code Multiset.entrySet()} update to reflect changes in the
* backing multiset.
*/
ENTRIES_ARE_VIEWS;
@Override
public Set<Feature<? super Multiset>> getImpliedFeatures() {
return Collections.emptySet();
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@TesterAnnotation
public @interface Require {
public abstract MultisetFeature[] value() default {};
public abstract MultisetFeature[] absent() default {};
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/MultisetFeature.java | Java | asf20 | 1,718 |
/*
* 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 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.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.SetTestSuiteBuilder;
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.Collection;
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
*/
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() {
withFeatures(CollectionFeature.KNOWN_ORDER);
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;
}
@Override
TestSuite createElementSetTestSuite(FeatureSpecificTestSuiteBuilder<
?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) {
// TODO(user): make a SortedElementSetGenerator
return SetTestSuiteBuilder
.using(new ElementSetGenerator<E>(parentBuilder.getSubjectGenerator()))
.named(getName() + ".elementSet")
.withFeatures(computeElementSetFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
/**
* 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);
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/google/SortedMultisetTestSuiteBuilder.java | Java | asf20 | 12,028 |
/*
* 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.annotations.GwtCompatible;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
/**
* A utility similar to {@link IteratorTester} for testing a
* {@link ListIterator} against a known good reference implementation. As with
* {@code IteratorTester}, a concrete subclass must provide target iterators on
* demand. It also requires three additional constructor parameters:
* {@code elementsToInsert}, the elements to be passed to {@code set()} and
* {@code add()} calls; {@code features}, the features supported by the
* iterator; and {@code expectedElements}, the elements the iterator should
* return in order.
* <p>
* The items in {@code elementsToInsert} will be repeated if {@code steps} is
* larger than the number of provided elements.
*
* @author Chris Povirk
*/
@GwtCompatible
public abstract class ListIteratorTester<E> extends
AbstractIteratorTester<E, ListIterator<E>> {
protected ListIteratorTester(int steps, Iterable<E> elementsToInsert,
Iterable<? extends IteratorFeature> features,
Iterable<E> expectedElements, int startIndex) {
super(steps, elementsToInsert, features, expectedElements,
KnownOrder.KNOWN_ORDER, startIndex);
}
@Override
protected final Iterable<? extends Stimulus<E, ? super ListIterator<E>>>
getStimulusValues() {
List<Stimulus<E, ? super ListIterator<E>>> list =
new ArrayList<Stimulus<E, ? super ListIterator<E>>>();
Helpers.addAll(list, iteratorStimuli());
Helpers.addAll(list, listIteratorStimuli());
return list;
}
@Override protected abstract ListIterator<E> newTargetIterator();
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/ListIteratorTester.java | Java | asf20 | 2,308 |
/*
* 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.annotations.GwtCompatible;
import com.google.common.collect.testing.SampleElements.Strings;
import java.util.List;
import java.util.Queue;
/**
* Create queue of strings for tests.
*
* @author Jared Levy
*/
@GwtCompatible
public abstract class TestStringQueueGenerator
implements TestQueueGenerator<String>
{
@Override
public SampleElements<String> samples() {
return new Strings();
}
@Override
public Queue<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 Queue<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;
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/TestStringQueueGenerator.java | Java | asf20 | 1,619 |
/*
* 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.annotations.GwtCompatible;
import java.util.Collections;
import java.util.Iterator;
/**
* A utility for testing an Iterator implementation by comparing its behavior to
* that of a "known good" reference implementation. In order to accomplish this,
* it's important to test a great variety of sequences of the
* {@link Iterator#next}, {@link Iterator#hasNext} and {@link Iterator#remove}
* operations. This utility takes the brute-force approach of trying <i>all</i>
* possible sequences of these operations, up to a given number of steps. So, if
* the caller specifies to use <i>n</i> steps, a total of <i>3^n</i> tests are
* actually performed.
*
* <p>For instance, if <i>steps</i> is 5, one example sequence that will be
* tested is:
*
* <ol>
* <li>remove();
* <li>hasNext()
* <li>hasNext();
* <li>remove();
* <li>next();
* </ol>
*
* <p>This particular order of operations may be unrealistic, and testing all 3^5
* of them may be thought of as overkill; however, it's difficult to determine
* which proper subset of this massive set would be sufficient to expose any
* possible bug. Brute force is simpler.
*
* <p>To use this class the concrete subclass must implement the
* {@link IteratorTester#newTargetIterator()} method. This is because it's
* impossible to test an Iterator without changing its state, so the tester
* needs a steady supply of fresh Iterators.
*
* <p>If your iterator supports modification through {@code remove()}, you may
* wish to override the verify() method, which is called <em>after</em>
* each sequence and is guaranteed to be called using the latest values
* obtained from {@link IteratorTester#newTargetIterator()}.
*
* @author Kevin Bourrillion
* @author Chris Povirk
*/
@GwtCompatible
public abstract class IteratorTester<E> extends
AbstractIteratorTester<E, Iterator<E>> {
/**
* Creates an IteratorTester.
*
* @param steps how many operations to test for each tested pair of iterators
* @param features the features supported by the iterator
*/
protected IteratorTester(int steps,
Iterable<? extends IteratorFeature> features,
Iterable<E> expectedElements, KnownOrder knownOrder) {
super(steps, Collections.<E>singleton(null), features, expectedElements,
knownOrder, 0);
}
@Override
protected final Iterable<Stimulus<E, Iterator<E>>> getStimulusValues() {
return iteratorStimuli();
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/IteratorTester.java | Java | asf20 | 3,094 |
/*
* 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 com.google.common.annotations.GwtCompatible;
/**
* Simple derived class to verify that we handle generics correctly.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public class DerivedComparable extends BaseComparable {
public DerivedComparable(String s) {
super(s);
}
private static final long serialVersionUID = 0;
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/DerivedComparable.java | Java | asf20 | 989 |
/*
* 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.disjoint;
import static java.util.logging.Level.FINER;
import com.google.common.collect.testing.features.ConflictingRequirementsException;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.features.FeatureUtil;
import com.google.common.collect.testing.features.TesterRequirements;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* the object generated by a G, selecting appropriate tests by matching them
* against specified features.
*
* @param <B> The concrete type of this builder (the 'self-type'). All the
* Builder methods of this class (such as {@link #named}) return this type, so
* that Builder methods of more derived classes can be chained onto them without
* casting.
* @param <G> The type of the generator to be passed to testers in the
* generated test suite. 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 abstract class FeatureSpecificTestSuiteBuilder<
B extends FeatureSpecificTestSuiteBuilder<B, G>, G> {
@SuppressWarnings("unchecked")
protected B self() {
return (B) this;
}
// Test Data
private G subjectGenerator;
// Gets run before every test.
private Runnable setUp;
// Gets run at the conclusion of every test.
private Runnable tearDown;
protected B usingGenerator(G subjectGenerator) {
this.subjectGenerator = subjectGenerator;
return self();
}
public G getSubjectGenerator() {
return subjectGenerator;
}
public B withSetUp(Runnable setUp) {
this.setUp = setUp;
return self();
}
protected Runnable getSetUp() {
return setUp;
}
public B withTearDown(Runnable tearDown) {
this.tearDown = tearDown;
return self();
}
protected Runnable getTearDown() {
return tearDown;
}
// Features
private Set<Feature<?>> features = new LinkedHashSet<Feature<?>>();
/**
* Configures this builder to produce tests appropriate for the given
* features. This method may be called more than once to add features
* in multiple groups.
*/
public B withFeatures(Feature<?>... features) {
return withFeatures(Arrays.asList(features));
}
public B withFeatures(Iterable<? extends Feature<?>> features) {
for (Feature<?> feature : features) {
this.features.add(feature);
}
return self();
}
public Set<Feature<?>> getFeatures() {
return Collections.unmodifiableSet(features);
}
// Name
private String name;
/** Configures this builder produce a TestSuite with the given name. */
public B named(String name) {
if (name.contains("(")) {
throw new IllegalArgumentException("Eclipse hides all characters after "
+ "'('; please use '[]' or other characters instead of parentheses");
}
this.name = name;
return self();
}
public String getName() {
return name;
}
// Test suppression
private Set<Method> suppressedTests = new HashSet<Method>();
/**
* Prevents the given methods from being run as part of the test suite.
*
* <em>Note:</em> in principle this should never need to be used, but it
* might be useful if the semantics of an implementation disagree in
* unforeseen ways with the semantics expected by a test, or to keep dependent
* builds clean in spite of an erroneous test.
*/
public B suppressing(Method... methods) {
return suppressing(Arrays.asList(methods));
}
public B suppressing(Collection<Method> methods) {
suppressedTests.addAll(methods);
return self();
}
public Set<Method> getSuppressedTests() {
return suppressedTests;
}
private static final Logger logger = Logger.getLogger(
FeatureSpecificTestSuiteBuilder.class.getName());
/**
* Creates a runnable JUnit test suite based on the criteria already given.
*/
/*
* Class parameters must be raw. This annotation should go on testerClass in
* the for loop, but the 1.5 javac crashes on annotations in for loops:
* <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6294589>
*/
@SuppressWarnings("unchecked")
public TestSuite createTestSuite() {
checkCanCreate();
logger.fine(" Testing: " + name);
logger.fine("Features: " + formatFeatureSet(features));
FeatureUtil.addImpliedFeatures(features);
logger.fine("Expanded: " + formatFeatureSet(features));
// Class parameters must be raw.
List<Class<? extends AbstractTester>> testers = getTesters();
TestSuite suite = new TestSuite(name);
for (Class<? extends AbstractTester> testerClass : testers) {
final TestSuite testerSuite = makeSuiteForTesterClass(
(Class<? extends AbstractTester<?>>) testerClass);
if (testerSuite.countTestCases() > 0) {
suite.addTest(testerSuite);
}
}
return suite;
}
/**
* Throw {@link IllegalStateException} if {@link #createTestSuite()} can't
* be called yet.
*/
protected void checkCanCreate() {
if (subjectGenerator == null) {
throw new IllegalStateException("Call using() before createTestSuite().");
}
if (name == null) {
throw new IllegalStateException("Call named() before createTestSuite().");
}
if (features == null) {
throw new IllegalStateException(
"Call withFeatures() before createTestSuite().");
}
}
// Class parameters must be raw.
protected abstract List<Class<? extends AbstractTester>>
getTesters();
private boolean matches(Test test) {
final Method method;
try {
method = extractMethod(test);
} catch (IllegalArgumentException e) {
logger.finer(Platform.format(
"%s: including by default: %s", test, e.getMessage()));
return true;
}
if (suppressedTests.contains(method)) {
logger.finer(Platform.format(
"%s: excluding because it was explicitly suppressed.", test));
return false;
}
final TesterRequirements requirements;
try {
requirements = FeatureUtil.getTesterRequirements(method);
} catch (ConflictingRequirementsException e) {
throw new RuntimeException(e);
}
if (!features.containsAll(requirements.getPresentFeatures())) {
if (logger.isLoggable(FINER)) {
Set<Feature<?>> missingFeatures =
Helpers.copyToSet(requirements.getPresentFeatures());
missingFeatures.removeAll(features);
logger.finer(Platform.format(
"%s: skipping because these features are absent: %s",
method, missingFeatures));
}
return false;
}
if (intersect(features, requirements.getAbsentFeatures())) {
if (logger.isLoggable(FINER)) {
Set<Feature<?>> unwantedFeatures =
Helpers.copyToSet(requirements.getAbsentFeatures());
unwantedFeatures.retainAll(features);
logger.finer(Platform.format(
"%s: skipping because these features are present: %s",
method, unwantedFeatures));
}
return false;
}
return true;
}
private static boolean intersect(Set<?> a, Set<?> b) {
return !disjoint(a, b);
}
private static Method extractMethod(Test test) {
if (test instanceof AbstractTester) {
AbstractTester<?> tester = (AbstractTester<?>) test;
return Helpers.getMethod(tester.getClass(), tester.getTestMethodName());
} else if (test instanceof TestCase) {
TestCase testCase = (TestCase) test;
return Helpers.getMethod(testCase.getClass(), testCase.getName());
} else {
throw new IllegalArgumentException(
"unable to extract method from test: not a TestCase.");
}
}
protected TestSuite makeSuiteForTesterClass(
Class<? extends AbstractTester<?>> testerClass) {
final TestSuite candidateTests = new TestSuite(testerClass);
final TestSuite suite = filterSuite(candidateTests);
Enumeration<?> allTests = suite.tests();
while (allTests.hasMoreElements()) {
Object test = allTests.nextElement();
if (test instanceof AbstractTester) {
@SuppressWarnings("unchecked")
AbstractTester<? super G> tester = (AbstractTester<? super G>) test;
tester.init(subjectGenerator, name, setUp, tearDown);
}
}
return suite;
}
private TestSuite filterSuite(TestSuite suite) {
TestSuite filtered = new TestSuite(suite.getName());
final Enumeration<?> tests = suite.tests();
while (tests.hasMoreElements()) {
Test test = (Test) tests.nextElement();
if (matches(test)) {
filtered.addTest(test);
}
}
return filtered;
}
protected static String formatFeatureSet(Set<? extends Feature<?>> features) {
List<String> temp = new ArrayList<String>();
for (Feature<?> feature : features) {
Object featureAsObject = feature; // to work around bogus JDK warning
if (featureAsObject instanceof Enum) {
Enum<?> f = (Enum<?>) featureAsObject;
temp.add(Platform.classGetSimpleName(
f.getDeclaringClass()) + "." + feature);
} else {
temp.add(feature.toString());
}
}
return temp.toString();
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilder.java | Java | asf20 | 10,330 |
/*
* 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.annotations.GwtCompatible;
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.
*
* @param <C> the type of the container
* @param <E> the type of the container's contents
*
* @author George van den Driessche
*/
@GwtCompatible
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(getOrderedElements());
}
/**
* 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>
*
* <p>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;
}
protected E[] createOrderedArray() {
E[] array = getSubjectGenerator().createArray(getNumElements());
getOrderedElements().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();
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/AbstractContainerTester.java | Java | asf20 | 8,238 |
/*
* 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.annotations.GwtCompatible;
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}.
*
* @author George van den Driessche
*/
@GwtCompatible
public interface OneSizeTestContainerGenerator<T, E>
extends TestSubjectGenerator<T>, TestContainerGenerator<T, E> {
TestContainerGenerator<T, E> getInnerGenerator();
Collection<E> getSampleElements(int howMany);
CollectionSize getCollectionSize();
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/OneSizeTestContainerGenerator.java | Java | asf20 | 1,457 |
/*
* 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.Set;
/**
* Reserializes the sets created by another test set generator.
*
* TODO: make CollectionTestSuiteBuilder test reserialized collections
*
* @author Jesse Wilson
*/
public class ReserializingTestSetGenerator<E>
extends ReserializingTestCollectionGenerator<E>
implements TestSetGenerator<E> {
ReserializingTestSetGenerator(TestSetGenerator<E> delegate) {
super(delegate);
}
public static <E> TestSetGenerator<E> newInstance(
TestSetGenerator<E> delegate) {
return new ReserializingTestSetGenerator<E>(delegate);
}
@Override public Set<E> create(Object... elements) {
return (Set<E>) super.create(elements);
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/ReserializingTestSetGenerator.java | Java | asf20 | 1,328 |
/*
* 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.annotations.GwtCompatible;
import java.util.Collection;
/**
* Creates collections, containing sample elements, to be tested.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public interface TestCollectionGenerator<E>
extends TestContainerGenerator<Collection<E>, E> {
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/TestCollectionGenerator.java | Java | asf20 | 951 |
/*
* 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.annotations.GwtCompatible;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;
/**
* Create integer sets for testing collections that are sorted by natural
* ordering.
*
* @author Chris Povirk
* @author Jared Levy
*/
@GwtCompatible
public abstract class TestIntegerSortedSetGenerator
extends TestIntegerSetGenerator {
@Override protected abstract SortedSet<Integer> create(Integer[] elements);
/** Sorts the elements by their natural ordering. */
@Override public List<Integer> order(List<Integer> insertionOrder) {
Collections.sort(insertionOrder);
return insertionOrder;
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/TestIntegerSortedSetGenerator.java | Java | asf20 | 1,306 |
/*
* 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.Feature;
import com.google.common.collect.testing.testers.CollectionSerializationEqualTester;
import com.google.common.collect.testing.testers.SetAddAllTester;
import com.google.common.collect.testing.testers.SetAddTester;
import com.google.common.collect.testing.testers.SetCreationTester;
import com.google.common.collect.testing.testers.SetEqualsTester;
import com.google.common.collect.testing.testers.SetHashCodeTester;
import com.google.common.collect.testing.testers.SetRemoveTester;
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 Set implementation.
*
* @author George van den Driessche
*/
public class SetTestSuiteBuilder<E>
extends AbstractCollectionTestSuiteBuilder<SetTestSuiteBuilder<E>, E> {
public static <E> SetTestSuiteBuilder<E> using(
TestSetGenerator<E> generator) {
return new SetTestSuiteBuilder<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(SetAddAllTester.class);
testers.add(SetAddTester.class);
testers.add(SetCreationTester.class);
testers.add(SetHashCodeTester.class);
testers.add(SetEqualsTester.class);
testers.add(SetRemoveTester.class);
// SetRemoveAllTester doesn't exist because, Sets not permitting
// duplicate elements, there are no tests for Set.removeAll() that aren't
// covered by CollectionRemoveAllTester.
return testers;
}
@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(SetTestSuiteBuilder
.using(new ReserializedSetGenerator<E>(parentBuilder.getSubjectGenerator()))
.named(getName() + " reserialized")
.withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
}
return derivedSuites;
}
static class ReserializedSetGenerator<E> implements TestSetGenerator<E>{
final OneSizeTestContainerGenerator<Collection<E>, E> gen;
private ReserializedSetGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) {
this.gen = gen;
}
@Override
public SampleElements<E> samples() {
return gen.samples();
}
@Override
public Set<E> create(Object... elements) {
return (Set<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);
}
}
private static Set<Feature<?>> computeReserializedCollectionFeatures(
Set<Feature<?>> features) {
Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>();
derivedFeatures.addAll(features);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);
return derivedFeatures;
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/SetTestSuiteBuilder.java | Java | asf20 | 4,491 |
/*
* 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.annotations.GwtCompatible;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* A container class for the five sample elements we need for testing.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public class SampleElements<E> implements Iterable<E> {
// TODO: rename e3, e4 => missing1, missing2
public final E e0;
public final E e1;
public final E e2;
public final E e3;
public final E e4;
public SampleElements(E e0, E e1, E e2, E e3, E e4) {
this.e0 = e0;
this.e1 = e1;
this.e2 = e2;
this.e3 = e3;
this.e4 = e4;
}
@Override
public Iterator<E> iterator() {
return asList().iterator();
}
public List<E> asList() {
return Arrays.asList(e0, e1, e2, e3, e4);
}
public static class Strings extends SampleElements<String> {
public Strings() {
// elements aren't sorted, to better test SortedSet iteration ordering
super("b", "a", "c", "d", "e");
}
// for testing SortedSet and SortedMap methods
public static final String BEFORE_FIRST = "\0";
public static final String BEFORE_FIRST_2 = "\0\0";
public static final String MIN_ELEMENT = "a";
public static final String AFTER_LAST = "z";
public static final String AFTER_LAST_2 = "zz";
}
public static class Chars extends SampleElements<Character> {
public Chars() {
// elements aren't sorted, to better test SortedSet iteration ordering
super('b', 'a', 'c', 'd', 'e');
}
}
public static class Enums extends SampleElements<AnEnum> {
public Enums() {
// elements aren't sorted, to better test SortedSet iteration ordering
super(AnEnum.B, AnEnum.A, AnEnum.C, AnEnum.D, AnEnum.E);
}
}
public static class Ints extends SampleElements<Integer> {
public Ints() {
// elements aren't sorted, to better test SortedSet iteration ordering
super(1, 0, 2, 3, 4);
}
}
public static <K, V> SampleElements<Map.Entry<K, V>> mapEntries(
SampleElements<K> keys, SampleElements<V> values) {
return new SampleElements<Map.Entry<K, V>>(
Helpers.mapEntry(keys.e0, values.e0),
Helpers.mapEntry(keys.e1, values.e1),
Helpers.mapEntry(keys.e2, values.e2),
Helpers.mapEntry(keys.e3, values.e3),
Helpers.mapEntry(keys.e4, values.e4));
}
public static class Unhashables extends SampleElements<UnhashableObject> {
public Unhashables() {
super(new UnhashableObject(1),
new UnhashableObject(2),
new UnhashableObject(3),
new UnhashableObject(4),
new UnhashableObject(5));
}
}
public static class Colliders extends SampleElements<Object> {
public Colliders() {
super(new Collider(1),
new Collider(2),
new Collider(3),
new Collider(4),
new Collider(5));
}
}
private static class Collider {
final int value;
Collider(int value) {
this.value = value;
}
@Override public boolean equals(Object obj) {
return obj instanceof Collider && ((Collider) obj).value == value;
}
@Override public int hashCode() {
return 1; // evil!
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/SampleElements.java | Java | asf20 | 3,872 |
/*
* 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;
import com.google.common.annotations.GwtCompatible;
/**
* A generator that relies on a preexisting generator for most of its work. For example, a derived
* iterator generator may delegate the work of creating the underlying collection to an inner
* collection generator.
*
* <p>{@code GwtTestSuiteGenerator} expects every {@code DerivedIterator} implementation to provide
* a one-arg constructor accepting its inner generator as an argument). This requirement enables it
* to generate source code (since GWT cannot use reflection to generate the suites).
*
* @author Chris Povirk
*/
@GwtCompatible
public interface DerivedGenerator {
TestSubjectGenerator<?> getInnerGenerator();
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/DerivedGenerator.java | Java | asf20 | 1,340 |
/*
* 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 com.google.common.collect.testing.DerivedCollectionGenerators.Bound;
import com.google.common.collect.testing.DerivedCollectionGenerators.SortedSetSubsetTestSetGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.testers.SortedSetNavigationTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a SortedSet implementation.
*/
public class SortedSetTestSuiteBuilder<E> extends SetTestSuiteBuilder<E> {
public static <E> SortedSetTestSuiteBuilder<E> using(
TestSortedSetGenerator<E> generator) {
SortedSetTestSuiteBuilder<E> builder =
new SortedSetTestSuiteBuilder<E>();
builder.usingGenerator(generator);
return builder;
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers =
Helpers.copyToList(super.getTesters());
testers.add(SortedSetNavigationTester.class);
return testers;
}
@Override public TestSuite createTestSuite() {
if (!getFeatures().contains(CollectionFeature.KNOWN_ORDER)) {
List<Feature<?>> features = Helpers.copyToList(getFeatures());
features.add(CollectionFeature.KNOWN_ORDER);
withFeatures(features);
}
return super.createTestSuite();
}
@Override
protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder<
?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) {
List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder);
if (!parentBuilder.getFeatures().contains(CollectionFeature.SUBSET_VIEW)) {
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.NO_BOUND, Bound.EXCLUSIVE));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.NO_BOUND));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.EXCLUSIVE));
}
return derivedSuites;
}
/**
* Creates a suite whose set has some elements filtered out of view.
*
* <p>Because the set may be ascending or descending, this test must derive
* the relative order of these extreme values rather than relying on their
* regular sort ordering.
*/
final TestSuite createSubsetSuite(final FeatureSpecificTestSuiteBuilder<?,
? extends OneSizeTestContainerGenerator<Collection<E>, E>>
parentBuilder, final Bound from, final Bound to) {
final TestSortedSetGenerator<E> delegate
= (TestSortedSetGenerator<E>) parentBuilder.getSubjectGenerator().getInnerGenerator();
List<Feature<?>> features = new ArrayList<Feature<?>>();
features.addAll(parentBuilder.getFeatures());
features.remove(CollectionFeature.ALLOWS_NULL_VALUES);
features.add(CollectionFeature.SUBSET_VIEW);
return newBuilderUsing(delegate, to, from)
.named(parentBuilder.getName() + " subSet " + from + "-" + to)
.withFeatures(features)
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
/** Like using() but overrideable by NavigableSetTestSuiteBuilder. */
SortedSetTestSuiteBuilder<E> newBuilderUsing(
TestSortedSetGenerator<E> delegate, Bound to, Bound from) {
return using(new SortedSetSubsetTestSetGenerator<E>(delegate, to, from));
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/SortedSetTestSuiteBuilder.java | Java | asf20 | 4,153 |
/*
* 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.annotations.GwtCompatible;
/**
* A type which will never be used as the element type of any collection in our
* tests, and so can be used to test how a Collection behaves when given input
* of the wrong type.
*/
@GwtCompatible
public enum WrongType {
VALUE
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/WrongType.java | Java | asf20 | 937 |
/*
* 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.annotations.GwtCompatible;
import java.util.Map;
/**
* Creates maps, containing sample elements, to be tested.
*
* @author George van den Driessche
*/
@GwtCompatible
public interface TestMapGenerator<K, V>
extends TestContainerGenerator<Map<K, V>, Map.Entry<K, V>> {
K[] createKeyArray(int length);
V[] createValueArray(int length);
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/TestMapGenerator.java | Java | asf20 | 1,021 |
/*
* 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.annotations.GwtCompatible;
/**
* A sample enumerated type we use for testing.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public enum AnEnum {
A, B, C, D, E, F
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/AnEnum.java | Java | asf20 | 844 |
/*
* 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 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.ConcurrentSkipListSet;
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());
suite.addTest(testsForConcurrentSkipListSetNatural());
suite.addTest(testsForConcurrentSkipListSetWithComparator());
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.emptySet();
}
protected Collection<Method> suppressForUnmodifiableSet() {
return Collections.emptySet();
}
protected Collection<Method> suppressForCheckedSet() {
return Collections.emptySet();
}
protected Collection<Method> suppressForAbstractSet() {
return Collections.emptySet();
}
protected Collection<Method> suppressForConcurrentSkipListSetNatural() {
return Collections.emptySet();
}
protected Collection<Method> suppressForConcurrentSkipListSetWithComparator() {
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,
CollectionSize.ANY)
.suppressing(suppressForEnumSet())
.createTestSuite();
}
public Test testsForTreeSetNatural() {
return NavigableSetTestSuiteBuilder
.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 NavigableSetTestSuiteBuilder
.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(
CollectionFeature.SUPPORTS_ADD,
CollectionFeature.SUPPORTS_REMOVE,
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();
}
public Test testsForConcurrentSkipListSetNatural() {
return SetTestSuiteBuilder
.using(new TestStringSortedSetGenerator() {
@Override public SortedSet<String> create(String[] elements) {
return new ConcurrentSkipListSet<String>(MinimalCollection.of(elements));
}
})
.named("ConcurrentSkipListSet, natural")
.withFeatures(
SetFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.KNOWN_ORDER,
CollectionSize.ANY)
.suppressing(suppressForConcurrentSkipListSetNatural())
.createTestSuite();
}
public Test testsForConcurrentSkipListSetWithComparator() {
return SetTestSuiteBuilder
.using(new TestStringSortedSetGenerator() {
@Override public SortedSet<String> create(String[] elements) {
SortedSet<String> set
= new ConcurrentSkipListSet<String>(arbitraryNullFriendlyComparator());
Collections.addAll(set, elements);
return set;
}
})
.named("ConcurrentSkipListSet, with comparator")
.withFeatures(
SetFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.KNOWN_ORDER,
CollectionSize.ANY)
.suppressing(suppressForConcurrentSkipListSetWithComparator())
.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));
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/TestsForSetsInJavaUtil.java | Java | asf20 | 14,020 |
/*
* 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.annotations.GwtCompatible;
import java.util.Iterator;
import java.util.Map.Entry;
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.
*
* @author Jared Levy
*/
// TODO: Use this class to test classes besides ImmutableSortedMap.
@GwtCompatible
public abstract class SortedMapInterfaceTest<K, V>
extends MapInterfaceTest<K, V> {
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();
}
}
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();
iterator.next(); // advance
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());
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/SortedMapInterfaceTest.java | Java | asf20 | 4,023 |
/*
* 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.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
/**
* 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(testsForTreeMapNatural());
suite.addTest(testsForTreeMapWithComparator());
suite.addTest(testsForEnumMap());
suite.addTest(testsForConcurrentHashMap());
suite.addTest(testsForConcurrentSkipListMapNatural());
suite.addTest(testsForConcurrentSkipListMapWithComparator());
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> suppressForTreeMapNatural() {
return Collections.emptySet();
}
protected Collection<Method> suppressForTreeMapWithComparator() {
return Collections.emptySet();
}
protected Collection<Method> suppressForEnumMap() {
return Collections.emptySet();
}
protected Collection<Method> suppressForConcurrentHashMap() {
return Collections.emptySet();
}
protected Collection<Method> suppressForConcurrentSkipListMap() {
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,
MapFeature.ALLOWS_ANY_NULL_QUERIES,
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);
}
})
.named("HashMap")
.withFeatures(
MapFeature.GENERAL_PURPOSE,
MapFeature.ALLOWS_NULL_KEYS,
MapFeature.ALLOWS_NULL_VALUES,
MapFeature.ALLOWS_ANY_NULL_QUERIES,
MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionFeature.SUPPORTS_ITERATOR_REMOVE,
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.ALLOWS_ANY_NULL_QUERIES,
MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionFeature.SUPPORTS_ITERATOR_REMOVE,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForLinkedHashMap())
.createTestSuite();
}
public Test testsForTreeMapNatural() {
return NavigableMapTestSuiteBuilder
.using(new TestStringSortedMapGenerator() {
@Override protected SortedMap<String, String> create(
Entry<String, String>[] entries) {
/*
* TODO(cpovirk): it would be nice to create an input Map and use
* the copy constructor here and in the other tests
*/
return populate(new TreeMap<String, String>(), entries);
}
})
.named("TreeMap, natural")
.withFeatures(
MapFeature.GENERAL_PURPOSE,
MapFeature.ALLOWS_NULL_VALUES,
MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionFeature.SUPPORTS_ITERATOR_REMOVE,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForTreeMapNatural())
.createTestSuite();
}
public Test testsForTreeMapWithComparator() {
return NavigableMapTestSuiteBuilder
.using(new TestStringSortedMapGenerator() {
@Override protected SortedMap<String, String> create(
Entry<String, String>[] entries) {
return populate(new TreeMap<String, String>(
arbitraryNullFriendlyComparator()), entries);
}
})
.named("TreeMap, with comparator")
.withFeatures(
MapFeature.GENERAL_PURPOSE,
MapFeature.ALLOWS_NULL_KEYS,
MapFeature.ALLOWS_NULL_VALUES,
MapFeature.ALLOWS_ANY_NULL_QUERIES,
MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionFeature.SUPPORTS_ITERATOR_REMOVE,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForTreeMapWithComparator())
.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.SUPPORTS_ITERATOR_REMOVE,
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.SUPPORTS_ITERATOR_REMOVE,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForConcurrentHashMap())
.createTestSuite();
}
public Test testsForConcurrentSkipListMapNatural() {
return NavigableMapTestSuiteBuilder
.using(new TestStringSortedMapGenerator() {
@Override protected SortedMap<String, String> create(
Entry<String, String>[] entries) {
return populate(new ConcurrentSkipListMap<String, String>(), entries);
}
})
.named("ConcurrentSkipListMap, natural")
.withFeatures(
MapFeature.GENERAL_PURPOSE,
CollectionFeature.SUPPORTS_ITERATOR_REMOVE,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForConcurrentSkipListMap())
.createTestSuite();
}
public Test testsForConcurrentSkipListMapWithComparator() {
return NavigableMapTestSuiteBuilder
.using(new TestStringSortedMapGenerator() {
@Override protected SortedMap<String, String> create(
Entry<String, String>[] entries) {
return populate(new ConcurrentSkipListMap<String, String>(
arbitraryNullFriendlyComparator()), entries);
}
})
.named("ConcurrentSkipListMap, with comparator")
.withFeatures(
MapFeature.GENERAL_PURPOSE,
CollectionFeature.SUPPORTS_ITERATOR_REMOVE,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForConcurrentSkipListMap())
.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, M extends Map<T, String>> M populate(
M 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));
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/TestsForMapsInJavaUtil.java | Java | asf20 | 11,820 |
/*
* 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.AbstractSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
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<Object> NATURAL_ORDER = new Comparator<Object>() {
@Override public int compare(Object o1, Object o2) {
return ((Comparable<Object>) 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 = (Comparator<? super K>) 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 new AbstractSet<Entry<K, V>>() {
private Set<Entry<K, V>> delegate() {
return delegate.entrySet();
}
@Override
public boolean contains(Object object) {
try {
return delegate().contains(object);
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
@Override
public Iterator<Entry<K, V>> iterator() {
return delegate().iterator();
}
@Override
public int size() {
return delegate().size();
}
@Override
public boolean remove(Object o) {
return delegate().remove(o);
}
@Override
public void clear() {
delegate().clear();
}
};
}
@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;
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/SafeTreeMap.java | Java | asf20 | 7,356 |
/*
* 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 com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
/**
* Simple base class to verify that we handle generics correctly.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public class BaseComparable implements Comparable<BaseComparable>, Serializable {
private final String s;
public BaseComparable(String s) {
this.s = s;
}
@Override public int hashCode() { // delegate to 's'
return s.hashCode();
}
@Override public boolean equals(Object other) {
if (other == null) {
return false;
} else if (other instanceof BaseComparable) {
return s.equals(((BaseComparable) other).s);
} else {
return false;
}
}
@Override
public int compareTo(BaseComparable o) {
return s.compareTo(o.s);
}
private static final long serialVersionUID = 0;
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/BaseComparable.java | Java | asf20 | 1,482 |
/*
* 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.annotations.GwtCompatible;
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.
*
* @author Regina O'Dell
*/
@GwtCompatible
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;
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/TestUnhashableCollectionGenerator.java | Java | asf20 | 1,893 |
/*
* 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.annotations.GwtCompatible;
import com.google.common.collect.testing.SampleElements.Chars;
import java.util.List;
/**
* Generates {@code List<Character>} instances for test suites.
*
* @author Kevin Bourrillion
* @author Louis Wasserman
*/
@GwtCompatible
public abstract class TestCharacterListGenerator
implements TestListGenerator<Character> {
@Override
public SampleElements<Character> samples() {
return new Chars();
}
@Override
public List<Character> create(Object... elements) {
Character[] array = new Character[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (Character) e;
}
return create(array);
}
/**
* Creates a new collection containing the given elements; implement this
* method instead of {@link #create(Object...)}.
*/
protected abstract List<Character> create(Character[] elements);
@Override
public Character[] createArray(int length) {
return new Character[length];
}
/** Returns the original element list, unchanged. */
@Override
public List<Character> order(List<Character> insertionOrder) {
return insertionOrder;
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/TestCharacterListGenerator.java | Java | asf20 | 1,825 |
/*
* 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.annotations.GwtCompatible;
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.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
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;
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/TestEnumSetGenerator.java | Java | asf20 | 1,727 |
/*
* 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 com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.features.FeatureUtil;
import junit.framework.TestSuite;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
/**
* This builder creates a composite test suite, containing a separate test suite
* for each {@link CollectionSize} present in the features specified
* by {@link #withFeatures(Feature...)}.
*
* @param <B> The concrete type of this builder (the 'self-type'). All the
* Builder methods of this class (such as {@link #named(String)}) return this
* type, so that Builder methods of more derived classes can be chained onto
* them without casting.
* @param <G> The type of the generator to be passed to testers in the
* generated test suite. An instance of G should somehow provide an
* instance of the class under test, plus any other information required
* to parameterize the test.
*
* @see FeatureSpecificTestSuiteBuilder
*
* @author George van den Driessche
*/
public abstract class PerCollectionSizeTestSuiteBuilder<
B extends PerCollectionSizeTestSuiteBuilder<B, G, T, E>,
G extends TestContainerGenerator<T, E>,
T,
E>
extends FeatureSpecificTestSuiteBuilder<B, G> {
private static final Logger logger = Logger.getLogger(
PerCollectionSizeTestSuiteBuilder.class.getName());
/**
* Creates a runnable JUnit test suite based on the criteria already given.
*/
@Override public TestSuite createTestSuite() {
checkCanCreate();
String name = getName();
// Copy this set, so we can modify it.
Set<Feature<?>> features = Helpers.copyToSet(getFeatures());
List<Class<? extends AbstractTester>> testers = getTesters();
logger.fine(" Testing: " + name);
// Split out all the specified sizes.
Set<Feature<?>> sizesToTest =
Helpers.<Feature<?>>copyToSet(CollectionSize.values());
sizesToTest.retainAll(features);
features.removeAll(sizesToTest);
FeatureUtil.addImpliedFeatures(sizesToTest);
sizesToTest.retainAll(Arrays.asList(
CollectionSize.ZERO, CollectionSize.ONE, CollectionSize.SEVERAL));
logger.fine(" Sizes: " + formatFeatureSet(sizesToTest));
if (sizesToTest.isEmpty()) {
throw new IllegalStateException(name
+ ": no CollectionSizes specified (check the argument to "
+ "FeatureSpecificTestSuiteBuilder.withFeatures().)");
}
TestSuite suite = new TestSuite(name);
for (Feature<?> collectionSize : sizesToTest) {
String oneSizeName = Platform.format("%s [collection size: %s]",
name, collectionSize.toString().toLowerCase());
OneSizeGenerator<T, E> oneSizeGenerator = new OneSizeGenerator<T, E>(
getSubjectGenerator(), (CollectionSize) collectionSize);
Set<Feature<?>> oneSizeFeatures = Helpers.copyToSet(features);
oneSizeFeatures.add(collectionSize);
Set<Method> oneSizeSuppressedTests = getSuppressedTests();
OneSizeTestSuiteBuilder<T, E> oneSizeBuilder =
new OneSizeTestSuiteBuilder<T, E>(testers)
.named(oneSizeName)
.usingGenerator(oneSizeGenerator)
.withFeatures(oneSizeFeatures)
.withSetUp(getSetUp())
.withTearDown(getTearDown())
.suppressing(oneSizeSuppressedTests);
TestSuite oneSizeSuite = oneSizeBuilder.createTestSuite();
suite.addTest(oneSizeSuite);
for (TestSuite derivedSuite : createDerivedSuites(oneSizeBuilder)) {
oneSizeSuite.addTest(derivedSuite);
}
}
return suite;
}
protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder<
?, ? extends OneSizeTestContainerGenerator<T, E>> parentBuilder) {
return new ArrayList<TestSuite>();
}
/** Builds a test suite for one particular {@link CollectionSize}. */
private static final class OneSizeTestSuiteBuilder<T, E> extends
FeatureSpecificTestSuiteBuilder<
OneSizeTestSuiteBuilder<T, E>, OneSizeGenerator<T, E>> {
private final List<Class<? extends AbstractTester>> testers;
public OneSizeTestSuiteBuilder(
List<Class<? extends AbstractTester>> testers) {
this.testers = testers;
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
return testers;
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/PerCollectionSizeTestSuiteBuilder.java | Java | asf20 | 5,143 |
/*
* 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.annotations.GwtCompatible;
import java.util.Collection;
/**
* Base class for collection testers.
*
* @param <E> the element type of the collection to be tested.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public abstract class AbstractCollectionTester<E>
extends AbstractContainerTester<Collection<E>, E> {
// TODO: replace this with an accessor.
protected Collection<E> collection;
@Override protected Collection<E> actualContents() {
return collection;
}
// TODO: dispose of this once collection is encapsulated.
@Override protected Collection<E> resetContainer(Collection<E> newContents) {
collection = super.resetContainer(newContents);
return collection;
}
/** @see AbstractContainerTester#resetContainer() */
protected void resetCollection() {
resetContainer();
}
/**
* @return an array of the proper size with {@code null} inserted into the
* middle element.
*/
protected E[] createArrayWithNullElement() {
E[] array = createSamplesArray();
array[getNullLocation()] = null;
return array;
}
protected void initCollectionWithNullElement() {
E[] array = createArrayWithNullElement();
resetContainer(getSubjectGenerator().create(array));
}
/**
* Equivalent to {@link #expectMissing(Object[]) expectMissing}{@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 expectNullMissingWhenNullUnsupported(String message) {
try {
assertFalse(message, actualContents().contains(null));
} catch (NullPointerException tolerated) {
// Tolerated
}
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/AbstractCollectionTester.java | Java | asf20 | 2,399 |
/*
* 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 com.google.common.annotations.GwtCompatible;
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.
*
* @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
*/
@GwtCompatible
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();
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/MapInterfaceTest.java | Java | asf20 | 47,230 |
/*
* 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.annotations.GwtCompatible;
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.
*
* @author George van den Driessche
*/
@GwtCompatible
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);
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/OneSizeGenerator.java | Java | asf20 | 2,481 |
/*
* 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();
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/DerivedIteratorTestSuiteBuilder.java | Java | asf20 | 1,694 |
/*
* 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.annotations.GwtCompatible;
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
*/
@GwtCompatible
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];
System.arraycopy(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();
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/MinimalCollection.java | Java | asf20 | 3,532 |
/*
* 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.annotations.GwtCompatible;
import java.util.Iterator;
/**
* Creates iterators to be tested.
*
* @param <E> the element type of the iterator.
*
* @author George van den Driessche
*/
@GwtCompatible
public interface TestIteratorGenerator<E> {
Iterator<E> get();
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/TestIteratorGenerator.java | Java | asf20 | 942 |
/*
* 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.annotations.GwtCompatible;
import java.util.List;
/**
* Creates sets, containing sample elements, to be tested.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public interface TestListGenerator<E> extends TestCollectionGenerator<E> {
@Override
List<E> create(Object... elements);
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/TestListGenerator.java | Java | asf20 | 964 |
/*
* 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 com.google.common.collect.testing.DerivedCollectionGenerators.Bound;
import com.google.common.collect.testing.DerivedCollectionGenerators.SortedSetSubsetTestSetGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.testers.NavigableSetNavigationTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.NavigableSet;
import java.util.Set;
import java.util.SortedSet;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a NavigableSet implementation.
*/
public final class NavigableSetTestSuiteBuilder<E>
extends SortedSetTestSuiteBuilder<E> {
public static <E> NavigableSetTestSuiteBuilder<E> using(
TestSortedSetGenerator<E> generator) {
NavigableSetTestSuiteBuilder<E> builder =
new NavigableSetTestSuiteBuilder<E>();
builder.usingGenerator(generator);
return builder;
}
@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.SUBSET_VIEW)) {
// Other combinations are inherited from SortedSetTestSuiteBuilder.
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.NO_BOUND, Bound.INCLUSIVE));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.NO_BOUND));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.EXCLUSIVE));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.INCLUSIVE));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.INCLUSIVE));
}
if (!parentBuilder.getFeatures().contains(CollectionFeature.DESCENDING_VIEW)) {
derivedSuites.add(createDescendingSuite(parentBuilder));
}
return derivedSuites;
}
public static final class NavigableSetSubsetTestSetGenerator<E>
extends SortedSetSubsetTestSetGenerator<E> {
public NavigableSetSubsetTestSetGenerator(
TestSortedSetGenerator<E> delegate, Bound to, Bound from) {
super(delegate, to, from);
}
@Override NavigableSet<E> createSubSet(SortedSet<E> sortedSet, E firstExclusive,
E lastExclusive) {
NavigableSet<E> set = (NavigableSet<E>) sortedSet;
if (from == Bound.NO_BOUND && to == Bound.INCLUSIVE) {
return set.headSet(lastInclusive, true);
} else if (from == Bound.EXCLUSIVE && to == Bound.NO_BOUND) {
return set.tailSet(firstExclusive, false);
} else if (from == Bound.EXCLUSIVE && to == Bound.EXCLUSIVE) {
return set.subSet(firstExclusive, false, lastExclusive, false);
} else if (from == Bound.EXCLUSIVE && to == Bound.INCLUSIVE) {
return set.subSet(firstExclusive, false, lastInclusive, true);
} else if (from == Bound.INCLUSIVE && to == Bound.INCLUSIVE) {
return set.subSet(firstInclusive, true, lastInclusive, true);
} else {
return (NavigableSet<E>) super.createSubSet(set, firstExclusive, lastExclusive);
}
}
}
@Override
public NavigableSetTestSuiteBuilder<E> newBuilderUsing(
TestSortedSetGenerator<E> delegate, Bound to, Bound from) {
return using(new NavigableSetSubsetTestSetGenerator<E>(delegate, to, from));
}
/**
* Create a suite whose maps are descending views of other maps.
*/
private TestSuite createDescendingSuite(final FeatureSpecificTestSuiteBuilder<?,
? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) {
final TestSetGenerator<E> delegate =
(TestSetGenerator<E>) parentBuilder.getSubjectGenerator().getInnerGenerator();
List<Feature<?>> features = new ArrayList<Feature<?>>();
features.add(CollectionFeature.DESCENDING_VIEW);
features.addAll(parentBuilder.getFeatures());
return NavigableSetTestSuiteBuilder.using(new TestSetGenerator<E>() {
@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) {
List<E> list = new ArrayList<E>();
for (E e : delegate.order(insertionOrder)) {
list.add(e);
}
Collections.reverse(list);
return list;
}
@Override
public Set<E> create(Object... elements) {
NavigableSet<E> navigableSet = (NavigableSet<E>) delegate.create(elements);
return navigableSet.descendingSet();
}
})
.named(parentBuilder.getName() + " descending")
.withFeatures(features)
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers =
Helpers.copyToList(super.getTesters());
testers.add(NavigableSetNavigationTester.class);
return testers;
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/NavigableSetTestSuiteBuilder.java | Java | asf20 | 6,103 |
/*
* 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 junit.framework.Assert.assertEquals;
import static junit.framework.Assert.fail;
import com.google.common.annotations.GwtCompatible;
import junit.framework.AssertionFailedError;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Stack;
/**
* Most of the logic for {@link IteratorTester} and {@link ListIteratorTester}.
*
* @param <E> the type of element returned by the iterator
* @param <I> the type of the iterator ({@link Iterator} or
* {@link ListIterator})
*
* @author Kevin Bourrillion
* @author Chris Povirk
*/
@GwtCompatible
abstract class AbstractIteratorTester<E, I extends Iterator<E>> {
private boolean whenNextThrowsExceptionStopTestingCallsToRemove;
private boolean whenAddThrowsExceptionStopTesting;
/**
* Don't verify iterator behavior on remove() after a call to next()
* throws an exception.
*
* <p>JDK 6 currently has a bug where some iterators get into a undefined
* state when next() throws a NoSuchElementException. The correct
* behavior is for remove() to remove the last element returned by
* next, even if a subsequent next() call threw an exception; however
* JDK 6's HashMap and related classes throw an IllegalStateException
* in this case.
*
* <p>Calling this method causes the iterator tester to skip testing
* any remove() in a stimulus sequence after the reference iterator
* throws an exception in next().
*
* <p>TODO: remove this once we're on 6u5, which has the fix.
*
* @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6529795">
* Sun Java Bug 6529795</a>
*/
public void ignoreSunJavaBug6529795() {
whenNextThrowsExceptionStopTestingCallsToRemove = true;
}
/**
* Don't verify iterator behavior after a call to add() throws an exception.
*
* <p>AbstractList's ListIterator implementation gets into a undefined state
* when add() throws an UnsupportedOperationException. Instead of leaving the
* iterator's position unmodified, it increments it, skipping an element or
* even moving past the end of the list.
*
* <p>Calling this method causes the iterator tester to skip testing in a
* stimulus sequence after the iterator under test throws an exception in
* add().
*
* <p>TODO: remove this once the behavior is fixed.
*
* @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6533203">
* Sun Java Bug 6533203</a>
*/
public void stopTestingWhenAddThrowsException() {
whenAddThrowsExceptionStopTesting = true;
}
private Stimulus<E, ? super I>[] stimuli;
private final Iterator<E> elementsToInsert;
private final Set<IteratorFeature> features;
private final List<E> expectedElements;
private final int startIndex;
private final KnownOrder knownOrder;
/**
* Meta-exception thrown by
* {@link AbstractIteratorTester.MultiExceptionListIterator} instead of
* throwing any particular exception type.
*/
// This class is accessible but not supported in GWT.
private static final class PermittedMetaException extends RuntimeException {
final Set<? extends Class<? extends RuntimeException>> exceptionClasses;
PermittedMetaException(
Set<? extends Class<? extends RuntimeException>> exceptionClasses) {
super("one of " + exceptionClasses);
this.exceptionClasses = exceptionClasses;
}
PermittedMetaException(Class<? extends RuntimeException> exceptionClass) {
this(Collections.singleton(exceptionClass));
}
// It's not supported In GWT, it always returns true.
boolean isPermitted(RuntimeException exception) {
for (Class<? extends RuntimeException> clazz : exceptionClasses) {
if (Platform.checkIsInstance(clazz, exception)) {
return true;
}
}
return false;
}
// It's not supported in GWT, it always passes.
void assertPermitted(RuntimeException exception) {
if (!isPermitted(exception)) {
// TODO: use simple class names
String message = "Exception " + exception.getClass()
+ " was thrown; expected " + this;
Helpers.fail(exception, message);
}
}
@Override public String toString() {
return getMessage();
}
private static final long serialVersionUID = 0;
}
private static final class UnknownElementException extends RuntimeException {
private UnknownElementException(Collection<?> expected, Object actual) {
super("Returned value '"
+ actual + "' not found. Remaining elements: " + expected);
}
private static final long serialVersionUID = 0;
}
/**
* Quasi-implementation of {@link ListIterator} that works from a list of
* elements and a set of features to support (from the enclosing
* {@link AbstractIteratorTester} instance). Instead of throwing exceptions
* like {@link NoSuchElementException} at the appropriate times, it throws
* {@link PermittedMetaException} instances, which wrap a set of all
* exceptions that the iterator could throw during the invocation of that
* method. This is necessary because, e.g., a call to
* {@code iterator().remove()} of an unmodifiable list could throw either
* {@link IllegalStateException} or {@link UnsupportedOperationException}.
* Note that iterator implementations should always throw one of the
* exceptions in a {@code PermittedExceptions} instance, since
* {@code PermittedExceptions} is thrown only when a method call is invalid.
*
* <p>This class is accessible but not supported in GWT as it references
* {@link PermittedMetaException}.
*/
protected final class MultiExceptionListIterator implements ListIterator<E> {
// TODO: track seen elements when order isn't guaranteed
// TODO: verify contents afterward
// TODO: something shiny and new instead of Stack
// TODO: test whether null is supported (create a Feature)
/**
* The elements to be returned by future calls to {@code next()}, with the
* first at the top of the stack.
*/
final Stack<E> nextElements = new Stack<E>();
/**
* The elements to be returned by future calls to {@code previous()}, with
* the first at the top of the stack.
*/
final Stack<E> previousElements = new Stack<E>();
/**
* {@link #nextElements} if {@code next()} was called more recently then
* {@code previous}, {@link #previousElements} if the reverse is true, or --
* overriding both of these -- {@code null} if {@code remove()} or
* {@code add()} has been called more recently than either. We use this to
* determine which stack to pop from on a call to {@code remove()} (or to
* pop from and push to on a call to {@code set()}.
*/
Stack<E> stackWithLastReturnedElementAtTop = null;
MultiExceptionListIterator(List<E> expectedElements) {
Helpers.addAll(nextElements, Helpers.reverse(expectedElements));
for (int i = 0; i < startIndex; i++) {
previousElements.push(nextElements.pop());
}
}
@Override
public void add(E e) {
if (!features.contains(IteratorFeature.SUPPORTS_ADD)) {
throw new PermittedMetaException(UnsupportedOperationException.class);
}
previousElements.push(e);
stackWithLastReturnedElementAtTop = null;
}
@Override
public boolean hasNext() {
return !nextElements.isEmpty();
}
@Override
public boolean hasPrevious() {
return !previousElements.isEmpty();
}
@Override
public E next() {
return transferElement(nextElements, previousElements);
}
@Override
public int nextIndex() {
return previousElements.size();
}
@Override
public E previous() {
return transferElement(previousElements, nextElements);
}
@Override
public int previousIndex() {
return nextIndex() - 1;
}
@Override
public void remove() {
throwIfInvalid(IteratorFeature.SUPPORTS_REMOVE);
stackWithLastReturnedElementAtTop.pop();
stackWithLastReturnedElementAtTop = null;
}
@Override
public void set(E e) {
throwIfInvalid(IteratorFeature.SUPPORTS_SET);
stackWithLastReturnedElementAtTop.pop();
stackWithLastReturnedElementAtTop.push(e);
}
/**
* Moves the given element from its current position in
* {@link #nextElements} to the top of the stack so that it is returned by
* the next call to {@link Iterator#next()}. If the element is not in
* {@link #nextElements}, this method throws an
* {@link UnknownElementException}.
*
* <p>This method is used when testing iterators without a known ordering.
* We poll the target iterator's next element and pass it to the reference
* iterator through this method so it can return the same element. This
* enables the assertion to pass and the reference iterator to properly
* update its state.
*/
void promoteToNext(E e) {
if (nextElements.remove(e)) {
nextElements.push(e);
} else {
throw new UnknownElementException(nextElements, e);
}
}
private E transferElement(Stack<E> source, Stack<E> destination) {
if (source.isEmpty()) {
throw new PermittedMetaException(NoSuchElementException.class);
}
destination.push(source.pop());
stackWithLastReturnedElementAtTop = destination;
return destination.peek();
}
private void throwIfInvalid(IteratorFeature methodFeature) {
Set<Class<? extends RuntimeException>> exceptions
= new HashSet<Class<? extends RuntimeException>>();
if (!features.contains(methodFeature)) {
exceptions.add(UnsupportedOperationException.class);
}
if (stackWithLastReturnedElementAtTop == null) {
exceptions.add(IllegalStateException.class);
}
if (!exceptions.isEmpty()) {
throw new PermittedMetaException(exceptions);
}
}
private List<E> getElements() {
List<E> elements = new ArrayList<E>();
Helpers.addAll(elements, previousElements);
Helpers.addAll(elements, Helpers.reverse(nextElements));
return elements;
}
}
public enum KnownOrder { KNOWN_ORDER, UNKNOWN_ORDER }
@SuppressWarnings("unchecked") // creating array of generic class Stimulus
AbstractIteratorTester(int steps, Iterable<E> elementsToInsertIterable,
Iterable<? extends IteratorFeature> features,
Iterable<E> expectedElements, KnownOrder knownOrder, int startIndex) {
// periodically we should manually try (steps * 3 / 2) here; all tests but
// one should still pass (testVerifyGetsCalled()).
stimuli = new Stimulus[steps];
if (!elementsToInsertIterable.iterator().hasNext()) {
throw new IllegalArgumentException();
}
elementsToInsert = Helpers.cycle(elementsToInsertIterable);
this.features = Helpers.copyToSet(features);
this.expectedElements = Helpers.copyToList(expectedElements);
this.knownOrder = knownOrder;
this.startIndex = startIndex;
}
/**
* I'd like to make this a parameter to the constructor, but I can't because
* the stimulus instances refer to {@code this}.
*/
protected abstract Iterable<? extends Stimulus<E, ? super I>>
getStimulusValues();
/**
* Returns a new target iterator each time it's called. This is the iterator
* you are trying to test. This must return an Iterator that returns the
* expected elements passed to the constructor in the given order. Warning: it
* is not enough to simply pull multiple iterators from the same source
* Iterable, unless that Iterator is unmodifiable.
*/
protected abstract I newTargetIterator();
/**
* Override this to verify anything after running a list of Stimuli.
*
* <p>For example, verify that calls to remove() actually removed
* the correct elements.
*
* @param elements the expected elements passed to the constructor, as mutated
* by {@code remove()}, {@code set()}, and {@code add()} calls
*/
protected void verify(List<E> elements) {}
/**
* Executes the test.
*/
public final void test() {
try {
recurse(0);
} catch (RuntimeException e) {
throw new RuntimeException(Arrays.toString(stimuli), e);
}
}
private void recurse(int level) {
// We're going to reuse the stimuli array 3^steps times by overwriting it
// in a recursive loop. Sneaky.
if (level == stimuli.length) {
// We've filled the array.
compareResultsForThisListOfStimuli();
} else {
// Keep recursing to fill the array.
for (Stimulus<E, ? super I> stimulus : getStimulusValues()) {
stimuli[level] = stimulus;
recurse(level + 1);
}
}
}
private void compareResultsForThisListOfStimuli() {
MultiExceptionListIterator reference =
new MultiExceptionListIterator(expectedElements);
I target = newTargetIterator();
boolean shouldStopTestingCallsToRemove = false;
for (int i = 0; i < stimuli.length; i++) {
Stimulus<E, ? super I> stimulus = stimuli[i];
if (stimulus.equals(remove) && shouldStopTestingCallsToRemove) {
break;
}
try {
boolean threwException = stimulus.executeAndCompare(reference, target);
if (threwException
&& stimulus.equals(next)
&& whenNextThrowsExceptionStopTestingCallsToRemove) {
shouldStopTestingCallsToRemove = true;
}
if (threwException
&& stimulus.equals(add)
&& whenAddThrowsExceptionStopTesting) {
break;
}
List<E> elements = reference.getElements();
verify(elements);
} catch (AssertionFailedError cause) {
Helpers.fail(cause,
"failed with stimuli " + subListCopy(stimuli, i + 1));
}
}
}
private static List<Object> subListCopy(Object[] source, int size) {
final Object[] copy = new Object[size];
System.arraycopy(source, 0, copy, 0, size);
return Arrays.asList(copy);
}
private interface IteratorOperation {
Object execute(Iterator<?> iterator);
}
/**
* Apply this method to both iterators and return normally only if both
* produce the same response.
*
* @return {@code true} if an exception was thrown by the iterators.
*
* @see Stimulus#executeAndCompare(ListIterator, Iterator)
*/
private <T extends Iterator<E>> boolean internalExecuteAndCompare(
T reference, T target, IteratorOperation method)
throws AssertionFailedError {
Object referenceReturnValue = null;
PermittedMetaException referenceException = null;
Object targetReturnValue = null;
RuntimeException targetException = null;
try {
targetReturnValue = method.execute(target);
} catch (RuntimeException e) {
targetException = e;
}
try {
if (method == NEXT_METHOD && targetException == null
&& knownOrder == KnownOrder.UNKNOWN_ORDER) {
/*
* We already know the iterator is an Iterator<E>, and now we know that
* we called next(), so the returned element must be of type E.
*/
@SuppressWarnings("unchecked")
E targetReturnValueFromNext = (E) targetReturnValue;
/*
* We have an Iterator<E> and want to cast it to
* MultiExceptionListIterator. Because we're inside an
* AbstractIteratorTester<E>, that's implicitly a cast to
* AbstractIteratorTester<E>.MultiExceptionListIterator. The runtime
* won't be able to verify the AbstractIteratorTester<E> part, so it's
* an unchecked cast. We know, however, that the only possible value for
* the type parameter is <E>, since otherwise the
* MultiExceptionListIterator wouldn't be an Iterator<E>. The cast is
* safe, even though javac can't tell.
*
* Sun bug 6665356 is an additional complication. Until OpenJDK 7, javac
* doesn't recognize this kind of cast as unchecked cast. Neither does
* Eclipse 3.4. Right now, this suppression is mostly unecessary.
*/
MultiExceptionListIterator multiExceptionListIterator =
(MultiExceptionListIterator) reference;
multiExceptionListIterator.promoteToNext(targetReturnValueFromNext);
}
referenceReturnValue = method.execute(reference);
} catch (PermittedMetaException e) {
referenceException = e;
} catch (UnknownElementException e) {
Helpers.fail(e, e.getMessage());
}
if (referenceException == null) {
if (targetException != null) {
Helpers.fail(targetException,
"Target threw exception when reference did not");
}
/*
* Reference iterator returned a value, so we should expect the
* same value from the target
*/
assertEquals(referenceReturnValue, targetReturnValue);
return false;
}
if (targetException == null) {
fail("Target failed to throw " + referenceException);
}
/*
* Reference iterator threw an exception, so we should expect an acceptable
* exception from the target.
*/
referenceException.assertPermitted(targetException);
return true;
}
private static final IteratorOperation REMOVE_METHOD =
new IteratorOperation() {
@Override
public Object execute(Iterator<?> iterator) {
iterator.remove();
return null;
}
};
private static final IteratorOperation NEXT_METHOD =
new IteratorOperation() {
@Override
public Object execute(Iterator<?> iterator) {
return iterator.next();
}
};
private static final IteratorOperation PREVIOUS_METHOD =
new IteratorOperation() {
@Override
public Object execute(Iterator<?> iterator) {
return ((ListIterator<?>) iterator).previous();
}
};
private final IteratorOperation newAddMethod() {
final Object toInsert = elementsToInsert.next();
return new IteratorOperation() {
@Override
public Object execute(Iterator<?> iterator) {
@SuppressWarnings("unchecked")
ListIterator<Object> rawIterator = (ListIterator<Object>) iterator;
rawIterator.add(toInsert);
return null;
}
};
}
private final IteratorOperation newSetMethod() {
final E toInsert = elementsToInsert.next();
return new IteratorOperation() {
@Override
public Object execute(Iterator<?> iterator) {
@SuppressWarnings("unchecked")
ListIterator<E> li = (ListIterator<E>) iterator;
li.set(toInsert);
return null;
}
};
}
abstract static class Stimulus<E, T extends Iterator<E>> {
private final String toString;
protected Stimulus(String toString) {
this.toString = toString;
}
/**
* Send this stimulus to both iterators and return normally only if both
* produce the same response.
*
* @return {@code true} if an exception was thrown by the iterators.
*/
abstract boolean executeAndCompare(ListIterator<E> reference, T target);
@Override public String toString() {
return toString;
}
}
Stimulus<E, Iterator<E>> hasNext = new Stimulus<E, Iterator<E>>("hasNext") {
@Override boolean
executeAndCompare(ListIterator<E> reference, Iterator<E> target) {
// return only if both are true or both are false
assertEquals(reference.hasNext(), target.hasNext());
return false;
}
};
Stimulus<E, Iterator<E>> next = new Stimulus<E, Iterator<E>>("next") {
@Override boolean
executeAndCompare(ListIterator<E> reference, Iterator<E> target) {
return internalExecuteAndCompare(reference, target, NEXT_METHOD);
}
};
Stimulus<E, Iterator<E>> remove = new Stimulus<E, Iterator<E>>("remove") {
@Override boolean
executeAndCompare(ListIterator<E> reference, Iterator<E> target) {
return internalExecuteAndCompare(reference, target, REMOVE_METHOD);
}
};
@SuppressWarnings("unchecked")
List<Stimulus<E, Iterator<E>>> iteratorStimuli() {
return Arrays.asList(hasNext, next, remove);
}
Stimulus<E, ListIterator<E>> hasPrevious =
new Stimulus<E, ListIterator<E>>("hasPrevious") {
@Override boolean executeAndCompare(
ListIterator<E> reference, ListIterator<E> target) {
// return only if both are true or both are false
assertEquals(reference.hasPrevious(), target.hasPrevious());
return false;
}
};
Stimulus<E, ListIterator<E>> nextIndex =
new Stimulus<E, ListIterator<E>>("nextIndex") {
@Override boolean executeAndCompare(
ListIterator<E> reference, ListIterator<E> target) {
assertEquals(reference.nextIndex(), target.nextIndex());
return false;
}
};
Stimulus<E, ListIterator<E>> previousIndex =
new Stimulus<E, ListIterator<E>>("previousIndex") {
@Override boolean executeAndCompare(
ListIterator<E> reference, ListIterator<E> target) {
assertEquals(reference.previousIndex(), target.previousIndex());
return false;
}
};
Stimulus<E, ListIterator<E>> previous =
new Stimulus<E, ListIterator<E>>("previous") {
@Override boolean executeAndCompare(
ListIterator<E> reference, ListIterator<E> target) {
return internalExecuteAndCompare(reference, target, PREVIOUS_METHOD);
}
};
Stimulus<E, ListIterator<E>> add = new Stimulus<E, ListIterator<E>>("add") {
@Override boolean executeAndCompare(
ListIterator<E> reference, ListIterator<E> target) {
return internalExecuteAndCompare(reference, target, newAddMethod());
}
};
Stimulus<E, ListIterator<E>> set = new Stimulus<E, ListIterator<E>>("set") {
@Override boolean executeAndCompare(
ListIterator<E> reference, ListIterator<E> target) {
return internalExecuteAndCompare(reference, target, newSetMethod());
}
};
@SuppressWarnings("unchecked")
List<Stimulus<E, ListIterator<E>>> listIteratorStimuli() {
return Arrays.asList(
hasPrevious, nextIndex, previousIndex, previous, add, set);
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java | Java | asf20 | 23,220 |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEY_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUE_QUERIES;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.testing.AbstractMapTester;
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.MapFeature;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
/**
* Tests {@link java.util.Map#entrySet}.
*
* @author Louis Wasserman
* @param <K> The key type of the map implementation under test.
* @param <V> The value type of the map implementation under test.
*/
@GwtCompatible
public class MapEntrySetTester<K, V> extends AbstractMapTester<K, V> {
private enum IncomparableType {
INSTANCE;
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE)
public void testEntrySetIteratorRemove() {
Set<Entry<K, V>> entrySet = getMap().entrySet();
Iterator<Entry<K, V>> entryItr = entrySet.iterator();
assertEquals(samples.e0, entryItr.next());
entryItr.remove();
assertTrue(getMap().isEmpty());
assertFalse(entrySet.contains(samples.e0));
}
public void testContainsEntryWithIncomparableKey() {
assertFalse(getMap()
.entrySet().contains(Helpers.mapEntry(IncomparableType.INSTANCE, samples.e0.getValue())));
}
public void testContainsEntryWithIncomparableValue() {
assertFalse(getMap()
.entrySet().contains(Helpers.mapEntry(samples.e0.getKey(), IncomparableType.INSTANCE)));
}
@MapFeature.Require(ALLOWS_NULL_KEY_QUERIES)
public void testContainsEntryWithNullKeyAbsent() {
assertFalse(getMap()
.entrySet().contains(Helpers.mapEntry(null, samples.e0.getValue())));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_KEYS)
public void testContainsEntryWithNullKeyPresent() {
initMapWithNullKey();
assertTrue(getMap()
.entrySet().contains(Helpers.mapEntry(null, getValueForNullKey())));
}
@MapFeature.Require(ALLOWS_NULL_VALUE_QUERIES)
public void testContainsEntryWithNullValueAbsent() {
assertFalse(getMap()
.entrySet().contains(Helpers.mapEntry(samples.e0.getKey(), null)));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_VALUES)
public void testContainsEntryWithNullValuePresent() {
initMapWithNullValue();
assertTrue(getMap()
.entrySet().contains(Helpers.mapEntry(getKeyForNullValue(), null)));
}
@GwtIncompatible("reflection")
public static Method getContainsEntryWithIncomparableKeyMethod() {
return Helpers.getMethod(MapEntrySetTester.class, "testContainsEntryWithIncomparableKey");
}
@GwtIncompatible("reflection")
public static Method getContainsEntryWithIncomparableValueMethod() {
return Helpers.getMethod(MapEntrySetTester.class, "testContainsEntryWithIncomparableValue");
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/testers/MapEntrySetTester.java | Java | asf20 | 4,299 |
/*
* 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.testers;
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 static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.NavigableMap;
/**
* A generic JUnit test which tests operations on a NavigableMap. Can't be
* invoked directly; please see {@code NavigableMapTestSuiteBuilder}.
*
* @author Jesse Wilson
* @author Louis Wasserman
*/
public class NavigableMapNavigationTester<K, V> extends AbstractMapTester<K, V> {
private NavigableMap<K, V> navigableMap;
private List<Entry<K, V>> entries;
private Entry<K, V> a;
private Entry<K, V> b;
private Entry<K, V> c;
@Override public void setUp() throws Exception {
super.setUp();
navigableMap = (NavigableMap<K, V>) getMap();
entries = Helpers.copyToList(getSubjectGenerator().getSampleElements(
getSubjectGenerator().getCollectionSize().getNumElements()));
Collections.sort(entries, Helpers.<K, V>entryComparator(navigableMap.comparator()));
// some tests assume SEVERAL == 3
if (entries.size() >= 1) {
a = entries.get(0);
if (entries.size() >= 3) {
b = entries.get(1);
c = entries.get(2);
}
}
}
/**
* Resets the contents of navigableMap to have entries a, c, for the
* navigation tests.
*/
@SuppressWarnings("unchecked") // Needed to stop Eclipse whining
private void resetWithHole() {
Entry<K, V>[] entries = new Entry[] {a, c};
super.resetMap(entries);
navigableMap = (NavigableMap<K, V>) getMap();
}
@CollectionSize.Require(ZERO)
public void testEmptyMapFirst() {
assertNull(navigableMap.firstEntry());
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ZERO)
public void testEmptyMapPollFirst() {
assertNull(navigableMap.pollFirstEntry());
}
@CollectionSize.Require(ZERO)
public void testEmptyMapNearby() {
assertNull(navigableMap.lowerEntry(samples.e0.getKey()));
assertNull(navigableMap.lowerKey(samples.e0.getKey()));
assertNull(navigableMap.floorEntry(samples.e0.getKey()));
assertNull(navigableMap.floorKey(samples.e0.getKey()));
assertNull(navigableMap.ceilingEntry(samples.e0.getKey()));
assertNull(navigableMap.ceilingKey(samples.e0.getKey()));
assertNull(navigableMap.higherEntry(samples.e0.getKey()));
assertNull(navigableMap.higherKey(samples.e0.getKey()));
}
@CollectionSize.Require(ZERO)
public void testEmptyMapLast() {
assertNull(navigableMap.lastEntry());
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ZERO)
public void testEmptyMapPollLast() {
assertNull(navigableMap.pollLastEntry());
}
@CollectionSize.Require(ONE)
public void testSingletonMapFirst() {
assertEquals(a, navigableMap.firstEntry());
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ONE)
public void testSingletonMapPollFirst() {
assertEquals(a, navigableMap.pollFirstEntry());
assertTrue(navigableMap.isEmpty());
}
@CollectionSize.Require(ONE)
public void testSingletonMapNearby() {
assertNull(navigableMap.lowerEntry(samples.e0.getKey()));
assertNull(navigableMap.lowerKey(samples.e0.getKey()));
assertEquals(a, navigableMap.floorEntry(samples.e0.getKey()));
assertEquals(a.getKey(), navigableMap.floorKey(samples.e0.getKey()));
assertEquals(a, navigableMap.ceilingEntry(samples.e0.getKey()));
assertEquals(a.getKey(), navigableMap.ceilingKey(samples.e0.getKey()));
assertNull(navigableMap.higherEntry(samples.e0.getKey()));
assertNull(navigableMap.higherKey(samples.e0.getKey()));
}
@CollectionSize.Require(ONE)
public void testSingletonMapLast() {
assertEquals(a, navigableMap.lastEntry());
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ONE)
public void testSingletonMapPollLast() {
assertEquals(a, navigableMap.pollLastEntry());
assertTrue(navigableMap.isEmpty());
}
@CollectionSize.Require(SEVERAL)
public void testFirst() {
assertEquals(a, navigableMap.firstEntry());
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testPollFirst() {
assertEquals(a, navigableMap.pollFirstEntry());
assertEquals(entries.subList(1, entries.size()),
Helpers.copyToList(navigableMap.entrySet()));
}
@MapFeature.Require(absent = SUPPORTS_REMOVE)
public void testPollFirstUnsupported() {
try {
navigableMap.pollFirstEntry();
fail();
} catch (UnsupportedOperationException e) {
}
}
@CollectionSize.Require(SEVERAL)
public void testLower() {
resetWithHole();
assertEquals(null, navigableMap.lowerEntry(a.getKey()));
assertEquals(null, navigableMap.lowerKey(a.getKey()));
assertEquals(a, navigableMap.lowerEntry(b.getKey()));
assertEquals(a.getKey(), navigableMap.lowerKey(b.getKey()));
assertEquals(a, navigableMap.lowerEntry(c.getKey()));
assertEquals(a.getKey(), navigableMap.lowerKey(c.getKey()));
}
@CollectionSize.Require(SEVERAL)
public void testFloor() {
resetWithHole();
assertEquals(a, navigableMap.floorEntry(a.getKey()));
assertEquals(a.getKey(), navigableMap.floorKey(a.getKey()));
assertEquals(a, navigableMap.floorEntry(b.getKey()));
assertEquals(a.getKey(), navigableMap.floorKey(b.getKey()));
assertEquals(c, navigableMap.floorEntry(c.getKey()));
assertEquals(c.getKey(), navigableMap.floorKey(c.getKey()));
}
@CollectionSize.Require(SEVERAL)
public void testCeiling() {
resetWithHole();
assertEquals(a, navigableMap.ceilingEntry(a.getKey()));
assertEquals(a.getKey(), navigableMap.ceilingKey(a.getKey()));
assertEquals(c, navigableMap.ceilingEntry(b.getKey()));
assertEquals(c.getKey(), navigableMap.ceilingKey(b.getKey()));
assertEquals(c, navigableMap.ceilingEntry(c.getKey()));
assertEquals(c.getKey(), navigableMap.ceilingKey(c.getKey()));
}
@CollectionSize.Require(SEVERAL)
public void testHigher() {
resetWithHole();
assertEquals(c, navigableMap.higherEntry(a.getKey()));
assertEquals(c.getKey(), navigableMap.higherKey(a.getKey()));
assertEquals(c, navigableMap.higherEntry(b.getKey()));
assertEquals(c.getKey(), navigableMap.higherKey(b.getKey()));
assertEquals(null, navigableMap.higherEntry(c.getKey()));
assertEquals(null, navigableMap.higherKey(c.getKey()));
}
@CollectionSize.Require(SEVERAL)
public void testLast() {
assertEquals(c, navigableMap.lastEntry());
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testPollLast() {
assertEquals(c, navigableMap.pollLastEntry());
assertEquals(entries.subList(0, entries.size() - 1),
Helpers.copyToList(navigableMap.entrySet()));
}
@MapFeature.Require(absent = SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testPollLastUnsupported() {
try {
navigableMap.pollLastEntry();
fail();
} catch (UnsupportedOperationException e) {
}
}
@CollectionSize.Require(SEVERAL)
public void testDescendingNavigation() {
List<Entry<K, V>> descending = new ArrayList<Entry<K, V>>();
for (Entry<K, V> entry : navigableMap.descendingMap().entrySet()) {
descending.add(entry);
}
Collections.reverse(descending);
assertEquals(entries, descending);
}
@CollectionSize.Require(absent = ZERO)
public void testHeadMapExclusive() {
assertFalse(navigableMap.headMap(a.getKey(), false).containsKey(a.getKey()));
}
@CollectionSize.Require(absent = ZERO)
public void testHeadMapInclusive() {
assertTrue(navigableMap.headMap(a.getKey(), true).containsKey(a.getKey()));
}
@CollectionSize.Require(absent = ZERO)
public void testTailMapExclusive() {
assertFalse(navigableMap.tailMap(a.getKey(), false).containsKey(a.getKey()));
}
@CollectionSize.Require(absent = ZERO)
public void testTailMapInclusive() {
assertTrue(navigableMap.tailMap(a.getKey(), true).containsKey(a.getKey()));
}
}
| zzhhhhh-aw4rwer | guava-testlib/src/com/google/common/collect/testing/testers/NavigableMapNavigationTester.java | Java | asf20 | 9,172 |