code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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();
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.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);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.TestCollectionGenerator;
/**
* Creates multisets, containing sample elements, to be tested.
*
* @author Jared Levy
*/
@GwtCompatible
public interface TestMultisetGenerator<E> extends TestCollectionGenerator<E> {
@Override
Multiset<E> create(Object... elements);
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import 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() {
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() {
assertTrue(multimap().putAll(sampleKeys().e3, Lists.newArrayList(sampleValues().e3, null)));
assertGet(sampleKeys().e3, sampleValues().e3, null);
}
@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);
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_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;
/**
* 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_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();
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.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();
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.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 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.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Tests for {@link Multimap#replaceValues(Object, Iterable)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapReplaceValuesTester<K, V>
extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@MapFeature.Require({SUPPORTS_PUT, SUPPORTS_REMOVE, ALLOWS_NULL_VALUES})
public void testReplaceValuesWithNullValue() {
int size = multimap().size();
K key = sampleKeys().e0;
@SuppressWarnings("unchecked")
List<V> values = Arrays.asList(sampleValues().e0, null, sampleValues().e3);
multimap().replaceValues(key, values);
assertGet(key, values);
}
@MapFeature.Require({SUPPORTS_PUT, SUPPORTS_REMOVE, ALLOWS_NULL_KEYS})
public void testReplaceValuesWithNullKey() {
int size = multimap().size();
K key = null;
@SuppressWarnings("unchecked")
List<V> values = Arrays.asList(sampleValues().e0, sampleValues().e2, sampleValues().e3);
multimap().replaceValues(key, values);
assertGet(key, values);
}
@MapFeature.Require({SUPPORTS_PUT, SUPPORTS_REMOVE})
public void testReplaceEmptyValues() {
int size = multimap().size();
K key = sampleKeys().e3;
@SuppressWarnings("unchecked")
List<V> values = Arrays.asList(sampleValues().e0, sampleValues().e2, sampleValues().e3);
multimap().replaceValues(key, values);
assertGet(key, values);
assertEquals(size + values.size(), multimap().size());
}
@MapFeature.Require({SUPPORTS_PUT, SUPPORTS_REMOVE})
public void testReplaceValuesWithEmpty() {
int size = multimap().size();
K key = sampleKeys().e0;
List<V> oldValues = new ArrayList<V>(multimap().get(key));
@SuppressWarnings("unchecked")
List<V> values = Collections.emptyList();
assertEquals(oldValues, new ArrayList<V>(multimap().replaceValues(key, values)));
assertGet(key);
assertEquals(size - oldValues.size(), multimap().size());
}
@MapFeature.Require({SUPPORTS_PUT, SUPPORTS_REMOVE})
public void testReplaceValuesWithDuplicates() {
int size = multimap().size();
K key = sampleKeys().e0;
List<V> oldValues = new ArrayList<V>(multimap().get(key));
List<V> values = Arrays.asList(
sampleValues().e0,
sampleValues().e3,
sampleValues().e0);
assertEquals(oldValues, new ArrayList<V>(multimap().replaceValues(key, values)));
assertEquals(
size - oldValues.size() + multimap().get(key).size(),
multimap().size());
assertTrue(multimap().get(key).containsAll(values));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({SUPPORTS_PUT, SUPPORTS_REMOVE})
public void testReplaceNonEmptyValues() {
List<K> keys = Helpers.copyToList(multimap().keySet());
@SuppressWarnings("unchecked")
List<V> values = Arrays.asList(sampleValues().e0, sampleValues().e2, sampleValues().e3);
for (K k : keys) {
resetContainer();
int size = multimap().size();
Collection<V> oldKeyValues = Helpers.copyToList(multimap().get(k));
multimap().replaceValues(k, values);
assertGet(k, values);
assertEquals(size + values.size() - oldKeyValues.size(), multimap().size());
}
}
@MapFeature.Require({SUPPORTS_PUT, SUPPORTS_REMOVE})
public void testReplaceValuesPropagatesToGet() {
K key = sampleKeys().e0;
Collection<V> getCollection = multimap().get(key);
@SuppressWarnings("unchecked")
List<V> values = Arrays.asList(sampleValues().e0, sampleValues().e2, sampleValues().e3);
multimap().replaceValues(key, values);
ASSERT.that(getCollection).has().exactly(
sampleValues().e0, sampleValues().e2, sampleValues().e3);
}
@MapFeature.Require(absent = SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testReplaceValuesRemoveNotSupported() {
List<V> values = Collections.singletonList(sampleValues().e3);
try {
multimap().replaceValues(sampleKeys().e0, values);
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {
// success
}
}
@MapFeature.Require(absent = SUPPORTS_PUT)
public void testReplaceValuesPutNotSupported() {
List<V> values = Collections.singletonList(sampleValues().e3);
try {
multimap().replaceValues(sampleKeys().e0, values);
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {
// success
}
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import 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 {};
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.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();
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import 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.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.Set;
/**
* Optional features of classes derived from {@code Multimap}.
*
* @author Louis Wasserman
*/
// Enum values use constructors with generic varargs.
@SuppressWarnings("unchecked")
@GwtCompatible
public enum MultimapFeature implements Feature<Multimap> {
VALUE_COLLECTIONS_SUPPORT_ITERATOR_REMOVE;
private final Set<Feature<? super Multimap>> implied;
MultimapFeature(Feature<? super Multimap> ... implied) {
this.implied = Helpers.copyToSet(implied);
}
@Override
public Set<Feature<? super Multimap>> getImpliedFeatures() {
return implied;
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@TesterAnnotation
public @interface Require {
public abstract MultimapFeature[] value() default {};
public abstract MultimapFeature[] absent() default {};
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.BiMap;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.SampleElements;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Implementation helper for {@link TestBiMapGenerator} for use with bimaps of
* strings.
*
* @author Chris Povirk
* @author Jared Levy
* @author George van den Driessche
* @author Louis Wasserman
*/
@GwtCompatible
public abstract class TestStringBiMapGenerator
implements TestBiMapGenerator<String, String> {
@Override
public SampleElements<Map.Entry<String, String>> samples() {
return new SampleElements<Map.Entry<String, String>>(
Helpers.mapEntry("one", "January"),
Helpers.mapEntry("two", "February"),
Helpers.mapEntry("three", "March"),
Helpers.mapEntry("four", "April"),
Helpers.mapEntry("five", "May")
);
}
@Override
public final BiMap<String, String> create(Object... entries) {
@SuppressWarnings("unchecked")
Entry<String, String>[] array = new Entry[entries.length];
int i = 0;
for (Object o : entries) {
@SuppressWarnings("unchecked")
Entry<String, String> e = (Entry<String, String>) o;
array[i++] = e;
}
return create(array);
}
protected abstract BiMap<String, String> create(
Entry<String, String>[] entries);
@Override
@SuppressWarnings("unchecked")
public final Entry<String, String>[] createArray(int length) {
return new Entry[length];
}
@Override
public final String[] createKeyArray(int length) {
return new String[length];
}
@Override
public final String[] createValueArray(int length) {
return new String[length];
}
/** Returns the original element list, unchanged. */
@Override
public Iterable<Entry<String, String>> order(
List<Entry<String, String>> insertionOrder) {
return insertionOrder;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import 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);
}
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import 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 {@code Multimap.toString()}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapToStringTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@CollectionSize.Require(ZERO)
public void testToStringEmpty() {
assertEquals("{}", multimap().toString());
}
@CollectionSize.Require(ONE)
public void testToStringSingleton() {
assertEquals("{" + sampleKeys().e0 + "=[" + sampleValues().e0 + "]}", multimap().toString());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_KEYS)
public void testToStringWithNullKey() {
initMultimapWithNullKey();
testToStringMatchesAsMap();
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_VALUES)
public void testToStringWithNullValue() {
initMultimapWithNullValue();
testToStringMatchesAsMap();
}
public void testToStringMatchesAsMap() {
assertEquals(multimap().asMap().toString(), multimap().toString());
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.testing.SerializableTester;
import java.util.Set;
/**
* A generic JUnit test which tests multiset-specific serialization. Can't be invoked directly;
* please see {@link com.google.common.collect.testing.MultisetTestSuiteBuilder}.
*
* @author Louis Wasserman
*/
@GwtCompatible // but no-op
public class MultisetSerializationTester<E> extends AbstractMultisetTester<E> {
@CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
public void testEntrySetSerialization() {
Set<Multiset.Entry<E>> expected = getMultiset().entrySet();
assertEquals(expected, SerializableTester.reserialize(expected));
}
@CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
public void testElementSetSerialization() {
Set<E> expected = getMultiset().elementSet();
assertEquals(expected, SerializableTester.reserialize(expected));
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.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.ALLOWS_NULL_QUERIES)) {
derivedFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES);
}
if (derivedFeatures.remove(MapFeature.SUPPORTS_REMOVE)) {
derivedFeatures.add(CollectionFeature.SUPPORTS_REMOVE);
}
return derivedFeatures;
}
static Set<Feature<?>> computeEntriesFeatures(
Set<Feature<?>> multimapFeatures) {
return computeDerivedCollectionFeatures(multimapFeatures);
}
static Set<Feature<?>> computeValuesFeatures(
Set<Feature<?>> multimapFeatures) {
return computeDerivedCollectionFeatures(multimapFeatures);
}
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);
}
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.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_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);
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
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_QUERIES})
public void testRemoveNullKeyAbsent() {
assertFalse(multimap().remove(null, sampleValues().e0));
expectUnchanged();
}
@MapFeature.Require({ SUPPORTS_REMOVE, ALLOWS_NULL_QUERIES})
public void testRemoveNullValueAbsent() {
assertFalse(multimap().remove(sampleKeys().e0, null));
expectUnchanged();
}
@MapFeature.Require(value = SUPPORTS_REMOVE, absent = ALLOWS_NULL_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_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));
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.BiMap;
import com.google.common.collect.testing.features.MapFeature;
/**
* Tester for {@code BiMap.clear}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class BiMapClearTester<K, V> extends AbstractBiMapTester<K, V> {
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearClearsInverse() {
BiMap<V, K> inv = getMap().inverse();
getMap().clear();
assertTrue(getMap().isEmpty());
assertTrue(inv.isEmpty());
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testKeySetClearClearsInverse() {
BiMap<V, K> inv = getMap().inverse();
getMap().keySet().clear();
assertTrue(getMap().isEmpty());
assertTrue(inv.isEmpty());
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testValuesClearClearsInverse() {
BiMap<V, K> inv = getMap().inverse();
getMap().values().clear();
assertTrue(getMap().isEmpty());
assertTrue(inv.isEmpty());
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearInverseClears() {
BiMap<V, K> inv = getMap().inverse();
inv.clear();
assertTrue(getMap().isEmpty());
assertTrue(inv.isEmpty());
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearInverseKeySetClears() {
BiMap<V, K> inv = getMap().inverse();
inv.keySet().clear();
assertTrue(getMap().isEmpty());
assertTrue(inv.isEmpty());
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearInverseValuesClears() {
BiMap<V, K> inv = getMap().inverse();
inv.values().clear();
assertTrue(getMap().isEmpty());
assertTrue(inv.isEmpty());
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import java.util.Arrays;
import java.util.Collections;
/**
* Tests for {@code Multiset.add}.
*
* @author Jared Levy
*/
@GwtCompatible
public class MultisetAddTester<E> extends AbstractMultisetTester<E> {
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testAddUnsupported() {
try {
getMultiset().add(samples.e0);
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {}
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddMeansAddOne() {
int originalCount = getMultiset().count(samples.e0);
assertTrue(getMultiset().add(samples.e0));
assertEquals(originalCount + 1, getMultiset().count(samples.e0));
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddOccurrencesZero() {
int originalCount = getMultiset().count(samples.e0);
assertEquals("old count", originalCount, getMultiset().add(samples.e0, 0));
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddOccurrences() {
int originalCount = getMultiset().count(samples.e0);
assertEquals("old count", originalCount, getMultiset().add(samples.e0, 2));
assertEquals("old count", originalCount + 2, getMultiset().count(samples.e0));
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddSeveralTimes() {
int originalCount = getMultiset().count(samples.e0);
assertEquals(originalCount, getMultiset().add(samples.e0, 2));
assertTrue(getMultiset().add(samples.e0));
assertEquals(originalCount + 3, getMultiset().add(samples.e0, 1));
assertEquals(originalCount + 4, getMultiset().count(samples.e0));
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testAddOccurrences_unsupported() {
try {
getMultiset().add(samples.e0, 2);
fail("unsupported multiset.add(E, int) didn't throw exception");
} catch (UnsupportedOperationException required) {}
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddOccurrencesNegative() {
try {
getMultiset().add(samples.e0, -1);
fail("multiset.add(E, -1) didn't throw an exception");
} catch (IllegalArgumentException required) {}
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddTooMany() {
getMultiset().add(samples.e3, Integer.MAX_VALUE);
try {
getMultiset().add(samples.e3);
fail();
} catch (IllegalArgumentException expected) {}
assertEquals(Integer.MAX_VALUE, getMultiset().count(samples.e3));
assertEquals(Integer.MAX_VALUE, getMultiset().size());
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddAll_emptySet() {
assertFalse(getMultiset().addAll(Collections.<E>emptySet()));
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddAll_emptyMultiset() {
assertFalse(getMultiset().addAll(getSubjectGenerator().create()));
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddAll_nonEmptyList() {
assertTrue(getMultiset().addAll(Arrays.asList(samples.e3, samples.e4, samples.e3)));
expectAdded(samples.e3, samples.e4, samples.e3);
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddAll_nonEmptyMultiset() {
assertTrue(getMultiset().addAll(
getSubjectGenerator().create(samples.e3, samples.e4, samples.e3)));
expectAdded(samples.e3, samples.e4, samples.e3);
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.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);
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.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);
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ListMultimap;
import java.util.Arrays;
import java.util.Collection;
/**
* Superclass for all {@code ListMultimap} testers.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class AbstractListMultimapTester<K, V>
extends AbstractMultimapTester<K, V, ListMultimap<K, V>> {
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).inOrder();
if (!values.isEmpty()) {
ASSERT.that(multimap().asMap().get(key)).has().exactlyAs(values).inOrder();
assertFalse(multimap().isEmpty());
} else {
ASSERT.that(multimap().asMap().get(key)).isNull();
}
assertEquals(values.size(), multimap().get(key).size());
assertEquals(values.size() > 0, multimap().containsKey(key));
assertEquals(values.size() > 0, multimap().keySet().contains(key));
assertEquals(values.size() > 0, multimap().keys().contains(key));
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.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);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.testing.Helpers.mapEntry;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Ordering;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestListGenerator;
import com.google.common.collect.testing.TestStringListGenerator;
import com.google.common.collect.testing.TestStringSortedMapGenerator;
import java.util.List;
import java.util.Map.Entry;
import java.util.SortedMap;
/**
* Generators of sorted maps and derived collections.
*
* @author Kevin Bourrillion
* @author Jesse Wilson
* @author Jared Levy
* @author Hayward Chan
* @author Chris Povirk
* @author Louis Wasserman
*/
@GwtCompatible
public class SortedMapGenerators {
public static class ImmutableSortedMapGenerator extends TestStringSortedMapGenerator {
@Override public SortedMap<String, String> create(Entry<String, String>[] entries) {
ImmutableSortedMap.Builder<String, String> builder = ImmutableSortedMap.naturalOrder();
for (Entry<String, String> entry : entries) {
checkNotNull(entry);
builder.put(entry.getKey(), entry.getValue());
}
return builder.build();
}
}
public static class ImmutableSortedMapEntryListGenerator
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 new Ordering<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> left, Entry<String, Integer> right) {
return left.getKey().compareTo(right.getKey());
}
}.sortedCopy(insertionOrder);
}
@Override
public List<Entry<String, Integer>> create(Object... elements) {
ImmutableSortedMap.Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
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 ImmutableSortedMapKeyListGenerator extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
ImmutableSortedMap.Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
for (int i = 0; i < elements.length; i++) {
builder.put(elements[i], i);
}
return builder.build().keySet().asList();
}
@Override
public List<String> order(List<String> insertionOrder) {
return Ordering.natural().sortedCopy(insertionOrder);
}
}
public static class ImmutableSortedMapValueListGenerator extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
ImmutableSortedMap.Builder<Integer, String> builder = ImmutableSortedMap.naturalOrder();
for (int i = 0; i < elements.length; i++) {
builder.put(i, elements[i]);
}
return builder.build().values().asList();
}
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.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_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_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);
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
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 SetMultimap#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 SetMultimapAsMapTester<K, V> extends AbstractMultimapTester<K, V, SetMultimap<K, V>> {
public void testAsMapValuesImplementSet() {
for (Collection<V> valueCollection : multimap().asMap().values()) {
assertTrue(valueCollection instanceof Set);
}
}
public void testAsMapGetImplementsSet() {
for (K key : multimap().keySet()) {
assertTrue(multimap().asMap().get(key) instanceof Set);
}
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testAsMapRemoveImplementsSet() {
List<K> keys = new ArrayList<K>(multimap().keySet());
for (K key : keys) {
resetCollection();
assertTrue(multimap().asMap().remove(key) instanceof Set);
}
}
@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, Sets.newHashSet(sampleValues().e0, sampleValues().e3));
expected.put(sampleKeys().e1, Sets.newHashSet(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>) Sets.newHashSet(sampleValues().e0, sampleValues().e3)));
expected.add(Helpers.mapEntry(
sampleKeys().e1,
(Collection<V>) Sets.newHashSet(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.singleton(sampleValues().e0)));
assertEquals(2, multimap().size());
assertEquals(
Collections.singletonMap(
sampleKeys().e0, Sets.newHashSet(sampleValues().e0, sampleValues().e3)),
multimap().asMap());
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.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_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_QUERIES)
public void testAsMapGetNullKeyAbsent() {
ASSERT.that(multimap().asMap().get(null)).isNull();
}
@MapFeature.Require(absent = ALLOWS_NULL_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());
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.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());
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.BiMap;
import com.google.common.collect.testing.TestContainerGenerator;
import java.util.Map;
/**
* Creates bimaps, containing sample entries, to be tested.
*
* @author Louis Wasserman
*/
@GwtCompatible
public interface TestBiMapGenerator<K, V>
extends TestContainerGenerator<BiMap<K, V>, Map.Entry<K, V>> {
K[] createKeyArray(int length);
V[] createValueArray(int length);
}
| Java |
/*
* Copyright (C) 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);
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.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.ImmutableList;
import com.google.common.collect.Lists;
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;
/**
* Tester for {@link Multimap#put}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapPutTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@MapFeature.Require(absent = SUPPORTS_PUT)
public void testPutUnsupported() {
try {
multimap().put(sampleKeys().e3, sampleValues().e3);
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {}
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutEmpty() {
int size = getNumElements();
K key = sampleKeys().e3;
V value = sampleValues().e3;
assertGet(key, ImmutableList.<V>of());
assertTrue(multimap().put(key, value));
assertGet(key, value);
assertEquals(size + 1, multimap().size());
}
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPutPresent() {
int size = getNumElements();
K key = sampleKeys().e0;
V oldValue = sampleValues().e0;
V newValue = sampleValues().e3;
assertGet(key, oldValue);
assertTrue(multimap().put(key, newValue));
assertGet(key, oldValue, newValue);
assertEquals(size + 1, multimap().size());
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutTwoElements() {
int size = getNumElements();
K key = sampleKeys().e0;
V v1 = sampleValues().e3;
V v2 = sampleValues().e4;
List<V> values = Helpers.copyToList(multimap().get(key));
assertTrue(multimap().put(key, v1));
assertTrue(multimap().put(key, v2));
values.add(v1);
values.add(v2);
assertGet(key, values);
assertEquals(size + 2, multimap().size());
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
public void testPutNullValue() {
int size = getNumElements();
multimap().put(sampleKeys().e3, null);
assertGet(sampleKeys().e3, Lists.newArrayList((V)null)); // ImmutableList.of can't take null.
assertEquals(size + 1, multimap().size());
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS})
public void testPutNullKey() {
int size = getNumElements();
multimap().put(null, sampleValues().e3);
assertGet(null, sampleValues().e3);
assertEquals(size + 1, multimap().size());
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutNotPresentKeyPropagatesToGet() {
int size = getNumElements();
Collection<V> collection = multimap().get(sampleKeys().e3);
ASSERT.that(collection).isEmpty();
multimap().put(sampleKeys().e3, sampleValues().e3);
ASSERT.that(collection).has().item(sampleValues().e3);
assertEquals(size + 1, multimap().size());
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutNotPresentKeyPropagatesToEntries() {
Collection<Entry<K, V>> entries = multimap().entries();
assertFalse(entries.contains(Helpers.mapEntry(sampleKeys().e3, sampleValues().e3)));
multimap().put(sampleKeys().e3, sampleValues().e3);
ASSERT.that(entries).has().allOf(Helpers.mapEntry(sampleKeys().e3, sampleValues().e3));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_PUT)
public void testPutPresentKeyPropagatesToEntries() {
Collection<Entry<K, V>> entries = multimap().entries();
assertFalse(entries.contains(Helpers.mapEntry(sampleKeys().e0, sampleValues().e3)));
multimap().put(sampleKeys().e0, sampleValues().e3);
ASSERT.that(entries).has().allOf(Helpers.mapEntry(sampleKeys().e0, sampleValues().e3));
}
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPutPresentKeyPropagatesToGet() {
List<K> keys = Helpers.copyToList(multimap().keySet());
for (K key : keys) {
resetContainer();
int size = getNumElements();
Collection<V> collection = multimap().get(key);
Collection<V> expectedCollection = Helpers.copyToList(collection);
multimap().put(key, sampleValues().e3);
expectedCollection.add(sampleValues().e3);
ASSERT.that(collection).has().exactlyAs(expectedCollection);
assertEquals(size + 1, multimap().size());
}
}
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPutPresentKeyPropagatesToAsMapGet() {
List<K> keys = Helpers.copyToList(multimap().keySet());
for (K key : keys) {
resetContainer();
int size = getNumElements();
Collection<V> collection = multimap().asMap().get(key);
assertNotNull(collection);
Collection<V> expectedCollection = Helpers.copyToList(collection);
multimap().put(key, sampleValues().e3);
expectedCollection.add(sampleValues().e3);
ASSERT.that(collection).has().exactlyAs(expectedCollection);
assertEquals(size + 1, multimap().size());
}
}
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPutPresentKeyPropagatesToAsMapEntrySet() {
List<K> keys = Helpers.copyToList(multimap().keySet());
for (K key : keys) {
resetContainer();
int size = getNumElements();
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().put(key, sampleValues().e3);
expectedCollection.add(sampleValues().e3);
ASSERT.that(collection).has().exactlyAs(expectedCollection);
assertEquals(size + 1, multimap().size());
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.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"));
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.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_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_QUERIES)
public void testGetNullAbsent() {
ASSERT.that(multimap().get(null)).isEmpty();
}
@MapFeature.Require(absent = ALLOWS_NULL_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);
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.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());
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_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);
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.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());
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
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_QUERIES)
public void testContainsNullValueNo() {
assertFalse(multimap().containsValue(null));
}
@MapFeature.Require(absent = ALLOWS_NULL_QUERIES)
public void testContainsNullValueFails() {
try {
multimap().containsValue(null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
/**
* A generic JUnit test which tests unconditional {@code setCount()} operations
* on a multiset. Can't be invoked directly; please see
* {@link MultisetTestSuiteBuilder}.
*
* @author Chris Povirk
*/
@GwtCompatible
public class MultisetSetCountUnconditionallyTester<E>
extends AbstractMultisetSetCountTester<E> {
@Override void setCountCheckReturnValue(E element, int count) {
assertEquals("multiset.setCount() should return the old count",
getMultiset().count(element), setCount(element, count));
}
@Override void setCountNoCheckReturnValue(E element, int count) {
setCount(element, count);
}
private int setCount(E element, int count) {
return getMultiset().setCount(element, count);
}
}
| Java |
/*
* Copyright (C) 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());
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.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();
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.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_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
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_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_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());
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.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_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_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));
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.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.SortedSetTestSuiteBuilder;
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.Entry;
import java.util.Set;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a {@code SortedSetMultimap} implementation.
*
* @author Louis Wasserman
*/
public class SortedSetMultimapTestSuiteBuilder<K, V>
extends MultimapTestSuiteBuilder<K, V, SetMultimap<K, V>> {
public static <K, V> SortedSetMultimapTestSuiteBuilder<K, V> using(
TestSetMultimapGenerator<K, V> generator) {
SortedSetMultimapTestSuiteBuilder<K, V> result = new SortedSetMultimapTestSuiteBuilder<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);
testers.add(SortedSetMultimapAsMapTester.class);
testers.add(SortedSetMultimapGetTester.class);
return testers;
}
@Override
TestSuite computeMultimapGetTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<SetMultimap<K, V>, Entry<K, V>>> parentBuilder) {
return SortedSetTestSuiteBuilder.using(
new SetMultimapTestSuiteBuilder.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 SortedSetTestSuiteBuilder.using(
new SetMultimapTestSuiteBuilder.MultimapAsMapGetGenerator<K, V>(
parentBuilder.getSubjectGenerator()))
.withFeatures(features)
.named(parentBuilder.getName() + ".asMap[].get[key]")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.AbstractCollectionTester;
/**
* Base class for multiset collection tests.
*
* @author Jared Levy
*/
@GwtCompatible
public class AbstractMultisetTester<E> extends AbstractCollectionTester<E> {
protected final Multiset<E> getMultiset() {
return (Multiset<E>) collection;
}
protected void initThreeCopies() {
collection =
getSubjectGenerator().create(samples.e0, samples.e0, samples.e0);
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
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_QUERIES)
public void testContainsEntryNullNo() {
assertFalse(multimap().containsEntry(null, null));
}
@MapFeature.Require(absent = ALLOWS_NULL_QUERIES)
public void testContainsEntryNullDisallowed() {
try {
multimap().containsEntry(null, null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
/**
* Tester for {@code BiMap.put} and {@code BiMap.forcePut}.
*/
@GwtCompatible
public class BiMapPutTester<K, V> extends AbstractBiMapTester<K, V> {
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(ZERO)
public void testPutWithSameValueFails() {
K k0 = samples.e0.getKey();
K k1 = samples.e1.getKey();
V v0 = samples.e0.getValue();
getMap().put(k0, v0);
try {
getMap().put(k1, v0);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {
// success
}
// verify that the bimap is unchanged
expectAdded(samples.e0);
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(ZERO)
public void testPutPresentKeyDifferentValue() {
K k0 = samples.e0.getKey();
V v0 = samples.e0.getValue();
V v1 = samples.e1.getValue();
getMap().put(k0, v0);
getMap().put(k0, v1);
// verify that the bimap is changed, and that the old inverse mapping
// from v1 -> v0 is deleted
expectContents(Helpers.mapEntry(k0, v1));
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(ZERO)
public void putDistinctKeysDistinctValues() {
getMap().put(samples.e0.getKey(), samples.e0.getValue());
getMap().put(samples.e1.getKey(), samples.e1.getValue());
expectAdded(samples.e0, samples.e1);
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(ZERO)
public void testForcePutOverwritesOldValueEntry() {
K k0 = samples.e0.getKey();
K k1 = samples.e1.getKey();
V v0 = samples.e0.getValue();
getMap().put(k0, v0);
getMap().forcePut(k1, v0);
// verify that the bimap is unchanged
expectAdded(Helpers.mapEntry(k1, v0));
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(ZERO)
public void testInversePut() {
K k0 = samples.e0.getKey();
V v0 = samples.e0.getValue();
K k1 = samples.e1.getKey();
V v1 = samples.e1.getValue();
getMap().put(k0, v0);
getMap().inverse().put(v1, k1);
expectAdded(samples.e0, samples.e1);
}
}
| Java |
/*
* Copyright (C) 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);
}
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.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 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 com.google.common.testing.EqualsTester;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
/**
* Tester for {@code Multimap.equals}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapEqualsTester<K, V> extends AbstractMultimapTester<K, V, Multimap<K, V>> {
public void testEqualsTrue() {
new EqualsTester()
.addEqualityGroup(multimap(), getSubjectGenerator().create(getSampleElements().toArray()))
.testEquals();
}
public void testEqualsFalse() {
List<Entry<K, V>> targetEntries = new ArrayList<Entry<K, V>>(getSampleElements());
targetEntries.add(Helpers.mapEntry(sampleKeys().e0, sampleValues().e3));
new EqualsTester()
.addEqualityGroup(multimap())
.addEqualityGroup(getSubjectGenerator().create(targetEntries.toArray()))
.testEquals();
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_KEYS)
public void testEqualsMultimapWithNullKey() {
Multimap<K, V> original = multimap();
initMultimapWithNullKey();
Multimap<K, V> withNull = multimap();
new EqualsTester()
.addEqualityGroup(original)
.addEqualityGroup(withNull, getSubjectGenerator().create(createArrayWithNullKey()))
.testEquals();
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_VALUES)
public void testEqualsMultimapWithNullValue() {
Multimap<K, V> original = multimap();
initMultimapWithNullValue();
Multimap<K, V> withNull = multimap();
new EqualsTester()
.addEqualityGroup(original)
.addEqualityGroup(withNull, getSubjectGenerator().create(createArrayWithNullValue()))
.testEquals();
}
@CollectionSize.Require(absent = ZERO)
public void testNotEqualsEmpty() {
new EqualsTester()
.addEqualityGroup(multimap())
.addEqualityGroup(getSubjectGenerator().create())
.testEquals();
}
public void testHashCodeMatchesAsMap() {
assertEquals(multimap().asMap().hashCode(), multimap().hashCode());
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE;
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 static com.google.common.collect.testing.google.MultisetFeature.ENTRIES_ARE_VIEWS;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Collections;
import java.util.Iterator;
/**
* Tests for {@code Multiset.entrySet}.
*
* @author Jared Levy
*/
@GwtCompatible
public class MultisetEntrySetTester<E> extends AbstractMultisetTester<E> {
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_clear() {
getMultiset().entrySet().clear();
assertTrue("multiset not empty after entrySet().clear()",
getMultiset().isEmpty());
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE)
public void testEntrySet_iteratorRemovePropagates() {
Iterator<Multiset.Entry<E>> iterator = getMultiset().entrySet().iterator();
assertTrue(
"non-empty multiset.entrySet() iterator.hasNext() returned false",
iterator.hasNext());
assertEquals("multiset.entrySet() iterator.next() returned incorrect entry",
Multisets.immutableEntry(samples.e0, 1), iterator.next());
assertFalse(
"size 1 multiset.entrySet() iterator.hasNext() returned true "
+ "after next()",
iterator.hasNext());
iterator.remove();
assertTrue(
"multiset isn't empty after multiset.entrySet() iterator.remove()",
getMultiset().isEmpty());
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_removePresent() {
assertTrue(
"multiset.entrySet.remove(presentEntry) returned false",
getMultiset().entrySet().remove(
Multisets.immutableEntry(samples.e0, 1)));
assertFalse(
"multiset contains element after removing its entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_removeAbsent() {
assertFalse(
"multiset.entrySet.remove(missingEntry) returned true",
getMultiset().entrySet().remove(
Multisets.immutableEntry(samples.e0, 2)));
assertTrue(
"multiset didn't contain element after removing a missing entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_removeAllPresent() {
assertTrue(
"multiset.entrySet.removeAll(presentEntry) returned false",
getMultiset().entrySet().removeAll(
Collections.singleton(Multisets.immutableEntry(samples.e0, 1))));
assertFalse(
"multiset contains element after removing its entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_removeAllAbsent() {
assertFalse(
"multiset.entrySet.remove(missingEntry) returned true",
getMultiset().entrySet().removeAll(
Collections.singleton(Multisets.immutableEntry(samples.e0, 2))));
assertTrue(
"multiset didn't contain element after removing a missing entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_retainAllPresent() {
assertFalse(
"multiset.entrySet.retainAll(presentEntry) returned false",
getMultiset().entrySet().retainAll(
Collections.singleton(Multisets.immutableEntry(samples.e0, 1))));
assertTrue(
"multiset doesn't contains element after retaining its entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_retainAllAbsent() {
assertTrue(
"multiset.entrySet.retainAll(missingEntry) returned true",
getMultiset().entrySet().retainAll(
Collections.singleton(Multisets.immutableEntry(samples.e0, 2))));
assertFalse(
"multiset contains element after retaining a different entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
@MultisetFeature.Require(ENTRIES_ARE_VIEWS)
public void testEntryViewReflectsRemove() {
initThreeCopies();
assertEquals(3, getMultiset().count(samples.e0));
Multiset.Entry<E> entry = Iterables.getOnlyElement(getMultiset().entrySet());
assertEquals(3, entry.getCount());
assertTrue(getMultiset().remove(samples.e0));
assertEquals(2, entry.getCount());
assertTrue(getMultiset().elementSet().remove(samples.e0));
assertEquals(0, entry.getCount());
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE)
@MultisetFeature.Require(ENTRIES_ARE_VIEWS)
public void testEntryReflectsIteratorRemove() {
initThreeCopies();
assertEquals(3, getMultiset().count(samples.e0));
Multiset.Entry<E> entry = Iterables.getOnlyElement(getMultiset().entrySet());
assertEquals(3, entry.getCount());
Iterator<E> itr = getMultiset().iterator();
itr.next();
itr.remove();
assertEquals(2, entry.getCount());
itr.next();
itr.remove();
itr.next();
itr.remove();
assertEquals(0, entry.getCount());
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
@MultisetFeature.Require(ENTRIES_ARE_VIEWS)
public void testEntryReflectsClear() {
initThreeCopies();
assertEquals(3, getMultiset().count(samples.e0));
Multiset.Entry<E> entry = Iterables.getOnlyElement(getMultiset().entrySet());
assertEquals(3, entry.getCount());
getMultiset().clear();
assertEquals(0, entry.getCount());
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
@MultisetFeature.Require(ENTRIES_ARE_VIEWS)
public void testEntryReflectsEntrySetClear() {
initThreeCopies();
assertEquals(3, getMultiset().count(samples.e0));
Multiset.Entry<E> entry = Iterables.getOnlyElement(getMultiset().entrySet());
assertEquals(3, entry.getCount());
getMultiset().entrySet().clear();
assertEquals(0, entry.getCount());
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE)
@MultisetFeature.Require(ENTRIES_ARE_VIEWS)
public void testEntryReflectsEntrySetIteratorRemove() {
initThreeCopies();
assertEquals(3, getMultiset().count(samples.e0));
Iterator<Multiset.Entry<E>> entryItr = getMultiset().entrySet().iterator();
Multiset.Entry<E> entry = entryItr.next();
entryItr.remove();
assertEquals(0, entry.getCount());
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
@MultisetFeature.Require(ENTRIES_ARE_VIEWS)
public void testEntryReflectsElementSetClear() {
initThreeCopies();
assertEquals(3, getMultiset().count(samples.e0));
Multiset.Entry<E> entry = Iterables.getOnlyElement(getMultiset().entrySet());
assertEquals(3, entry.getCount());
getMultiset().elementSet().clear();
assertEquals(0, entry.getCount());
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE)
@MultisetFeature.Require(ENTRIES_ARE_VIEWS)
public void testEntryReflectsElementSetIteratorRemove() {
initThreeCopies();
assertEquals(3, getMultiset().count(samples.e0));
Multiset.Entry<E> entry = Iterables.getOnlyElement(getMultiset().entrySet());
assertEquals(3, entry.getCount());
Iterator<E> elementItr = getMultiset().elementSet().iterator();
elementItr.next();
elementItr.remove();
assertEquals(0, entry.getCount());
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require({SUPPORTS_REMOVE, SUPPORTS_ADD})
@MultisetFeature.Require(ENTRIES_ARE_VIEWS)
public void testEntryReflectsRemoveThenAdd() {
initThreeCopies();
assertEquals(3, getMultiset().count(samples.e0));
Multiset.Entry<E> entry = Iterables.getOnlyElement(getMultiset().entrySet());
assertEquals(3, entry.getCount());
assertTrue(getMultiset().remove(samples.e0));
assertEquals(2, entry.getCount());
assertTrue(getMultiset().elementSet().remove(samples.e0));
assertEquals(0, entry.getCount());
getMultiset().add(samples.e0, 2);
assertEquals(2, entry.getCount());
}
public void testToString() {
assertEquals(getMultiset().entrySet().toString(), getMultiset().toString());
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.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);
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static java.util.Arrays.asList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.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);
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.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);
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.collect.ListMultimap;
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.ListTestSuiteBuilder;
import com.google.common.collect.testing.OneSizeTestContainerGenerator;
import com.google.common.collect.testing.TestListGenerator;
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 junit.framework.TestSuite;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a {@code ListMultimap} implementation.
*
* @author Louis Wasserman
*/
public class ListMultimapTestSuiteBuilder<K, V> extends
MultimapTestSuiteBuilder<K, V, ListMultimap<K, V>> {
public static <K, V> ListMultimapTestSuiteBuilder<K, V> using(
TestListMultimapGenerator<K, V> generator) {
ListMultimapTestSuiteBuilder<K, V> result = new ListMultimapTestSuiteBuilder<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(ListMultimapAsMapTester.class);
testers.add(ListMultimapEqualsTester.class);
testers.add(ListMultimapPutTester.class);
testers.add(ListMultimapPutAllTester.class);
testers.add(ListMultimapRemoveTester.class);
testers.add(ListMultimapReplaceValuesTester.class);
return testers;
}
@Override
TestSuite computeMultimapGetTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<ListMultimap<K, V>, Entry<K, V>>> parentBuilder) {
return ListTestSuiteBuilder.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<ListMultimap<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 ListTestSuiteBuilder.using(
new MultimapAsMapGetGenerator<K, V>(parentBuilder.getSubjectGenerator()))
.withFeatures(features)
.named(parentBuilder.getName() + ".asMap[].get[key]")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
}
@Override
Set<Feature<?>> computeMultimapGetFeatures(
Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> derivedFeatures = super.computeMultimapGetFeatures(multimapFeatures);
if (derivedFeatures.contains(CollectionFeature.SUPPORTS_ADD)) {
derivedFeatures.add(ListFeature.SUPPORTS_ADD_WITH_INDEX);
}
if (derivedFeatures.contains(CollectionFeature.GENERAL_PURPOSE)) {
derivedFeatures.add(ListFeature.GENERAL_PURPOSE);
}
return derivedFeatures;
}
private static class MultimapGetGenerator<K, V>
extends MultimapTestSuiteBuilder.MultimapGetGenerator<K, V, ListMultimap<K, V>>
implements TestListGenerator<V> {
public MultimapGetGenerator(
OneSizeTestContainerGenerator<ListMultimap<K, V>, Entry<K, V>> multimapGenerator) {
super(multimapGenerator);
}
@Override
public List<V> create(Object... elements) {
return (List<V>) super.create(elements);
}
}
private static class MultimapAsMapGetGenerator<K, V>
extends MultimapTestSuiteBuilder.MultimapAsMapGetGenerator<K, V, ListMultimap<K, V>>
implements TestListGenerator<V> {
public MultimapAsMapGetGenerator(
OneSizeTestContainerGenerator<ListMultimap<K, V>, Entry<K, V>> multimapGenerator) {
super(multimapGenerator);
}
@Override
public List<V> create(Object... elements) {
return (List<V>) super.create(elements);
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.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());
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.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);
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.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();
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.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;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
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.features.CollectionSize;
import com.google.common.testing.EqualsTester;
/**
* Testers for {@link SetMultimap#equals(Object)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class SetMultimapEqualsTester<K, V>
extends AbstractMultimapTester<K, V, SetMultimap<K, V>> {
@CollectionSize.Require(SEVERAL)
public void testOrderingDoesntAffectEqualsComparisons() {
SetMultimap<K, V> multimap1 = getSubjectGenerator().create(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e1),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e4));
SetMultimap<K, V> multimap2 = getSubjectGenerator().create(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e1),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e4));
new EqualsTester()
.addEqualityGroup(multimap1, multimap2)
.testEquals();
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.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));
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.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_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.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_NULL_QUERIES })
public void testRemoveAllNullKeyAbsent() {
ASSERT.that(multimap().removeAll(null)).isEmpty();
expectUnchanged();
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.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);
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.AnEnum;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.SampleElements.Enums;
import java.util.Collections;
import java.util.List;
/**
* An abstract {@code TestMultisetGenerator} for generating multisets containing
* enum values.
*
* @author Jared Levy
*/
@GwtCompatible
public abstract class TestEnumMultisetGenerator
implements TestMultisetGenerator<AnEnum> {
@Override
public SampleElements<AnEnum> samples() {
return new Enums();
}
@Override
public Multiset<AnEnum> create(Object... elements) {
AnEnum[] array = new AnEnum[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (AnEnum) e;
}
return create(array);
}
protected abstract Multiset<AnEnum> create(AnEnum[] elements);
@Override
public AnEnum[] createArray(int length) {
return new AnEnum[length];
}
/**
* Sorts the enums according to their natural ordering.
*/
@Override
public List<AnEnum> order(List<AnEnum> insertionOrder) {
Collections.sort(insertionOrder);
return insertionOrder;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.SampleElements.Strings;
import java.util.List;
/**
* Create multisets of strings for tests.
*
* @author Jared Levy
*/
@GwtCompatible
public abstract class TestStringMultisetGenerator
implements TestMultisetGenerator<String>
{
@Override
public SampleElements<String> samples() {
return new Strings();
}
@Override
public Multiset<String> create(Object... elements) {
String[] array = new String[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (String) e;
}
return create(array);
}
protected abstract Multiset<String> create(String[] elements);
@Override
public String[] createArray(int length) {
return new String[length];
}
/** Returns the original element list, unchanged. */
@Override
public List<String> order(List<String> insertionOrder) {
return insertionOrder;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.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.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);
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.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());
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.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());
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.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;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.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>> {
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ListMultimap;
/**
* A generator for {@code ListMultimap} implementations based on test data.
*
* @author Louis Wasserman
*/
@GwtCompatible
public interface TestListMultimapGenerator<K, V>
extends TestMultimapGenerator<K, V, ListMultimap<K, V>> {
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.BiMap;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.Helpers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
/**
* Skeleton for a tester of a {@code BiMap}.
*/
@GwtCompatible
public abstract class AbstractBiMapTester<K, V> extends AbstractMapTester<K, V> {
@Override
protected BiMap<K, V> getMap() {
return (BiMap<K, V>) super.getMap();
}
static <K, V> Entry<V, K> reverseEntry(Entry<K, V> entry) {
return Helpers.mapEntry(entry.getValue(), entry.getKey());
}
@Override
protected void expectContents(Collection<Entry<K, V>> expected) {
super.expectContents(expected);
List<Entry<V, K>> reversedEntries = new ArrayList<Entry<V, K>>();
for (Entry<K, V> entry : expected) {
reversedEntries.add(reverseEntry(entry));
}
Helpers.assertEqualIgnoringOrder(getMap().inverse().entrySet(), reversedEntries);
for (Entry<K, V> entry : expected) {
assertEquals("Wrong key for value " + entry.getValue(), entry.getKey(), getMap()
.inverse()
.get(entry.getValue()));
}
}
@Override
protected void expectMissing(Entry<K, V>... entries) {
super.expectMissing(entries);
for (Entry<K, V> entry : entries) {
Entry<V, K> reversed = reverseEntry(entry);
BiMap<V, K> inv = getMap().inverse();
assertFalse("Inverse should not contain entry " + reversed,
inv.entrySet().contains(entry));
assertFalse("Inverse should not contain key " + entry.getValue(),
inv.containsKey(entry.getValue()));
assertFalse("Inverse should not contain value " + entry.getKey(),
inv.containsValue(entry.getKey()));
assertNull("Inverse should not return a mapping for key " + entry.getValue(),
getMap().get(entry.getValue()));
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY 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);
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;
import static junit.framework.TestCase.fail;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.LinkedHashMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
/**
* A series of tests that support asserting that collections cannot be
* modified, either through direct or indirect means.
*
* @author Robert Konigsberg
*/
@GwtCompatible
public class UnmodifiableCollectionTests {
public static void assertMapEntryIsUnmodifiable(Entry<?, ?> entry) {
try {
entry.setValue(null);
fail("setValue on unmodifiable Map.Entry succeeded");
} catch (UnsupportedOperationException expected) {
}
}
/**
* Verifies that an Iterator is unmodifiable.
*
* <p>This test only works with iterators that iterate over a finite set.
*/
public static void assertIteratorIsUnmodifiable(Iterator<?> iterator) {
while (iterator.hasNext()) {
iterator.next();
try {
iterator.remove();
fail("Remove on unmodifiable iterator succeeded");
} catch (UnsupportedOperationException expected) {
}
}
}
/**
* Asserts that two iterators contain elements in tandem.
*
* <p>This test only works with iterators that iterate over a finite set.
*/
public static void assertIteratorsInOrder(
Iterator<?> expectedIterator, Iterator<?> actualIterator) {
int i = 0;
while (expectedIterator.hasNext()) {
Object expected = expectedIterator.next();
assertTrue(
"index " + i + " expected <" + expected + "., actual is exhausted",
actualIterator.hasNext());
Object actual = actualIterator.next();
assertEquals("index " + i, expected, actual);
i++;
}
if (actualIterator.hasNext()) {
fail("index " + i
+ ", expected is exhausted, actual <" + actualIterator.next() + ">");
}
}
/**
* Verifies that a collection is immutable.
*
* <p>A collection is considered immutable if:
* <ol>
* <li>All its mutation methods result in UnsupportedOperationException, and
* do not change the underlying contents.
* <li>All methods that return objects that can indirectly mutate the
* collection throw UnsupportedOperationException when those mutators
* are called.
* </ol>
*
* @param collection the presumed-immutable collection
* @param sampleElement an element of the same type as that contained by
* {@code collection}. {@code collection} may or may not have {@code
* sampleElement} as a member.
*/
public static <E> void assertCollectionIsUnmodifiable(
Collection<E> collection, E sampleElement) {
Collection<E> siblingCollection = new ArrayList<E>();
siblingCollection.add(sampleElement);
Collection<E> copy = new ArrayList<E>();
copy.addAll(collection);
try {
collection.add(sampleElement);
fail("add succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(copy, collection);
try {
collection.addAll(siblingCollection);
fail("addAll succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(copy, collection);
try {
collection.clear();
fail("clear succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(copy, collection);
assertIteratorIsUnmodifiable(collection.iterator());
assertCollectionsAreEquivalent(copy, collection);
try {
collection.remove(sampleElement);
fail("remove succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(copy, collection);
try {
collection.removeAll(siblingCollection);
fail("removeAll succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(copy, collection);
try {
collection.retainAll(siblingCollection);
fail("retainAll succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(copy, collection);
}
/**
* Verifies that a set is immutable.
*
* <p>A set is considered immutable if:
* <ol>
* <li>All its mutation methods result in UnsupportedOperationException, and
* do not change the underlying contents.
* <li>All methods that return objects that can indirectly mutate the
* set throw UnsupportedOperationException when those mutators
* are called.
* </ol>
*
* @param set the presumed-immutable set
* @param sampleElement an element of the same type as that contained by
* {@code set}. {@code set} may or may not have {@code sampleElement} as a
* member.
*/
public static <E> void assertSetIsUnmodifiable(
Set<E> set, E sampleElement) {
assertCollectionIsUnmodifiable(set, sampleElement);
}
/**
* Verifies that a multiset is immutable.
*
* <p>A multiset is considered immutable if:
* <ol>
* <li>All its mutation methods result in UnsupportedOperationException, and
* do not change the underlying contents.
* <li>All methods that return objects that can indirectly mutate the
* multiset throw UnsupportedOperationException when those mutators
* are called.
* </ol>
*
* @param multiset the presumed-immutable multiset
* @param sampleElement an element of the same type as that contained by
* {@code multiset}. {@code multiset} may or may not have {@code
* sampleElement} as a member.
*/
public static <E> void assertMultisetIsUnmodifiable(Multiset<E> multiset,
final E sampleElement) {
Multiset<E> copy = LinkedHashMultiset.create(multiset);
assertCollectionsAreEquivalent(multiset, copy);
// Multiset is a collection, so we can use all those tests.
assertCollectionIsUnmodifiable(multiset, sampleElement);
assertCollectionsAreEquivalent(multiset, copy);
try {
multiset.add(sampleElement, 2);
fail("add(Object, int) succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(multiset, copy);
try {
multiset.remove(sampleElement, 2);
fail("remove(Object, int) succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(multiset, copy);
assertCollectionsAreEquivalent(multiset, copy);
assertSetIsUnmodifiable(multiset.elementSet(), sampleElement);
assertCollectionsAreEquivalent(multiset, copy);
assertSetIsUnmodifiable(
multiset.entrySet(), new Multiset.Entry<E>() {
@Override
public int getCount() {
return 1;
}
@Override
public E getElement() {
return sampleElement;
}
});
assertCollectionsAreEquivalent(multiset, copy);
}
/**
* Verifies that a multimap is immutable.
*
* <p>A multimap is considered immutable if:
* <ol>
* <li>All its mutation methods result in UnsupportedOperationException, and
* do not change the underlying contents.
* <li>All methods that return objects that can indirectly mutate the
* multimap throw UnsupportedOperationException when those mutators
* </ol>
*
* @param multimap the presumed-immutable multimap
* @param sampleKey a key of the same type as that contained by
* {@code multimap}. {@code multimap} may or may not have {@code sampleKey} as
* a key.
* @param sampleValue a key of the same type as that contained by
* {@code multimap}. {@code multimap} may or may not have {@code sampleValue}
* as a key.
*/
public static <K, V> void assertMultimapIsUnmodifiable(
Multimap<K, V> multimap, final K sampleKey, final V sampleValue) {
List<Entry<K, V>> originalEntries =
Collections.unmodifiableList(Lists.newArrayList(multimap.entries()));
assertMultimapRemainsUnmodified(multimap, originalEntries);
Collection<V> sampleValueAsCollection = Collections.singleton(sampleValue);
// Test #clear()
try {
multimap.clear();
fail("clear succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test asMap().entrySet()
assertSetIsUnmodifiable(
multimap.asMap().entrySet(),
Maps.immutableEntry(sampleKey, sampleValueAsCollection));
// Test #values()
assertMultimapRemainsUnmodified(multimap, originalEntries);
if (!multimap.isEmpty()) {
Collection<V> values =
multimap.asMap().entrySet().iterator().next().getValue();
assertCollectionIsUnmodifiable(values, sampleValue);
}
// Test #entries()
assertCollectionIsUnmodifiable(
multimap.entries(),
Maps.immutableEntry(sampleKey, sampleValue));
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Iterate over every element in the entry set
for (Entry<K, V> entry : multimap.entries()) {
assertMapEntryIsUnmodifiable(entry);
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #keys()
assertMultisetIsUnmodifiable(multimap.keys(), sampleKey);
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #keySet()
assertSetIsUnmodifiable(multimap.keySet(), sampleKey);
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #get()
if (!multimap.isEmpty()) {
K key = multimap.keySet().iterator().next();
assertCollectionIsUnmodifiable(multimap.get(key), sampleValue);
assertMultimapRemainsUnmodified(multimap, originalEntries);
}
// Test #put()
try {
multimap.put(sampleKey, sampleValue);
fail("put succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #putAll(K, Collection<V>)
try {
multimap.putAll(sampleKey, sampleValueAsCollection);
fail("putAll(K, Iterable) succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #putAll(Multimap<K, V>)
Multimap<K, V> multimap2 = ArrayListMultimap.create();
multimap2.put(sampleKey, sampleValue);
try {
multimap.putAll(multimap2);
fail("putAll(Multimap<K, V>) succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #remove()
try {
multimap.remove(sampleKey, sampleValue);
fail("remove succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #removeAll()
try {
multimap.removeAll(sampleKey);
fail("removeAll succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #replaceValues()
try {
multimap.replaceValues(sampleKey, sampleValueAsCollection);
fail("replaceValues succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #asMap()
try {
multimap.asMap().remove(sampleKey);
fail("asMap().remove() succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
if (!multimap.isEmpty()) {
K presentKey = multimap.keySet().iterator().next();
try {
multimap.asMap().get(presentKey).remove(sampleValue);
fail("asMap().get().remove() succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
try {
multimap.asMap().values().iterator().next().remove(sampleValue);
fail("asMap().values().iterator().next().remove() succeeded on " +
"unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
try {
((Collection<?>) multimap.asMap().values().toArray()[0]).clear();
fail("asMap().values().toArray()[0].clear() succeeded on " +
"unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
}
assertCollectionIsUnmodifiable(multimap.values(), sampleValue);
assertMultimapRemainsUnmodified(multimap, originalEntries);
}
private static <E> void assertCollectionsAreEquivalent(
Collection<E> expected, Collection<E> actual) {
assertIteratorsInOrder(expected.iterator(), actual.iterator());
}
private static <K, V> void assertMultimapRemainsUnmodified(
Multimap<K, V> expected, List<Entry<K, V>> actual) {
assertIteratorsInOrder(
expected.entries().iterator(), actual.iterator());
}
}
| Java |
/*
* Copyright (C) 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"));
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static java.util.Collections.nCopies;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests conditional {@code setCount()} operations on
* a multiset. Can't be invoked directly; please see
* {@link MultisetTestSuiteBuilder}.
*
* @author Chris Povirk
*/
@GwtCompatible
public class MultisetSetCountConditionallyTester<E> extends
AbstractMultisetSetCountTester<E> {
@Override void setCountCheckReturnValue(E element, int count) {
assertTrue(
"setCount() with the correct expected present count should return true",
setCount(element, count));
}
@Override void setCountNoCheckReturnValue(E element, int count) {
setCount(element, count);
}
private boolean setCount(E element, int count) {
return getMultiset().setCount(element, getMultiset().count(element), count);
}
private void assertSetCountNegativeOldCount() {
try {
getMultiset().setCount(samples.e3, -1, 1);
fail("calling setCount() with a negative oldCount should throw "
+ "IllegalArgumentException");
} catch (IllegalArgumentException expected) {
}
}
// Negative oldCount.
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCountConditional_negativeOldCount_addSupported() {
assertSetCountNegativeOldCount();
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCountConditional_negativeOldCount_addUnsupported() {
try {
assertSetCountNegativeOldCount();
} catch (UnsupportedOperationException tolerated) {
}
}
// Incorrect expected present count.
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCountConditional_oldCountTooLarge() {
assertFalse("setCount() with a too-large oldCount should return false",
getMultiset().setCount(samples.e0, 2, 3));
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCountConditional_oldCountTooSmallZero() {
assertFalse("setCount() with a too-small oldCount should return false",
getMultiset().setCount(samples.e0, 0, 2));
expectUnchanged();
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCountConditional_oldCountTooSmallNonzero() {
initThreeCopies();
assertFalse("setCount() with a too-small oldCount should return false",
getMultiset().setCount(samples.e0, 1, 5));
expectContents(nCopies(3, samples.e0));
}
/*
* TODO: test that unmodifiable multisets either throw UOE or return false
* when both are valid options. Currently we test the UOE cases and the
* return-false cases but not their intersection
*/
}
| Java |
/*
* Copyright (C) 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);
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Arrays;
/**
* Tests for {@code Multiset.containsAll} not already addressed by {@code CollectionContainsTester}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultisetContainsTester<E> extends AbstractMultisetTester<E> {
@CollectionSize.Require(absent = ZERO)
public void testContainsAllMultisetIgnoresFrequency() {
assertTrue(getMultiset()
.containsAll(getSubjectGenerator().create(samples.e0, samples.e0, samples.e0)));
}
@CollectionSize.Require(absent = ZERO)
public void testContainsAllListIgnoresFrequency() {
assertTrue(getMultiset().containsAll(Arrays.asList(samples.e0, samples.e0, samples.e0)));
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.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"));
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* To be implemented by test generators of things that can contain
* elements. Such things include both {@link Collection} and {@link Map}; since
* there isn't an established collective noun that encompasses both of these,
* 'container' is used.
*
* @author George van den Driessche
*/
@GwtCompatible
public interface TestContainerGenerator<T, E> {
/**
* Returns the sample elements that this generate populates its container
* with.
*/
SampleElements<E> samples();
/**
* Creates a new container containing the given elements. TODO: would be nice
* to figure out how to use E... or E[] as a parameter type, but this doesn't
* seem to work because Java creates an array of the erased type.
*/
T create(Object ... elements);
/**
* Helper method to create an array of the appropriate type used by this
* generator. The returned array will contain only nulls.
*/
E[] createArray(int length);
/**
* Returns the iteration ordering of elements, given the order in
* which they were added to the container. This method may return the
* original list unchanged, the original list modified in place, or a
* different list.
*
* <p>This method runs only when {@link
* com.google.common.collect.testing.features.CollectionFeature#KNOWN_ORDER}
* is specified when creating the test suite. It should never run when testing
* containers such as {@link java.util.HashSet}, which have a
* non-deterministic iteration order.
*/
Iterable<E> order(List<E> insertionOrder);
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.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;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* Base class for map testers.
*
* TODO: see how much of this is actually needed once Map testers are written.
* (It was cloned from AbstractCollectionTester.)
*
* @param <K> the key type of the map to be tested.
* @param <V> the value type of the map to be tested.
*
* @author George van den Driessche
*/
@GwtCompatible
public abstract class AbstractMapTester<K, V> extends
AbstractContainerTester<Map<K, V>, Map.Entry<K, V>> {
protected Map<K, V> getMap() {
return container;
}
@Override public void setUp() throws Exception {
super.setUp();
samples = this.getSubjectGenerator().samples();
resetMap();
}
@Override protected Collection<Map.Entry<K, V>> actualContents() {
return getMap().entrySet();
}
/** @see AbstractContainerTester#resetContainer() */
protected void resetMap() {
resetContainer();
}
protected void expectMissingKeys(K... elements) {
for (K element : elements) {
assertFalse("Should not contain key " + element,
getMap().containsKey(element));
}
}
protected void expectMissingValues(V... elements) {
for (V element : elements) {
assertFalse("Should not contain value " + element,
getMap().containsValue(element));
}
}
/**
* @return an array of the proper size with {@code null} as the key of the
* middle element.
*/
protected Map.Entry<K, V>[] createArrayWithNullKey() {
Map.Entry<K, V>[] array = createSamplesArray();
final int nullKeyLocation = getNullLocation();
final Map.Entry<K, V> oldEntry = array[nullKeyLocation];
array[nullKeyLocation] = entry(null, oldEntry.getValue());
return array;
}
protected V getValueForNullKey() {
return getEntryNullReplaces().getValue();
}
protected K getKeyForNullValue() {
return getEntryNullReplaces().getKey();
}
private Entry<K, V> getEntryNullReplaces() {
Iterator<Entry<K, V>> entries = getSampleElements().iterator();
for (int i = 0; i < getNullLocation(); i++) {
entries.next();
}
return entries.next();
}
/**
* @return an array of the proper size with {@code null} as the value of the
* middle element.
*/
protected Map.Entry<K, V>[] createArrayWithNullValue() {
Map.Entry<K, V>[] array = createSamplesArray();
final int nullValueLocation = getNullLocation();
final Map.Entry<K, V> oldEntry = array[nullValueLocation];
array[nullValueLocation] = entry(oldEntry.getKey(), null);
return array;
}
protected void initMapWithNullKey() {
resetMap(createArrayWithNullKey());
}
protected void initMapWithNullValue() {
resetMap(createArrayWithNullValue());
}
/**
* Equivalent to {@link #expectMissingKeys(Object[]) expectMissingKeys}
* {@code (null)}
* except that the call to {@code contains(null)} is permitted to throw a
* {@code NullPointerException}.
* @param message message to use upon assertion failure
*/
protected void expectNullKeyMissingWhenNullKeysUnsupported(String message) {
try {
assertFalse(message, getMap().containsKey(null));
} catch (NullPointerException tolerated) {
// Tolerated
}
}
/**
* Equivalent to {@link #expectMissingValues(Object[]) expectMissingValues}
* {@code (null)}
* except that the call to {@code contains(null)} is permitted to throw a
* {@code NullPointerException}.
* @param message message to use upon assertion failure
*/
protected void expectNullValueMissingWhenNullValuesUnsupported(
String message) {
try {
assertFalse(message, getMap().containsValue(null));
} catch (NullPointerException tolerated) {
// Tolerated
}
}
@SuppressWarnings("unchecked")
@Override protected MinimalCollection<Map.Entry<K, V>>
createDisjointCollection() {
return MinimalCollection.of(samples.e3, samples.e4);
}
protected int getNumEntries() {
return getNumElements();
}
protected Collection<Map.Entry<K, V>> getSampleEntries(int howMany) {
return getSampleElements(howMany);
}
protected Collection<Map.Entry<K, V>> getSampleEntries() {
return getSampleElements();
}
@Override protected void expectMissing(Entry<K, V>... entries) {
for (Entry<K, V> entry : entries) {
assertFalse("Should not contain entry " + entry,
actualContents().contains(entry));
assertFalse("Should not contain key " + entry.getKey() + " mapped to"
+ " value " + entry.getValue(),
equal(getMap().get(entry.getKey()), entry.getValue()));
}
}
private static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
// This one-liner saves us from some ugly casts
protected Entry<K, V> entry(K key, V value) {
return Helpers.mapEntry(key, value);
}
@Override protected void expectContents(Collection<Entry<K, V>> expected) {
// TODO: move this to invariant checks once the appropriate hook exists?
super.expectContents(expected);
for (Entry<K, V> entry : expected) {
assertEquals("Wrong value for key " + entry.getKey(),
entry.getValue(), getMap().get(entry.getKey()));
}
}
protected final void expectReplacement(Entry<K, V> newEntry) {
List<Entry<K, V>> expected = Helpers.copyToList(getSampleElements());
replaceValue(expected, newEntry);
expectContents(expected);
}
private void replaceValue(List<Entry<K, V>> expected, Entry<K, V> newEntry) {
for (ListIterator<Entry<K, V>> i = expected.listIterator(); i.hasNext();) {
if (Helpers.equal(i.next().getKey(), newEntry.getKey())) {
i.set(newEntry);
return;
}
}
throw new IllegalArgumentException(Platform.format(
"key %s not found in entries %s", newEntry.getKey(), expected));
}
/**
* Wrapper for {@link Map#get(Object)} that forces the caller to pass in a key
* of the same type as the map. Besides being slightly shorter than code that
* uses {@link #getMap()}, it also ensures that callers don't pass an
* {@link Entry} by mistake.
*/
protected V get(K key) {
return getMap().get(key);
}
protected void resetMap(Entry<K, V>[] entries) {
resetContainer(getSubjectGenerator().create((Object[]) entries));
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import 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> {
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.SetFeature;
import 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));
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.testers.CollectionAddAllTester;
import com.google.common.collect.testing.testers.CollectionAddTester;
import com.google.common.collect.testing.testers.CollectionClearTester;
import com.google.common.collect.testing.testers.CollectionContainsAllTester;
import com.google.common.collect.testing.testers.CollectionContainsTester;
import com.google.common.collect.testing.testers.CollectionCreationTester;
import com.google.common.collect.testing.testers.CollectionEqualsTester;
import com.google.common.collect.testing.testers.CollectionIsEmptyTester;
import com.google.common.collect.testing.testers.CollectionIteratorTester;
import com.google.common.collect.testing.testers.CollectionRemoveAllTester;
import com.google.common.collect.testing.testers.CollectionRemoveTester;
import com.google.common.collect.testing.testers.CollectionRetainAllTester;
import com.google.common.collect.testing.testers.CollectionSerializationTester;
import com.google.common.collect.testing.testers.CollectionSizeTester;
import com.google.common.collect.testing.testers.CollectionToArrayTester;
import com.google.common.collect.testing.testers.CollectionToStringTester;
import junit.framework.TestSuite;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Abstract superclass of all test-suite builders for collection interfaces.
*
* @author George van den Driessche
*/
public abstract class AbstractCollectionTestSuiteBuilder<
B extends AbstractCollectionTestSuiteBuilder<B, E>, E>
extends PerCollectionSizeTestSuiteBuilder<
B, TestCollectionGenerator<E>, Collection<E>, E> {
// Class parameters must be raw.
@SuppressWarnings("unchecked")
@Override protected List<Class<? extends AbstractTester>> getTesters() {
return Arrays.<Class<? extends AbstractTester>>asList(
CollectionAddAllTester.class,
CollectionAddTester.class,
CollectionClearTester.class,
CollectionContainsAllTester.class,
CollectionContainsTester.class,
CollectionCreationTester.class,
CollectionEqualsTester.class,
CollectionIsEmptyTester.class,
CollectionIteratorTester.class,
CollectionRemoveAllTester.class,
CollectionRemoveTester.class,
CollectionRetainAllTester.class,
CollectionSerializationTester.class,
CollectionSizeTester.class,
CollectionToArrayTester.class,
CollectionToStringTester.class
);
}
@Override
protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder<
?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>>
parentBuilder) {
DerivedIteratorTestSuiteBuilder<?> iteratorTestSuiteBuilder =
new DerivedIteratorTestSuiteBuilder<E>()
.named(parentBuilder.getName())
.usingGenerator(parentBuilder.getSubjectGenerator())
.withFeatures(parentBuilder.getFeatures());
return Collections.singletonList(
iteratorTestSuiteBuilder.createTestSuite());
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import static java.util.Collections.singleton;
import 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();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.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);
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Creates map entries using sample keys and sample values.
*
* @author Jesse Wilson
*/
@GwtCompatible
public abstract class TestMapEntrySetGenerator<K, V>
implements TestSetGenerator<Map.Entry<K, V>> {
private final SampleElements<K> keys;
private final SampleElements<V> values;
protected TestMapEntrySetGenerator(
SampleElements<K> keys, SampleElements<V> values) {
this.keys = keys;
this.values = values;
}
@Override
public SampleElements<Map.Entry<K, V>> samples() {
return SampleElements.mapEntries(keys, values);
}
@Override
public Set<Map.Entry<K, V>> create(Object... elements) {
Map.Entry<K, V>[] entries = createArray(elements.length);
System.arraycopy(elements, 0, entries, 0, elements.length);
return createFromEntries(entries);
}
public abstract Set<Map.Entry<K, V>> createFromEntries(
Map.Entry<K, V>[] entries);
@Override
@SuppressWarnings("unchecked") // generic arrays make typesafety sad
public Map.Entry<K, V>[] createArray(int length) {
return new Map.Entry[length];
}
/** Returns the original element list, unchanged. */
@Override
public List<Map.Entry<K, V>> order(List<Map.Entry<K, V>> insertionOrder) {
return insertionOrder;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import static com.google.common.collect.testing.Helpers.castOrCopyToList;
import static com.google.common.collect.testing.Helpers.equal;
import static com.google.common.collect.testing.Helpers.mapEntry;
import static java.util.Collections.sort;
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.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
/**
* Derived suite generators, split out of the suite builders so that they are available to GWT.
*
* @author George van den Driessche
*/
@GwtCompatible
public final class DerivedCollectionGenerators {
public static class MapEntrySetGenerator<K, V>
implements TestSetGenerator<Map.Entry<K, V>>, DerivedGenerator {
private final OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>>
mapGenerator;
public MapEntrySetGenerator(
OneSizeTestContainerGenerator<
Map<K, V>, Map.Entry<K, V>> mapGenerator) {
this.mapGenerator = mapGenerator;
}
@Override
public SampleElements<Map.Entry<K, V>> samples() {
return mapGenerator.samples();
}
@Override
public Set<Map.Entry<K, V>> create(Object... elements) {
return mapGenerator.create(elements).entrySet();
}
@Override
public Map.Entry<K, V>[] createArray(int length) {
return mapGenerator.createArray(length);
}
@Override
public Iterable<Map.Entry<K, V>> order(
List<Map.Entry<K, V>> insertionOrder) {
return mapGenerator.order(insertionOrder);
}
@Override
public OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>> getInnerGenerator() {
return mapGenerator;
}
}
// TODO: investigate some API changes to SampleElements that would tidy up
// parts of the following classes.
static <K, V> TestSetGenerator<K> keySetGenerator(
OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>> mapGenerator) {
if (mapGenerator.getInnerGenerator() instanceof TestSortedMapGenerator) {
return new MapSortedKeySetGenerator<K, V>(mapGenerator);
} else {
return new MapKeySetGenerator<K, V>(mapGenerator);
}
}
public static class MapKeySetGenerator<K, V>
implements TestSetGenerator<K>, DerivedGenerator {
private final OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>>
mapGenerator;
private final SampleElements<K> samples;
public MapKeySetGenerator(
OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>>
mapGenerator) {
this.mapGenerator = mapGenerator;
final SampleElements<Map.Entry<K, V>> mapSamples =
this.mapGenerator.samples();
this.samples = new SampleElements<K>(
mapSamples.e0.getKey(),
mapSamples.e1.getKey(),
mapSamples.e2.getKey(),
mapSamples.e3.getKey(),
mapSamples.e4.getKey());
}
@Override
public SampleElements<K> samples() {
return samples;
}
@Override
public Set<K> create(Object... elements) {
@SuppressWarnings("unchecked")
K[] keysArray = (K[]) elements;
// Start with a suitably shaped collection of entries
Collection<Map.Entry<K, V>> originalEntries =
mapGenerator.getSampleElements(elements.length);
// Create a copy of that, with the desired value for each key
Collection<Map.Entry<K, V>> entries =
new ArrayList<Entry<K, V>>(elements.length);
int i = 0;
for (Map.Entry<K, V> entry : originalEntries) {
entries.add(Helpers.mapEntry(keysArray[i++], entry.getValue()));
}
return mapGenerator.create(entries.toArray()).keySet();
}
@Override
public K[] createArray(int length) {
// TODO: with appropriate refactoring of OneSizeGenerator, we can perhaps
// tidy this up and get rid of the casts here and in
// MapValueCollectionGenerator.
return ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator())
.createKeyArray(length);
}
@Override
public Iterable<K> order(List<K> insertionOrder) {
V v = ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator()).samples().e0.getValue();
List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>();
for (K element : insertionOrder) {
entries.add(mapEntry(element, v));
}
List<K> keys = new ArrayList<K>();
for (Entry<K, V> entry : mapGenerator.order(entries)) {
keys.add(entry.getKey());
}
return keys;
}
@Override
public OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>> getInnerGenerator() {
return mapGenerator;
}
}
public static class MapSortedKeySetGenerator<K, V> extends MapKeySetGenerator<K, V>
implements TestSortedSetGenerator<K>, DerivedGenerator {
private final TestSortedMapGenerator<K, V> delegate;
public MapSortedKeySetGenerator(
OneSizeTestContainerGenerator<Map<K, V>, Entry<K, V>> mapGenerator) {
super(mapGenerator);
this.delegate = (TestSortedMapGenerator<K, V>) mapGenerator.getInnerGenerator();
}
@Override
public SortedSet<K> create(Object... elements) {
return (SortedSet<K>) super.create(elements);
}
@Override
public K belowSamplesLesser() {
return delegate.belowSamplesLesser().getKey();
}
@Override
public K belowSamplesGreater() {
return delegate.belowSamplesGreater().getKey();
}
@Override
public K aboveSamplesLesser() {
return delegate.aboveSamplesLesser().getKey();
}
@Override
public K aboveSamplesGreater() {
return delegate.aboveSamplesGreater().getKey();
}
}
public static class MapValueCollectionGenerator<K, V>
implements TestCollectionGenerator<V>, DerivedGenerator {
private final OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>>
mapGenerator;
private final SampleElements<V> samples;
public MapValueCollectionGenerator(
OneSizeTestContainerGenerator<
Map<K, V>, Map.Entry<K, V>> mapGenerator) {
this.mapGenerator = mapGenerator;
final SampleElements<Map.Entry<K, V>> mapSamples =
this.mapGenerator.samples();
this.samples = new SampleElements<V>(
mapSamples.e0.getValue(),
mapSamples.e1.getValue(),
mapSamples.e2.getValue(),
mapSamples.e3.getValue(),
mapSamples.e4.getValue());
}
@Override
public SampleElements<V> samples() {
return samples;
}
@Override
public Collection<V> create(Object... elements) {
@SuppressWarnings("unchecked")
V[] valuesArray = (V[]) elements;
// Start with a suitably shaped collection of entries
Collection<Map.Entry<K, V>> originalEntries =
mapGenerator.getSampleElements(elements.length);
// Create a copy of that, with the desired value for each value
Collection<Map.Entry<K, V>> entries =
new ArrayList<Entry<K, V>>(elements.length);
int i = 0;
for (Map.Entry<K, V> entry : originalEntries) {
entries.add(Helpers.mapEntry(entry.getKey(), valuesArray[i++]));
}
return mapGenerator.create(entries.toArray()).values();
}
@Override
public V[] createArray(int length) {
//noinspection UnnecessaryLocalVariable
final V[] vs = ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator())
.createValueArray(length);
return vs;
}
@Override
public Iterable<V> order(List<V> insertionOrder) {
final List<Entry<K, V>> orderedEntries =
castOrCopyToList(mapGenerator.order(castOrCopyToList(
mapGenerator.getSampleElements(5))));
sort(insertionOrder, new Comparator<V>() {
@Override public int compare(V left, V right) {
// The indexes are small enough for the subtraction trick to be safe.
return indexOfEntryWithValue(left) - indexOfEntryWithValue(right);
}
int indexOfEntryWithValue(V value) {
for (int i = 0; i < orderedEntries.size(); i++) {
if (equal(orderedEntries.get(i).getValue(), value)) {
return i;
}
}
throw new IllegalArgumentException("Map.values generator can order only sample values");
}
});
return insertionOrder;
}
@Override
public OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>> getInnerGenerator() {
return mapGenerator;
}
}
// TODO(cpovirk): could something like this be used elsewhere, e.g., ReserializedListGenerator?
static class ForwardingTestMapGenerator<K, V> implements TestMapGenerator<K, V> {
TestMapGenerator<K, V> delegate;
ForwardingTestMapGenerator(TestMapGenerator<K, V> delegate) {
this.delegate = delegate;
}
@Override
public Iterable<Entry<K, V>> order(List<Entry<K, V>> insertionOrder) {
return delegate.order(insertionOrder);
}
@Override
public K[] createKeyArray(int length) {
return delegate.createKeyArray(length);
}
@Override
public V[] createValueArray(int length) {
return delegate.createValueArray(length);
}
@Override
public SampleElements<Entry<K, V>> samples() {
return delegate.samples();
}
@Override
public Map<K, V> create(Object... elements) {
return delegate.create(elements);
}
@Override
public Entry<K, V>[] createArray(int length) {
return delegate.createArray(length);
}
}
/**
* Two bounds (from and to) define how to build a subMap.
*/
public enum Bound {
INCLUSIVE,
EXCLUSIVE,
NO_BOUND;
}
public static class SortedSetSubsetTestSetGenerator<E>
implements TestSortedSetGenerator<E> {
final Bound to;
final Bound from;
final E firstInclusive;
final E lastInclusive;
private final Comparator<? super E> comparator;
private final TestSortedSetGenerator<E> delegate;
public SortedSetSubsetTestSetGenerator(
TestSortedSetGenerator<E> delegate, Bound to, Bound from) {
this.to = to;
this.from = from;
this.delegate = delegate;
SortedSet<E> emptySet = delegate.create();
this.comparator = emptySet.comparator();
SampleElements<E> samples = delegate.samples();
List<E> samplesList = new ArrayList<E>(samples.asList());
Collections.sort(samplesList, comparator);
this.firstInclusive = samplesList.get(0);
this.lastInclusive = samplesList.get(samplesList.size() - 1);
}
public final TestSortedSetGenerator<E> getInnerGenerator() {
return delegate;
}
public final Bound getTo() {
return to;
}
public final Bound getFrom() {
return from;
}
@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 SortedSet<E> create(Object... elements) {
@SuppressWarnings("unchecked") // set generators must pass SampleElements values
List<E> normalValues = (List) Arrays.asList(elements);
List<E> extremeValues = new ArrayList<E>();
// nulls are usually out of bounds for a subset, so ban them altogether
for (Object o : elements) {
if (o == null) {
throw new NullPointerException();
}
}
// prepare extreme values to be filtered out of view
E firstExclusive = delegate.belowSamplesGreater();
E lastExclusive = delegate.aboveSamplesLesser();
if (from != Bound.NO_BOUND) {
extremeValues.add(delegate.belowSamplesLesser());
extremeValues.add(delegate.belowSamplesGreater());
}
if (to != Bound.NO_BOUND) {
extremeValues.add(delegate.aboveSamplesLesser());
extremeValues.add(delegate.aboveSamplesGreater());
}
// the regular values should be visible after filtering
List<E> allEntries = new ArrayList<E>();
allEntries.addAll(extremeValues);
allEntries.addAll(normalValues);
SortedSet<E> map = delegate.create(allEntries.toArray());
return createSubSet(map, firstExclusive, lastExclusive);
}
/**
* Calls the smallest subSet overload that filters out the extreme values.
*/
SortedSet<E> createSubSet(SortedSet<E> set, E firstExclusive, E lastExclusive) {
if (from == Bound.NO_BOUND && to == Bound.EXCLUSIVE) {
return set.headSet(lastExclusive);
} else if (from == Bound.INCLUSIVE && to == Bound.NO_BOUND) {
return set.tailSet(firstInclusive);
} else if (from == Bound.INCLUSIVE && to == Bound.EXCLUSIVE) {
return set.subSet(firstInclusive, lastExclusive);
} else {
throw new IllegalArgumentException();
}
}
@Override
public E belowSamplesLesser() {
throw new UnsupportedOperationException();
}
@Override
public E belowSamplesGreater() {
throw new UnsupportedOperationException();
}
@Override
public E aboveSamplesLesser() {
throw new UnsupportedOperationException();
}
@Override
public E aboveSamplesGreater() {
throw new UnsupportedOperationException();
}
}
/*
* TODO(cpovirk): surely we can find a less ugly solution than a class that accepts 3 parameters,
* exposes as many getters, does work in the constructor, and has both a superclass and a subclass
*/
public static class SortedMapSubmapTestMapGenerator<K, V>
extends ForwardingTestMapGenerator<K, V> implements TestSortedMapGenerator<K, V> {
final Bound to;
final Bound from;
final K firstInclusive;
final K lastInclusive;
private final Comparator<Entry<K, V>> entryComparator;
public SortedMapSubmapTestMapGenerator(
TestSortedMapGenerator<K, V> delegate, Bound to, Bound from) {
super(delegate);
this.to = to;
this.from = from;
SortedMap<K, V> emptyMap = delegate.create();
this.entryComparator = Helpers.entryComparator(emptyMap.comparator());
// derive values for inclusive filtering from the input samples
SampleElements<Entry<K, V>> samples = delegate.samples();
@SuppressWarnings("unchecked") // no elements are inserted into the array
List<Entry<K, V>> samplesList = Arrays.asList(
samples.e0, samples.e1, samples.e2, samples.e3, samples.e4);
Collections.sort(samplesList, entryComparator);
this.firstInclusive = samplesList.get(0).getKey();
this.lastInclusive = samplesList.get(samplesList.size() - 1).getKey();
}
@Override public SortedMap<K, V> create(Object... entries) {
@SuppressWarnings("unchecked") // map generators must past entry objects
List<Entry<K, V>> normalValues = (List) Arrays.asList(entries);
List<Entry<K, V>> extremeValues = new ArrayList<Entry<K, V>>();
// prepare extreme values to be filtered out of view
K firstExclusive = getInnerGenerator().belowSamplesGreater().getKey();
K lastExclusive = getInnerGenerator().aboveSamplesLesser().getKey();
if (from != Bound.NO_BOUND) {
extremeValues.add(getInnerGenerator().belowSamplesLesser());
extremeValues.add(getInnerGenerator().belowSamplesGreater());
}
if (to != Bound.NO_BOUND) {
extremeValues.add(getInnerGenerator().aboveSamplesLesser());
extremeValues.add(getInnerGenerator().aboveSamplesGreater());
}
// the regular values should be visible after filtering
List<Entry<K, V>> allEntries = new ArrayList<Entry<K, V>>();
allEntries.addAll(extremeValues);
allEntries.addAll(normalValues);
SortedMap<K, V> map = (SortedMap<K, V>)
delegate.create((Object[])
allEntries.toArray(new Entry<?, ?>[allEntries.size()]));
return createSubMap(map, firstExclusive, lastExclusive);
}
/**
* Calls the smallest subMap overload that filters out the extreme values. This method is
* overridden in NavigableMapTestSuiteBuilder.
*/
SortedMap<K, V> createSubMap(SortedMap<K, V> map, K firstExclusive, K lastExclusive) {
if (from == Bound.NO_BOUND && to == Bound.EXCLUSIVE) {
return map.headMap(lastExclusive);
} else if (from == Bound.INCLUSIVE && to == Bound.NO_BOUND) {
return map.tailMap(firstInclusive);
} else if (from == Bound.INCLUSIVE && to == Bound.EXCLUSIVE) {
return map.subMap(firstInclusive, lastExclusive);
} else {
throw new IllegalArgumentException();
}
}
public final Bound getTo() {
return to;
}
public final Bound getFrom() {
return from;
}
public final TestSortedMapGenerator<K, V> getInnerGenerator() {
return (TestSortedMapGenerator<K, V>) delegate;
}
@Override
public Entry<K, V> belowSamplesLesser() {
// should never reach here!
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> belowSamplesGreater() {
// should never reach here!
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> aboveSamplesLesser() {
// should never reach here!
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> aboveSamplesGreater() {
// should never reach here!
throw new UnsupportedOperationException();
}
}
private DerivedCollectionGenerators() {}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import junit.framework.TestSuite;
import java.util.List;
/**
* Given a test iterable generator, builds a test suite for the
* iterable's iterator, by delegating to a {@link IteratorTestSuiteBuilder}.
*
* @author George van den Driessche
*/
public class DerivedIteratorTestSuiteBuilder<E>
extends FeatureSpecificTestSuiteBuilder<
DerivedIteratorTestSuiteBuilder<E>,
TestSubjectGenerator<? extends Iterable<E>>> {
/**
* We rely entirely on the delegate builder for test creation, so this
* just throws UnsupportedOperationException.
*
* @return never.
*/
@Override protected List<Class<? extends AbstractTester>> getTesters() {
throw new UnsupportedOperationException();
}
@Override public TestSuite createTestSuite() {
checkCanCreate();
return new IteratorTestSuiteBuilder<E>()
.named(getName() + " iterator")
.usingGenerator(new DerivedTestIteratorGenerator<E>(
getSubjectGenerator()))
.withFeatures(getFeatures())
.createTestSuite();
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
import junit.framework.Test;
import junit.framework.TestSuite;
import java.lang.reflect.Method;
import java.util.AbstractList;
import java.util.AbstractSequentialList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Generates a test suite covering the {@link List} implementations in the
* {@link java.util} package. Can be subclassed to specify tests that should
* be suppressed.
*
* @author Kevin Bourrillion
*/
public class TestsForListsInJavaUtil {
public static Test suite() {
return new TestsForListsInJavaUtil().allTests();
}
public Test allTests() {
TestSuite suite = new TestSuite("java.util Lists");
suite.addTest(testsForEmptyList());
suite.addTest(testsForSingletonList());
suite.addTest(testsForArraysAsList());
suite.addTest(testsForArrayList());
suite.addTest(testsForLinkedList());
suite.addTest(testsForCopyOnWriteArrayList());
suite.addTest(testsForUnmodifiableList());
suite.addTest(testsForCheckedList());
suite.addTest(testsForAbstractList());
suite.addTest(testsForAbstractSequentialList());
return suite;
}
protected Collection<Method> suppressForEmptyList() {
return Collections.emptySet();
}
protected Collection<Method> suppressForSingletonList() {
return Collections.emptySet();
}
protected Collection<Method> suppressForArraysAsList() {
return Collections.emptySet();
}
protected Collection<Method> suppressForArrayList() {
return Collections.emptySet();
}
protected Collection<Method> suppressForLinkedList() {
return Collections.emptySet();
}
protected Collection<Method> suppressForCopyOnWriteArrayList() {
return Collections.emptySet();
}
protected Collection<Method> suppressForUnmodifiableList() {
return Collections.emptySet();
}
protected Collection<Method> suppressForCheckedList() {
return Collections.emptySet();
}
protected Collection<Method> suppressForAbstractList() {
return Collections.emptySet();
}
protected Collection<Method> suppressForAbstractSequentialList() {
return Collections.emptySet();
}
public Test testsForEmptyList() {
return ListTestSuiteBuilder
.using(new TestStringListGenerator() {
@Override public List<String> create(String[] elements) {
return Collections.emptyList();
}
})
.named("emptyList")
.withFeatures(
CollectionFeature.SERIALIZABLE,
CollectionSize.ZERO)
.suppressing(suppressForEmptyList())
.createTestSuite();
}
public Test testsForSingletonList() {
return ListTestSuiteBuilder
.using(new TestStringListGenerator() {
@Override public List<String> create(String[] elements) {
return Collections.singletonList(elements[0]);
}
})
.named("singletonList")
.withFeatures(
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionSize.ONE)
.suppressing(suppressForSingletonList())
.createTestSuite();
}
public Test testsForArraysAsList() {
return ListTestSuiteBuilder
.using(new TestStringListGenerator() {
@Override public List<String> create(String[] elements) {
return Arrays.asList(elements.clone());
}
})
.named("Arrays.asList")
.withFeatures(
ListFeature.SUPPORTS_SET,
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionSize.ANY)
.suppressing(suppressForArraysAsList())
.createTestSuite();
}
public Test testsForArrayList() {
return ListTestSuiteBuilder
.using(new TestStringListGenerator() {
@Override public List<String> create(String[] elements) {
return new ArrayList<String>(MinimalCollection.of(elements));
}
})
.named("ArrayList")
.withFeatures(
ListFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionSize.ANY)
.suppressing(suppressForArrayList())
.createTestSuite();
}
public Test testsForLinkedList() {
return ListTestSuiteBuilder
.using(new TestStringListGenerator() {
@Override public List<String> create(String[] elements) {
return new LinkedList<String>(MinimalCollection.of(elements));
}
})
.named("LinkedList")
.withFeatures(
ListFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionSize.ANY)
.suppressing(suppressForLinkedList())
.createTestSuite();
}
public Test testsForCopyOnWriteArrayList() {
return ListTestSuiteBuilder
.using(new TestStringListGenerator() {
@Override public List<String> create(String[] elements) {
return new CopyOnWriteArrayList<String>(
MinimalCollection.of(elements));
}
})
.named("CopyOnWriteArrayList")
.withFeatures(
ListFeature.SUPPORTS_ADD_WITH_INDEX,
ListFeature.SUPPORTS_REMOVE_WITH_INDEX,
ListFeature.SUPPORTS_SET,
CollectionFeature.SUPPORTS_ADD,
CollectionFeature.SUPPORTS_REMOVE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionSize.ANY)
.suppressing(suppressForCopyOnWriteArrayList())
.createTestSuite();
}
public Test testsForUnmodifiableList() {
return ListTestSuiteBuilder
.using(new TestStringListGenerator() {
@Override public List<String> create(String[] elements) {
List<String> innerList = new ArrayList<String>();
Collections.addAll(innerList, elements);
return Collections.unmodifiableList(innerList);
}
})
.named("unmodifiableList/ArrayList")
.withFeatures(
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionSize.ANY)
.suppressing(suppressForUnmodifiableList())
.createTestSuite();
}
public Test testsForCheckedList() {
return ListTestSuiteBuilder
.using(new TestStringListGenerator() {
@Override public List<String> create(String[] elements) {
List<String> innerList = new ArrayList<String>();
Collections.addAll(innerList, elements);
return Collections.checkedList(innerList, String.class);
}
})
.named("checkedList/ArrayList")
.withFeatures(
ListFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.RESTRICTS_ELEMENTS,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionSize.ANY)
.suppressing(suppressForCheckedList())
.createTestSuite();
}
public Test testsForAbstractList() {
return ListTestSuiteBuilder
.using(new TestStringListGenerator () {
@Override protected List<String> create(final String[] elements) {
return new AbstractList<String>() {
@Override public int size() {
return elements.length;
}
@Override public String get(int index) {
return elements[index];
}
};
}
})
.named("AbstractList")
.withFeatures(
CollectionFeature.NONE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionSize.ANY)
.suppressing(suppressForAbstractList())
.createTestSuite();
}
public Test testsForAbstractSequentialList() {
return ListTestSuiteBuilder
.using(new TestStringListGenerator () {
@Override protected List<String> create(final String[] elements) {
// For this test we trust ArrayList works
final List<String> list = new ArrayList<String>();
Collections.addAll(list, elements);
return new AbstractSequentialList<String>() {
@Override public int size() {
return list.size();
}
@Override public ListIterator<String> listIterator(int index) {
return list.listIterator(index);
}
};
}
})
.named("AbstractSequentialList")
.withFeatures(
ListFeature.GENERAL_PURPOSE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionSize.ANY)
.suppressing(suppressForAbstractSequentialList())
.createTestSuite();
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import 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();
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import static com.google.common.collect.testing.Helpers.orderEntriesByKey;
import com.google.common.annotations.GwtCompatible;
import java.util.List;
import java.util.Map.Entry;
import java.util.SortedMap;
/**
* Implementation helper for {@link TestMapGenerator} for use with sorted maps of strings.
*
* @author Chris Povirk
*/
@GwtCompatible
public abstract class TestStringSortedMapGenerator extends TestStringMapGenerator
implements TestSortedMapGenerator<String, String> {
@Override
public Entry<String, String> belowSamplesLesser() {
return Helpers.mapEntry("!! a", "below view");
}
@Override
public Entry<String, String> belowSamplesGreater() {
return Helpers.mapEntry("!! b", "below view");
}
@Override
public Entry<String, String> aboveSamplesLesser() {
return Helpers.mapEntry("~~ a", "above view");
}
@Override
public Entry<String, String> aboveSamplesGreater() {
return Helpers.mapEntry("~~ b", "above view");
}
@Override
public Iterable<Entry<String, String>> order(List<Entry<String, String>> insertionOrder) {
return orderEntriesByKey(insertionOrder);
}
@Override
protected abstract SortedMap<String, String> create(Entry<String, String>[] entries);
@Override
public SortedMap<String, String> create(Object... entries) {
return (SortedMap<String, String>) super.create(entries);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import junit.framework.Test;
import junit.framework.TestSuite;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
/**
* Generates a test suite covering the {@link Queue} implementations in the
* {@link java.util} package. Can be subclassed to specify tests that should
* be suppressed.
*
* @author Jared Levy
*/
public class TestsForQueuesInJavaUtil {
public static Test suite() {
return new TestsForQueuesInJavaUtil().allTests();
}
public Test allTests() {
TestSuite suite = new TestSuite();
suite.addTest(testsForLinkedList());
suite.addTest(testsForArrayBlockingQueue());
suite.addTest(testsForConcurrentLinkedQueue());
suite.addTest(testsForLinkedBlockingQueue());
suite.addTest(testsForPriorityBlockingQueue());
suite.addTest(testsForPriorityQueue());
return suite;
}
protected Collection<Method> suppressForLinkedList() {
return Collections.emptySet();
}
protected Collection<Method> suppressForArrayBlockingQueue() {
return Collections.emptySet();
}
protected Collection<Method> suppressForConcurrentLinkedQueue() {
return Collections.emptySet();
}
protected Collection<Method> suppressForLinkedBlockingQueue() {
return Collections.emptySet();
}
protected Collection<Method> suppressForPriorityBlockingQueue() {
return Collections.emptySet();
}
protected Collection<Method> suppressForPriorityQueue() {
return Collections.emptySet();
}
public Test testsForLinkedList() {
return QueueTestSuiteBuilder
.using(new TestStringQueueGenerator() {
@Override public Queue<String> create(String[] elements) {
return new LinkedList<String>(MinimalCollection.of(elements));
}
})
.named("LinkedList")
.withFeatures(
CollectionFeature.GENERAL_PURPOSE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionFeature.KNOWN_ORDER,
CollectionSize.ANY)
.skipCollectionTests() // already covered in TestsForListsInJavaUtil
.suppressing(suppressForLinkedList())
.createTestSuite();
}
public Test testsForArrayBlockingQueue() {
return QueueTestSuiteBuilder
.using(new TestStringQueueGenerator() {
@Override public Queue<String> create(String[] elements) {
return new ArrayBlockingQueue<String>(
100, false, MinimalCollection.of(elements));
}
})
.named("ArrayBlockingQueue")
.withFeatures(
CollectionFeature.GENERAL_PURPOSE,
CollectionFeature.KNOWN_ORDER,
CollectionSize.ANY)
.suppressing(suppressForArrayBlockingQueue())
.createTestSuite();
}
public Test testsForConcurrentLinkedQueue() {
return QueueTestSuiteBuilder
.using(new TestStringQueueGenerator() {
@Override public Queue<String> create(String[] elements) {
return new ConcurrentLinkedQueue<String>(
MinimalCollection.of(elements));
}
})
.named("ConcurrentLinkedQueue")
.withFeatures(
CollectionFeature.GENERAL_PURPOSE,
CollectionFeature.KNOWN_ORDER,
CollectionSize.ANY)
.suppressing(suppressForConcurrentLinkedQueue())
.createTestSuite();
}
public Test testsForLinkedBlockingQueue() {
return QueueTestSuiteBuilder
.using(new TestStringQueueGenerator() {
@Override public Queue<String> create(String[] elements) {
return new LinkedBlockingQueue<String>(
MinimalCollection.of(elements));
}
})
.named("LinkedBlockingQueue")
.withFeatures(
CollectionFeature.GENERAL_PURPOSE,
CollectionFeature.KNOWN_ORDER,
CollectionSize.ANY)
.suppressing(suppressForLinkedBlockingQueue())
.createTestSuite();
}
// Not specifying KNOWN_ORDER for PriorityQueue and PriorityBlockingQueue
// even though they do have it, because our tests interpret KNOWN_ORDER to
// also mean that the iterator returns the head element first, which those
// don't.
public Test testsForPriorityBlockingQueue() {
return QueueTestSuiteBuilder
.using(new TestStringQueueGenerator() {
@Override public Queue<String> create(String[] elements) {
return new PriorityBlockingQueue<String>(
MinimalCollection.of(elements));
}
})
.named("PriorityBlockingQueue")
.withFeatures(
CollectionFeature.GENERAL_PURPOSE,
CollectionSize.ANY)
.suppressing(suppressForPriorityBlockingQueue())
.createTestSuite();
}
public Test testsForPriorityQueue() {
return QueueTestSuiteBuilder
.using(new TestStringQueueGenerator() {
@Override public Queue<String> create(String[] elements) {
return new PriorityQueue<String>(MinimalCollection.of(elements));
}
})
.named("PriorityQueue")
.withFeatures(
CollectionFeature.GENERAL_PURPOSE,
CollectionSize.ANY)
.suppressing(suppressForPriorityQueue())
.createTestSuite();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import 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();
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import java.io.Serializable;
import java.util.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 NATURAL_ORDER = new Comparator<Comparable>() {
@Override public int compare(Comparable o1, Comparable o2) {
return o1.compareTo(o2);
}
};
private final NavigableMap<K, V> delegate;
public SafeTreeMap() {
this(new TreeMap<K, V>());
}
public SafeTreeMap(Comparator<? super K> comparator) {
this(new TreeMap<K, V>(comparator));
}
public SafeTreeMap(Map<? extends K, ? extends V> map) {
this(new TreeMap<K, V>(map));
}
public SafeTreeMap(SortedMap<K, ? extends V> map) {
this(new TreeMap<K, V>(map));
}
private SafeTreeMap(NavigableMap<K, V> delegate) {
this.delegate = delegate;
if (delegate == null) {
throw new NullPointerException();
}
for (K k : keySet()) {
checkValid(k);
}
}
@Override public Entry<K, V> ceilingEntry(K key) {
return delegate.ceilingEntry(checkValid(key));
}
@Override public K ceilingKey(K key) {
return delegate.ceilingKey(checkValid(key));
}
@Override public void clear() {
delegate.clear();
}
@SuppressWarnings("unchecked")
@Override public Comparator<? super K> comparator() {
Comparator<? super K> comparator = delegate.comparator();
if (comparator == null) {
comparator = NATURAL_ORDER;
}
return comparator;
}
@Override public boolean containsKey(Object key) {
try {
return delegate.containsKey(checkValid(key));
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
@Override public boolean containsValue(Object value) {
return delegate.containsValue(value);
}
@Override public NavigableSet<K> descendingKeySet() {
return delegate.descendingKeySet();
}
@Override public NavigableMap<K, V> descendingMap() {
return new SafeTreeMap<K, V>(delegate.descendingMap());
}
@Override public Set<Entry<K, V>> entrySet() {
return 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;
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
/**
* An implementation of {@code Iterable} which throws an exception on all
* invocations of the {@link #iterator()} method after the first, and whose
* iterator is always unmodifiable.
*
* <p>The {@code Iterable} specification does not make it absolutely clear what
* should happen on a second invocation, so implementors have made various
* choices, including:
*
* <ul>
* <li>returning the same iterator again
* <li>throwing an exception of some kind
* <li>or the usual, <i>robust</i> behavior, which all known {@link Collection}
* implementations have, of returning a new, independent iterator
* </ul>
*
* <p>Because of this situation, any public method accepting an iterable should
* invoke the {@code iterator} method only once, and should be tested using this
* class. Exceptions to this rule should be clearly documented.
*
* <p>Note that although your APIs should be liberal in what they accept, your
* methods which <i>return</i> iterables should make every attempt to return
* ones of the robust variety.
*
* <p>This testing utility is not thread-safe.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public final class MinimalIterable<E> implements Iterable<E> {
/**
* Returns an iterable whose iterator returns the given elements in order.
*/
public static <E> MinimalIterable<E> of(E... elements) {
// Make sure to get an unmodifiable iterator
return new MinimalIterable<E>(Arrays.asList(elements).iterator());
}
/**
* Returns an iterable whose iterator returns the given elements in order.
* The elements are copied out of the source collection at the time this
* method is called.
*/
@SuppressWarnings("unchecked") // Es come in, Es go out
public static <E> MinimalIterable<E> from(final Collection<E> elements) {
return (MinimalIterable) of(elements.toArray());
}
private Iterator<E> iterator;
private MinimalIterable(Iterator<E> iterator) {
this.iterator = iterator;
}
@Override
public Iterator<E> iterator() {
if (iterator == null) {
// TODO: throw something else? Do we worry that people's code and tests
// might be relying on this particular type of exception?
throw new IllegalStateException();
}
try {
return iterator;
} finally {
iterator = null;
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import 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> {
/** A key type that is not assignable to any classes but Object. */
private static final class IncompatibleComparableKeyType
implements Comparable<IncompatibleComparableKeyType> {
@Override public String toString() {
return "IncompatibleComparableKeyType";
}
@Override
public int compareTo(IncompatibleComparableKeyType o) {
throw new ClassCastException();
}
}
protected SortedMapInterfaceTest(boolean allowsNullKeys,
boolean allowsNullValues, boolean supportsPut, boolean supportsRemove,
boolean supportsClear) {
super(allowsNullKeys, allowsNullValues, supportsPut, supportsRemove,
supportsClear);
}
@Override protected abstract SortedMap<K, V> makeEmptyMap()
throws UnsupportedOperationException;
@Override protected abstract SortedMap<K, V> makePopulatedMap()
throws UnsupportedOperationException;
@Override protected SortedMap<K, V> makeEitherMap() {
try {
return makePopulatedMap();
} catch (UnsupportedOperationException e) {
return makeEmptyMap();
}
}
public void testTailMapWriteThrough() {
final SortedMap<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (map.size() < 2 || !supportsPut) {
return;
}
Iterator<Entry<K, V>> iterator = map.entrySet().iterator();
Entry<K, V> firstEntry = iterator.next();
Entry<K, V> secondEntry = iterator.next();
K key = secondEntry.getKey();
SortedMap<K, V> subMap = map.tailMap(key);
V value = getValueNotInPopulatedMap();
subMap.put(key, value);
assertEquals(secondEntry.getValue(), value);
assertEquals(map.get(key), value);
try {
subMap.put(firstEntry.getKey(), value);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {
}
}
public void testTailMapRemoveThrough() {
final SortedMap<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int oldSize = map.size();
if (map.size() < 2 || !supportsRemove) {
return;
}
Iterator<Entry<K, V>> iterator = map.entrySet().iterator();
Entry<K, V> firstEntry = iterator.next();
Entry<K, V> secondEntry = iterator.next();
K key = secondEntry.getKey();
SortedMap<K, V> subMap = map.tailMap(key);
subMap.remove(key);
assertNull(subMap.remove(firstEntry.getKey()));
assertEquals(map.size(), oldSize - 1);
assertFalse(map.containsKey(key));
assertEquals(subMap.size(), oldSize - 2);
}
public void testTailMapClearThrough() {
final SortedMap<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int oldSize = map.size();
if (map.size() < 2 || !supportsClear) {
return;
}
Iterator<Entry<K, V>> iterator = map.entrySet().iterator();
Entry<K, V> firstEntry = iterator.next();
Entry<K, V> secondEntry = iterator.next();
K key = secondEntry.getKey();
SortedMap<K, V> subMap = map.tailMap(key);
int subMapSize = subMap.size();
subMap.clear();
assertEquals(map.size(), oldSize - subMapSize);
assertTrue(subMap.isEmpty());
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.List;
/**
* Reserializes the sets created by another test set generator.
*
* TODO: make CollectionTestSuiteBuilder test reserialized collections
*
* @author Jesse Wilson
*/
public class ReserializingTestCollectionGenerator<E>
implements TestCollectionGenerator<E> {
private final TestCollectionGenerator<E> delegate;
ReserializingTestCollectionGenerator(TestCollectionGenerator<E> delegate) {
this.delegate = delegate;
}
public static <E> ReserializingTestCollectionGenerator<E> newInstance(
TestCollectionGenerator<E> delegate) {
return new ReserializingTestCollectionGenerator<E>(delegate);
}
@Override
public Collection<E> create(Object... elements) {
return reserialize(delegate.create(elements));
}
@SuppressWarnings("unchecked")
static <T> T reserialize(T object) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bytes);
out.writeObject(object);
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bytes.toByteArray()));
return (T) in.readObject();
} catch (IOException e) {
Helpers.fail(e, e.getMessage());
} catch (ClassNotFoundException e) {
Helpers.fail(e, e.getMessage());
}
throw new AssertionError("not reachable");
}
@Override
public SampleElements<E> samples() {
return delegate.samples();
}
@Override
public E[] createArray(int length) {
return delegate.createArray(length);
}
@Override
public Iterable<E> order(List<E> insertionOrder) {
return delegate.order(insertionOrder);
}
} | Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.SampleElements.Ints;
import java.util.List;
import java.util.Set;
/**
* Create integer sets for collection tests.
*
* @author Gregory Kick
*/
@GwtCompatible
public abstract class TestIntegerSetGenerator implements TestSetGenerator<Integer> {
@Override public SampleElements<Integer> samples() {
return new Ints();
}
@Override public Set<Integer> create(Object... elements) {
Integer[] array = new Integer[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (Integer) e;
}
return create(array);
}
protected abstract Set<Integer> create(Integer[] elements);
@Override public Integer[] createArray(int length) {
return new Integer[length];
}
/**
* {@inheritDoc}
*
* <p>By default, returns the supplied elements in their given order; however,
* generators for containers with a known order other than insertion order
* must override this method.
*
* <p>Note: This default implementation is overkill (but valid) for an
* unordered container. An equally valid implementation for an unordered
* container is to throw an exception. The chosen implementation, however, has
* the advantage of working for insertion-ordered containers, as well.
*/
@Override public List<Integer> order(List<Integer> insertionOrder) {
return insertionOrder;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
import java.util.Set;
/**
* Creates sets, containing sample elements, to be tested.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public interface TestSetGenerator<E> extends TestCollectionGenerator<E> {
@Override
Set<E> create(Object... elements);
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.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();
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import static com.google.common.collect.testing.DerivedCollectionGenerators.keySetGenerator;
import com.google.common.collect.testing.DerivedCollectionGenerators.MapEntrySetGenerator;
import com.google.common.collect.testing.DerivedCollectionGenerators.MapValueCollectionGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.features.MapFeature;
import com.google.common.collect.testing.testers.MapClearTester;
import com.google.common.collect.testing.testers.MapContainsKeyTester;
import com.google.common.collect.testing.testers.MapContainsValueTester;
import com.google.common.collect.testing.testers.MapCreationTester;
import com.google.common.collect.testing.testers.MapEntrySetTester;
import com.google.common.collect.testing.testers.MapEqualsTester;
import com.google.common.collect.testing.testers.MapGetTester;
import com.google.common.collect.testing.testers.MapHashCodeTester;
import com.google.common.collect.testing.testers.MapIsEmptyTester;
import com.google.common.collect.testing.testers.MapPutAllTester;
import com.google.common.collect.testing.testers.MapPutTester;
import com.google.common.collect.testing.testers.MapRemoveTester;
import com.google.common.collect.testing.testers.MapSerializationTester;
import com.google.common.collect.testing.testers.MapSizeTester;
import com.google.common.collect.testing.testers.MapToStringTester;
import com.google.common.testing.SerializableTester;
import junit.framework.TestSuite;
import java.util.Arrays;
import java.util.HashSet;
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 Map implementation.
*
* @author George van den Driessche
*/
public class MapTestSuiteBuilder<K, V>
extends PerCollectionSizeTestSuiteBuilder<
MapTestSuiteBuilder<K, V>,
TestMapGenerator<K, V>, Map<K, V>, Map.Entry<K, V>> {
public static <K, V> MapTestSuiteBuilder<K, V> using(
TestMapGenerator<K, V> generator) {
return new MapTestSuiteBuilder<K, V>().usingGenerator(generator);
}
@SuppressWarnings("unchecked") // Class parameters must be raw.
@Override protected List<Class<? extends AbstractTester>> getTesters() {
return Arrays.<Class<? extends AbstractTester>>asList(
MapClearTester.class,
MapContainsKeyTester.class,
MapContainsValueTester.class,
MapCreationTester.class,
MapEntrySetTester.class,
MapEqualsTester.class,
MapGetTester.class,
MapHashCodeTester.class,
MapIsEmptyTester.class,
MapPutTester.class,
MapPutAllTester.class,
MapRemoveTester.class,
MapSerializationTester.class,
MapSizeTester.class,
MapToStringTester.class
);
}
@Override
protected List<TestSuite> createDerivedSuites(
FeatureSpecificTestSuiteBuilder<
?,
? extends OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>>>
parentBuilder) {
// TODO: Once invariant support is added, supply invariants to each of the
// derived suites, to check that mutations to the derived collections are
// reflected in the underlying map.
List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder);
if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {
derivedSuites.add(MapTestSuiteBuilder.using(
new ReserializedMapGenerator<K, V>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + " reserialized")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
}
derivedSuites.add(SetTestSuiteBuilder.using(
new MapEntrySetGenerator<K, V>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + " entrySet")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
derivedSuites.add(createDerivedKeySetSuite(
keySetGenerator(parentBuilder.getSubjectGenerator()))
.withFeatures(computeKeySetFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + " keys")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
derivedSuites.add(CollectionTestSuiteBuilder.using(
new MapValueCollectionGenerator<K, V>(
parentBuilder.getSubjectGenerator()))
.named(parentBuilder.getName() + " values")
.withFeatures(computeValuesCollectionFeatures(
parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
return derivedSuites;
}
protected SetTestSuiteBuilder<K> createDerivedKeySetSuite(TestSetGenerator<K> keySetGenerator) {
return SetTestSuiteBuilder.using(keySetGenerator);
}
private static Set<Feature<?>> computeReserializedMapFeatures(
Set<Feature<?>> mapFeatures) {
Set<Feature<?>> derivedFeatures = Helpers.copyToSet(mapFeatures);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);
return derivedFeatures;
}
private static Set<Feature<?>> computeEntrySetFeatures(
Set<Feature<?>> mapFeatures) {
Set<Feature<?>> entrySetFeatures =
computeCommonDerivedCollectionFeatures(mapFeatures);
entrySetFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES);
return entrySetFeatures;
}
private static Set<Feature<?>> computeKeySetFeatures(
Set<Feature<?>> mapFeatures) {
Set<Feature<?>> keySetFeatures =
computeCommonDerivedCollectionFeatures(mapFeatures);
// TODO(user): make this trigger only if the map is a submap
// currently, the KeySetGenerator won't work properly for a subset of a keyset of a submap
keySetFeatures.add(CollectionFeature.SUBSET_VIEW);
if (mapFeatures.contains(MapFeature.ALLOWS_NULL_KEYS)) {
keySetFeatures.add(CollectionFeature.ALLOWS_NULL_VALUES);
} else if (mapFeatures.contains(MapFeature.ALLOWS_NULL_QUERIES)) {
keySetFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES);
}
return keySetFeatures;
}
private static Set<Feature<?>> computeValuesCollectionFeatures(
Set<Feature<?>> mapFeatures) {
Set<Feature<?>> valuesCollectionFeatures =
computeCommonDerivedCollectionFeatures(mapFeatures);
if (mapFeatures.contains(MapFeature.ALLOWS_NULL_QUERIES)) {
valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES);
}
if (mapFeatures.contains(MapFeature.ALLOWS_NULL_VALUES)) {
valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_VALUES);
}
return valuesCollectionFeatures;
}
public static Set<Feature<?>> computeCommonDerivedCollectionFeatures(
Set<Feature<?>> mapFeatures) {
mapFeatures = new HashSet<Feature<?>>(mapFeatures);
Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>();
mapFeatures.remove(CollectionFeature.SERIALIZABLE);
if (mapFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) {
derivedFeatures.add(CollectionFeature.SERIALIZABLE);
}
if (mapFeatures.contains(MapFeature.SUPPORTS_REMOVE)) {
derivedFeatures.add(CollectionFeature.SUPPORTS_REMOVE);
}
if (mapFeatures.contains(MapFeature.REJECTS_DUPLICATES_AT_CREATION)) {
derivedFeatures.add(CollectionFeature.REJECTS_DUPLICATES_AT_CREATION);
}
if (mapFeatures.contains(MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION)) {
derivedFeatures.add(CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION);
}
// add the intersection of CollectionFeature.values() and mapFeatures
for (CollectionFeature feature : CollectionFeature.values()) {
if (mapFeatures.contains(feature)) {
derivedFeatures.add(feature);
}
}
// add the intersection of CollectionSize.values() and mapFeatures
for (CollectionSize size : CollectionSize.values()) {
if (mapFeatures.contains(size)) {
derivedFeatures.add(size);
}
}
return derivedFeatures;
}
private static class ReserializedMapGenerator<K, V>
implements TestMapGenerator<K, V> {
private final OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>>
mapGenerator;
public ReserializedMapGenerator(
OneSizeTestContainerGenerator<
Map<K, V>, Map.Entry<K, V>> mapGenerator) {
this.mapGenerator = mapGenerator;
}
@Override
public SampleElements<Map.Entry<K, V>> samples() {
return mapGenerator.samples();
}
@Override
public Map.Entry<K, V>[] createArray(int length) {
return mapGenerator.createArray(length);
}
@Override
public Iterable<Map.Entry<K, V>> order(
List<Map.Entry<K, V>> insertionOrder) {
return mapGenerator.order(insertionOrder);
}
@Override
public Map<K, V> create(Object... elements) {
return SerializableTester.reserialize(mapGenerator.create(elements));
}
@Override
public K[] createKeyArray(int length) {
return ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator())
.createKeyArray(length);
}
@Override
public V[] createValueArray(int length) {
return ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator())
.createValueArray(length);
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.