code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.HashSet; import java.util.Set; /** * Unit tests for {@link Sets#union}, {@link Sets#intersection} and * {@link Sets#difference}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class SetOperationsTest extends TestCase { public static class MoreTests extends TestCase { Set<String> friends; Set<String> enemies; @Override public void setUp() { friends = Sets.newHashSet("Tom", "Joe", "Dave"); enemies = Sets.newHashSet("Dick", "Harry", "Tom"); } public void testUnion() { Set<String> all = Sets.union(friends, enemies); assertEquals(5, all.size()); ImmutableSet<String> immut = Sets.union(friends, enemies).immutableCopy(); HashSet<String> mut = Sets.union(friends, enemies).copyInto(new HashSet<String>()); enemies.add("Buck"); assertEquals(6, all.size()); assertEquals(5, immut.size()); assertEquals(5, mut.size()); } public void testIntersection() { Set<String> friends = Sets.newHashSet("Tom", "Joe", "Dave"); Set<String> enemies = Sets.newHashSet("Dick", "Harry", "Tom"); Set<String> frenemies = Sets.intersection(friends, enemies); assertEquals(1, frenemies.size()); ImmutableSet<String> immut = Sets.intersection(friends, enemies).immutableCopy(); HashSet<String> mut = Sets.intersection(friends, enemies).copyInto(new HashSet<String>()); enemies.add("Joe"); assertEquals(2, frenemies.size()); assertEquals(1, immut.size()); assertEquals(1, mut.size()); } public void testDifference() { Set<String> friends = Sets.newHashSet("Tom", "Joe", "Dave"); Set<String> enemies = Sets.newHashSet("Dick", "Harry", "Tom"); Set<String> goodFriends = Sets.difference(friends, enemies); assertEquals(2, goodFriends.size()); ImmutableSet<String> immut = Sets.difference(friends, enemies).immutableCopy(); HashSet<String> mut = Sets.difference(friends, enemies).copyInto(new HashSet<String>()); enemies.add("Dave"); assertEquals(1, goodFriends.size()); assertEquals(2, immut.size()); assertEquals(2, mut.size()); } public void testSymmetricDifference() { Set<String> friends = Sets.newHashSet("Tom", "Joe", "Dave"); Set<String> enemies = Sets.newHashSet("Dick", "Harry", "Tom"); Set<String> symmetricDifferenceFriendsFirst = Sets.symmetricDifference( friends, enemies); assertEquals(4, symmetricDifferenceFriendsFirst.size()); Set<String> symmetricDifferenceEnemiesFirst = Sets.symmetricDifference( enemies, friends); assertEquals(4, symmetricDifferenceEnemiesFirst.size()); assertEquals(symmetricDifferenceFriendsFirst, symmetricDifferenceEnemiesFirst); ImmutableSet<String> immut = Sets.symmetricDifference(friends, enemies).immutableCopy(); HashSet<String> mut = Sets.symmetricDifference(friends, enemies) .copyInto(new HashSet<String>()); enemies.add("Dave"); assertEquals(3, symmetricDifferenceFriendsFirst.size()); assertEquals(4, immut.size()); assertEquals(4, mut.size()); immut = Sets.symmetricDifference(enemies, friends).immutableCopy(); mut = Sets.symmetricDifference(enemies, friends). copyInto(new HashSet<String>()); friends.add("Harry"); assertEquals(2, symmetricDifferenceEnemiesFirst.size()); assertEquals(3, immut.size()); assertEquals(3, mut.size()); } } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/SetOperationsTest.java
Java
asf20
4,315
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.SortedSet; /** * Unit tests for {@code TreeMultimap} with explicit comparators. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class TreeMultimapExplicitTest extends TestCase { /** * Compare strings lengths, and if the lengths are equal compare the strings. * A {@code null} is less than any non-null value. */ private enum StringLength implements Comparator<String> { COMPARATOR; @Override public int compare(String first, String second) { if (first == second) { return 0; } else if (first == null) { return -1; } else if (second == null) { return 1; } else if (first.length() != second.length()) { return first.length() - second.length(); } else { return first.compareTo(second); } } } /** * Decreasing integer values. A {@code null} comes before any non-null value. */ private static final Comparator<Integer> DECREASING_INT_COMPARATOR = Ordering.<Integer>natural().reverse().nullsFirst(); private SetMultimap<String, Integer> create() { return TreeMultimap.create( StringLength.COMPARATOR, DECREASING_INT_COMPARATOR); } /** * Create and populate a {@code TreeMultimap} with explicit comparators. */ private TreeMultimap<String, Integer> createPopulate() { TreeMultimap<String, Integer> multimap = TreeMultimap.create( StringLength.COMPARATOR, DECREASING_INT_COMPARATOR); multimap.put("google", 2); multimap.put("google", 6); multimap.put(null, 3); multimap.put(null, 1); multimap.put(null, 7); multimap.put("tree", 0); multimap.put("tree", null); return multimap; } /** * Test that a TreeMultimap created from another uses the natural ordering. */ public void testMultimapCreateFromTreeMultimap() { TreeMultimap<String, Integer> tree = TreeMultimap.create( StringLength.COMPARATOR, DECREASING_INT_COMPARATOR); tree.put("google", 2); tree.put("google", 6); tree.put("tree", 0); tree.put("tree", 3); ASSERT.that(tree.keySet()).has().exactly("tree", "google").inOrder(); ASSERT.that(tree.get("google")).has().exactly(6, 2).inOrder(); TreeMultimap<String, Integer> copy = TreeMultimap.create(tree); assertEquals(tree, copy); ASSERT.that(copy.keySet()).has().exactly("google", "tree").inOrder(); ASSERT.that(copy.get("google")).has().exactly(2, 6).inOrder(); assertEquals(Ordering.natural(), copy.keyComparator()); assertEquals(Ordering.natural(), copy.valueComparator()); assertEquals(Ordering.natural(), copy.get("google").comparator()); } public void testToString() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 3); multimap.put("bar", 1); multimap.putAll("foo", Arrays.asList(-1, 2, 4)); multimap.putAll("bar", Arrays.asList(2, 3)); multimap.put("foo", 1); assertEquals("{bar=[3, 2, 1], foo=[4, 3, 2, 1, -1]}", multimap.toString()); } public void testGetComparator() { TreeMultimap<String, Integer> multimap = createPopulate(); assertEquals(StringLength.COMPARATOR, multimap.keyComparator()); assertEquals(DECREASING_INT_COMPARATOR, multimap.valueComparator()); } public void testOrderedGet() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.get(null)).has().exactly(7, 3, 1).inOrder(); ASSERT.that(multimap.get("google")).has().exactly(6, 2).inOrder(); ASSERT.that(multimap.get("tree")).has().exactly(null, 0).inOrder(); } public void testOrderedKeySet() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.keySet()).has().exactly(null, "tree", "google").inOrder(); } public void testOrderedAsMapEntries() { TreeMultimap<String, Integer> multimap = createPopulate(); Iterator<Map.Entry<String, Collection<Integer>>> iterator = multimap.asMap().entrySet().iterator(); Map.Entry<String, Collection<Integer>> entry = iterator.next(); assertEquals(null, entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(7, 3, 1); entry = iterator.next(); assertEquals("tree", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(null, 0); entry = iterator.next(); assertEquals("google", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(6, 2); } public void testOrderedEntries() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.entries()).has().exactly( Maps.immutableEntry((String) null, 7), Maps.immutableEntry((String) null, 3), Maps.immutableEntry((String) null, 1), Maps.immutableEntry("tree", (Integer) null), Maps.immutableEntry("tree", 0), Maps.immutableEntry("google", 6), Maps.immutableEntry("google", 2)).inOrder(); } public void testOrderedValues() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.values()).has().exactly(7, 3, 1, null, 0, 6, 2).inOrder(); } public void testComparator() { TreeMultimap<String, Integer> multimap = createPopulate(); assertEquals(DECREASING_INT_COMPARATOR, multimap.get("foo").comparator()); assertEquals(DECREASING_INT_COMPARATOR, multimap.get("missing").comparator()); } public void testMultimapComparators() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 3); multimap.put("bar", 1); multimap.putAll("foo", Arrays.asList(-1, 2, 4)); multimap.putAll("bar", Arrays.asList(2, 3)); multimap.put("foo", 1); TreeMultimap<String, Integer> copy = TreeMultimap.create(StringLength.COMPARATOR, DECREASING_INT_COMPARATOR); copy.putAll(multimap); assertEquals(multimap, copy); assertEquals(StringLength.COMPARATOR, copy.keyComparator()); assertEquals(DECREASING_INT_COMPARATOR, copy.valueComparator()); } public void testSortedKeySet() { TreeMultimap<String, Integer> multimap = createPopulate(); SortedSet<String> keySet = multimap.keySet(); assertEquals(null, keySet.first()); assertEquals("google", keySet.last()); assertEquals(StringLength.COMPARATOR, keySet.comparator()); assertEquals(Sets.newHashSet(null, "tree"), keySet.headSet("yahoo")); assertEquals(Sets.newHashSet("google"), keySet.tailSet("yahoo")); assertEquals(Sets.newHashSet("tree"), keySet.subSet("ask", "yahoo")); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/TreeMultimapExplicitTest.java
Java
asf20
7,378
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.testing.Helpers.nefariousMapEntry; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Predicates; import com.google.common.base.Supplier; import com.google.common.collect.Maps.EntryTransformer; import com.google.common.collect.testing.IteratorTester; import com.google.common.collect.testing.google.UnmodifiableCollectionTests; import junit.framework.TestCase; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nullable; /** * Unit test for {@code Multimaps}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class MultimapsTest extends TestCase { private static final Comparator<Integer> INT_COMPARATOR = Ordering.<Integer>natural().reverse().nullsFirst(); private static final EntryTransformer<Object, Object, Object> ALWAYS_NULL = new EntryTransformer<Object, Object, Object>() { @Override public Object transformEntry(Object k, Object v1) { return null; } }; @SuppressWarnings("deprecation") public void testUnmodifiableListMultimapShortCircuit() { ListMultimap<String, Integer> mod = ArrayListMultimap.create(); ListMultimap<String, Integer> unmod = Multimaps.unmodifiableListMultimap(mod); assertNotSame(mod, unmod); assertSame(unmod, Multimaps.unmodifiableListMultimap(unmod)); ImmutableListMultimap<String, Integer> immutable = ImmutableListMultimap.of("a", 1, "b", 2, "a", 3); assertSame(immutable, Multimaps.unmodifiableListMultimap(immutable)); assertSame( immutable, Multimaps.unmodifiableListMultimap((ListMultimap<String, Integer>) immutable)); } @SuppressWarnings("deprecation") public void testUnmodifiableSetMultimapShortCircuit() { SetMultimap<String, Integer> mod = HashMultimap.create(); SetMultimap<String, Integer> unmod = Multimaps.unmodifiableSetMultimap(mod); assertNotSame(mod, unmod); assertSame(unmod, Multimaps.unmodifiableSetMultimap(unmod)); ImmutableSetMultimap<String, Integer> immutable = ImmutableSetMultimap.of("a", 1, "b", 2, "a", 3); assertSame(immutable, Multimaps.unmodifiableSetMultimap(immutable)); assertSame( immutable, Multimaps.unmodifiableSetMultimap((SetMultimap<String, Integer>) immutable)); } @SuppressWarnings("deprecation") public void testUnmodifiableMultimapShortCircuit() { Multimap<String, Integer> mod = HashMultimap.create(); Multimap<String, Integer> unmod = Multimaps.unmodifiableMultimap(mod); assertNotSame(mod, unmod); assertSame(unmod, Multimaps.unmodifiableMultimap(unmod)); ImmutableMultimap<String, Integer> immutable = ImmutableMultimap.of("a", 1, "b", 2, "a", 3); assertSame(immutable, Multimaps.unmodifiableMultimap(immutable)); assertSame(immutable, Multimaps.unmodifiableMultimap((Multimap<String, Integer>) immutable)); } public void testUnmodifiableArrayListMultimapRandomAccess() { ListMultimap<String, Integer> delegate = ArrayListMultimap.create(); delegate.put("foo", 1); delegate.put("foo", 3); ListMultimap<String, Integer> multimap = Multimaps.unmodifiableListMultimap(delegate); assertTrue(multimap.get("foo") instanceof RandomAccess); assertTrue(multimap.get("bar") instanceof RandomAccess); } public void testUnmodifiableLinkedListMultimapRandomAccess() { ListMultimap<String, Integer> delegate = LinkedListMultimap.create(); delegate.put("foo", 1); delegate.put("foo", 3); ListMultimap<String, Integer> multimap = Multimaps.unmodifiableListMultimap(delegate); assertFalse(multimap.get("foo") instanceof RandomAccess); assertFalse(multimap.get("bar") instanceof RandomAccess); } public void testUnmodifiableMultimapIsView() { Multimap<String, Integer> mod = HashMultimap.create(); Multimap<String, Integer> unmod = Multimaps.unmodifiableMultimap(mod); assertEquals(mod, unmod); mod.put("foo", 1); assertTrue(unmod.containsEntry("foo", 1)); assertEquals(mod, unmod); } @SuppressWarnings("unchecked") public void testUnmodifiableMultimapEntries() { Multimap<String, Integer> mod = HashMultimap.create(); Multimap<String, Integer> unmod = Multimaps.unmodifiableMultimap(mod); mod.put("foo", 1); Entry<String, Integer> entry = unmod.entries().iterator().next(); try { entry.setValue(2); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} entry = (Entry<String, Integer>) unmod.entries().toArray()[0]; try { entry.setValue(2); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} Entry<String, Integer>[] array = (Entry<String, Integer>[]) new Entry<?, ?>[2]; assertSame(array, unmod.entries().toArray(array)); try { array[0].setValue(2); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} assertFalse(unmod.entries().contains(nefariousMapEntry("pwnd", 2))); assertFalse(unmod.keys().contains("pwnd")); } /** * The supplied multimap will be mutated and an unmodifiable instance used * in its stead. The multimap must support null keys and values. */ private static void checkUnmodifiableMultimap( Multimap<String, Integer> multimap, boolean permitsDuplicates) { checkUnmodifiableMultimap(multimap, permitsDuplicates, null, null); } /** * The supplied multimap will be mutated and an unmodifiable instance used * in its stead. If the multimap does not support null keys or values, * alternatives may be specified for tests involving nulls. */ private static void checkUnmodifiableMultimap( Multimap<String, Integer> multimap, boolean permitsDuplicates, @Nullable String nullKey, @Nullable Integer nullValue) { Multimap<String, Integer> unmodifiable = prepareUnmodifiableTests(multimap, permitsDuplicates, nullKey, nullValue); UnmodifiableCollectionTests.assertMultimapIsUnmodifiable( unmodifiable, "test", 123); assertUnmodifiableIterableInTandem( unmodifiable.keys(), multimap.keys()); assertUnmodifiableIterableInTandem( unmodifiable.keySet(), multimap.keySet()); assertUnmodifiableIterableInTandem( unmodifiable.entries(), multimap.entries()); assertUnmodifiableIterableInTandem( unmodifiable.asMap().entrySet(), multimap.asMap().entrySet()); assertEquals(multimap.toString(), unmodifiable.toString()); assertEquals(multimap.hashCode(), unmodifiable.hashCode()); assertEquals(multimap, unmodifiable); ASSERT.that(unmodifiable.asMap().get("bar")).has().exactly(5, -1); assertNull(unmodifiable.asMap().get("missing")); assertFalse(unmodifiable.entries() instanceof Serializable); } /** * Prepares the multimap for unmodifiable tests, returning an unmodifiable view * of the map. */ private static Multimap<String, Integer> prepareUnmodifiableTests( Multimap<String, Integer> multimap, boolean permitsDuplicates, @Nullable String nullKey, @Nullable Integer nullValue) { multimap.clear(); multimap.put("foo", 1); multimap.put("foo", 2); multimap.put("foo", 3); multimap.put("bar", 5); multimap.put("bar", -1); multimap.put(nullKey, nullValue); multimap.put("foo", nullValue); multimap.put(nullKey, 5); multimap.put("foo", 2); if (permitsDuplicates) { assertEquals(9, multimap.size()); } else { assertEquals(8, multimap.size()); } Multimap<String, Integer> unmodifiable; if (multimap instanceof SortedSetMultimap) { unmodifiable = Multimaps.unmodifiableSortedSetMultimap( (SortedSetMultimap<String, Integer>) multimap); } else if (multimap instanceof SetMultimap) { unmodifiable = Multimaps.unmodifiableSetMultimap( (SetMultimap<String, Integer>) multimap); } else if (multimap instanceof ListMultimap) { unmodifiable = Multimaps.unmodifiableListMultimap( (ListMultimap<String, Integer>) multimap); } else { unmodifiable = Multimaps.unmodifiableMultimap(multimap); } return unmodifiable; } private static <T> void assertUnmodifiableIterableInTandem( Iterable<T> unmodifiable, Iterable<T> modifiable) { UnmodifiableCollectionTests.assertIteratorIsUnmodifiable( unmodifiable.iterator()); UnmodifiableCollectionTests.assertIteratorsInOrder( unmodifiable.iterator(), modifiable.iterator()); } public void testInvertFrom() { ImmutableMultimap<Integer, String> empty = ImmutableMultimap.of(); // typical usage example - sad that ArrayListMultimap.create() won't work Multimap<String, Integer> multimap = Multimaps.invertFrom(empty, ArrayListMultimap.<String, Integer>create()); assertTrue(multimap.isEmpty()); ImmutableMultimap<Integer, String> single = new ImmutableMultimap.Builder<Integer, String>() .put(1, "one") .put(2, "two") .build(); // copy into existing multimap assertSame(multimap, Multimaps.invertFrom(single, multimap)); ImmutableMultimap<String, Integer> expected = new ImmutableMultimap.Builder<String, Integer>() .put("one", 1) .put("two", 2) .build(); assertEquals(expected, multimap); } public void testAsMap_multimap() { Multimap<String, Integer> multimap = Multimaps.newMultimap( new HashMap<String, Collection<Integer>>(), new QueueSupplier()); Map<String, Collection<Integer>> map = Multimaps.asMap(multimap); assertSame(multimap.asMap(), map); } public void testAsMap_listMultimap() { ListMultimap<String, Integer> listMultimap = ArrayListMultimap.create(); Map<String, List<Integer>> map = Multimaps.asMap(listMultimap); assertSame(listMultimap.asMap(), map); } public void testAsMap_setMultimap() { SetMultimap<String, Integer> setMultimap = LinkedHashMultimap.create(); Map<String, Set<Integer>> map = Multimaps.asMap(setMultimap); assertSame(setMultimap.asMap(), map); } public void testAsMap_sortedSetMultimap() { SortedSetMultimap<String, Integer> sortedSetMultimap = TreeMultimap.create(); Map<String, SortedSet<Integer>> map = Multimaps.asMap(sortedSetMultimap); assertSame(sortedSetMultimap.asMap(), map); } public void testForMap() { Map<String, Integer> map = Maps.newHashMap(); map.put("foo", 1); map.put("bar", 2); Multimap<String, Integer> multimap = HashMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); Multimap<String, Integer> multimapView = Multimaps.forMap(map); assertTrue(multimap.equals(multimapView)); assertTrue(multimapView.equals(multimap)); assertTrue(multimapView.equals(multimapView)); assertFalse(multimapView.equals(map)); Multimap<String, Integer> multimap2 = HashMultimap.create(); multimap2.put("foo", 1); assertFalse(multimapView.equals(multimap2)); multimap2.put("bar", 1); assertFalse(multimapView.equals(multimap2)); ListMultimap<String, Integer> listMultimap = new ImmutableListMultimap.Builder<String, Integer>() .put("foo", 1).put("bar", 2).build(); assertFalse("SetMultimap equals ListMultimap", multimapView.equals(listMultimap)); assertEquals(multimap.toString(), multimapView.toString()); assertEquals(multimap.hashCode(), multimapView.hashCode()); assertEquals(multimap.size(), multimapView.size()); assertTrue(multimapView.containsKey("foo")); assertTrue(multimapView.containsValue(1)); assertTrue(multimapView.containsEntry("bar", 2)); assertEquals(Collections.singleton(1), multimapView.get("foo")); assertEquals(Collections.singleton(2), multimapView.get("bar")); try { multimapView.put("baz", 3); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { multimapView.putAll("baz", Collections.singleton(3)); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { multimapView.putAll(multimap); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { multimapView.replaceValues("foo", Collections.<Integer>emptySet()); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} multimapView.remove("bar", 2); assertFalse(multimapView.containsKey("bar")); assertFalse(map.containsKey("bar")); assertEquals(map.keySet(), multimapView.keySet()); assertEquals(map.keySet(), multimapView.keys().elementSet()); ASSERT.that(multimapView.keys()).has().item("foo"); ASSERT.that(multimapView.values()).has().item(1); ASSERT.that(multimapView.entries()).has().item( Maps.immutableEntry("foo", 1)); ASSERT.that(multimapView.asMap().entrySet()).has().item( Maps.immutableEntry( "foo", (Collection<Integer>) Collections.singleton(1))); multimapView.clear(); assertFalse(multimapView.containsKey("foo")); assertFalse(map.containsKey("foo")); assertTrue(map.isEmpty()); assertTrue(multimapView.isEmpty()); multimap.clear(); assertEquals(multimap.toString(), multimapView.toString()); assertEquals(multimap.hashCode(), multimapView.hashCode()); assertEquals(multimap.size(), multimapView.size()); assertEquals(multimapView, ArrayListMultimap.create()); } public void testForMapRemoveAll() { Map<String, Integer> map = Maps.newHashMap(); map.put("foo", 1); map.put("bar", 2); map.put("cow", 3); Multimap<String, Integer> multimap = Multimaps.forMap(map); assertEquals(3, multimap.size()); assertEquals(Collections.emptySet(), multimap.removeAll("dog")); assertEquals(3, multimap.size()); assertTrue(multimap.containsKey("bar")); assertEquals(Collections.singleton(2), multimap.removeAll("bar")); assertEquals(2, multimap.size()); assertFalse(multimap.containsKey("bar")); } public void testForMapAsMap() { Map<String, Integer> map = Maps.newHashMap(); map.put("foo", 1); map.put("bar", 2); Map<String, Collection<Integer>> asMap = Multimaps.forMap(map).asMap(); assertEquals(Collections.singleton(1), asMap.get("foo")); assertNull(asMap.get("cow")); assertTrue(asMap.containsKey("foo")); assertFalse(asMap.containsKey("cow")); Set<Entry<String, Collection<Integer>>> entries = asMap.entrySet(); assertFalse(entries.contains(4.5)); assertFalse(entries.remove(4.5)); assertFalse(entries.contains(Maps.immutableEntry("foo", Collections.singletonList(1)))); assertFalse(entries.remove(Maps.immutableEntry("foo", Collections.singletonList(1)))); assertFalse(entries.contains(Maps.immutableEntry("foo", Sets.newLinkedHashSet(asList(1, 2))))); assertFalse(entries.remove(Maps.immutableEntry("foo", Sets.newLinkedHashSet(asList(1, 2))))); assertFalse(entries.contains(Maps.immutableEntry("foo", Collections.singleton(2)))); assertFalse(entries.remove(Maps.immutableEntry("foo", Collections.singleton(2)))); assertTrue(map.containsKey("foo")); assertTrue(entries.contains(Maps.immutableEntry("foo", Collections.singleton(1)))); assertTrue(entries.remove(Maps.immutableEntry("foo", Collections.singleton(1)))); assertFalse(map.containsKey("foo")); } public void testForMapGetIteration() { IteratorTester<Integer> tester = new IteratorTester<Integer>(4, MODIFIABLE, newHashSet(1), IteratorTester.KnownOrder.KNOWN_ORDER) { private Multimap<String, Integer> multimap; @Override protected Iterator<Integer> newTargetIterator() { Map<String, Integer> map = Maps.newHashMap(); map.put("foo", 1); map.put("bar", 2); multimap = Multimaps.forMap(map); return multimap.get("foo").iterator(); } @Override protected void verify(List<Integer> elements) { assertEquals(newHashSet(elements), multimap.get("foo")); } }; tester.test(); } private enum Color {BLUE, RED, YELLOW, GREEN} private abstract static class CountingSupplier<E> implements Supplier<E>, Serializable { int count; abstract E getImpl(); @Override public E get() { count++; return getImpl(); } } private static class QueueSupplier extends CountingSupplier<Queue<Integer>> { @Override public Queue<Integer> getImpl() { return new LinkedList<Integer>(); } private static final long serialVersionUID = 0; } public void testNewMultimapWithCollectionRejectingNegativeElements() { CountingSupplier<Set<Integer>> factory = new SetSupplier() { @Override public Set<Integer> getImpl() { final Set<Integer> backing = super.getImpl(); return new ForwardingSet<Integer>() { @Override protected Set<Integer> delegate() { return backing; } @Override public boolean add(Integer element) { checkArgument(element >= 0); return super.add(element); } @Override public boolean addAll(Collection<? extends Integer> collection) { return standardAddAll(collection); } }; } }; Map<Color, Collection<Integer>> map = Maps.newEnumMap(Color.class); Multimap<Color, Integer> multimap = Multimaps.newMultimap(map, factory); try { multimap.put(Color.BLUE, -1); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } multimap.put(Color.RED, 1); multimap.put(Color.BLUE, 2); try { multimap.put(Color.GREEN, -1); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } ASSERT.that(multimap.entries()).has().exactly( Maps.immutableEntry(Color.RED, 1), Maps.immutableEntry(Color.BLUE, 2)); } public void testNewMultimap() { // The ubiquitous EnumArrayBlockingQueueMultimap CountingSupplier<Queue<Integer>> factory = new QueueSupplier(); Map<Color, Collection<Integer>> map = Maps.newEnumMap(Color.class); Multimap<Color, Integer> multimap = Multimaps.newMultimap(map, factory); assertEquals(0, factory.count); multimap.putAll(Color.BLUE, asList(3, 1, 4)); assertEquals(1, factory.count); multimap.putAll(Color.RED, asList(2, 7, 1, 8)); assertEquals(2, factory.count); assertEquals("[3, 1, 4]", multimap.get(Color.BLUE).toString()); Multimap<Color, Integer> ummodifiable = Multimaps.unmodifiableMultimap(multimap); assertEquals("[3, 1, 4]", ummodifiable.get(Color.BLUE).toString()); Collection<Integer> collection = multimap.get(Color.BLUE); assertEquals(collection, collection); assertFalse(multimap.keySet() instanceof SortedSet); assertFalse(multimap.asMap() instanceof SortedMap); } private static class ListSupplier extends CountingSupplier<LinkedList<Integer>> { @Override public LinkedList<Integer> getImpl() { return new LinkedList<Integer>(); } private static final long serialVersionUID = 0; } public void testNewListMultimap() { CountingSupplier<LinkedList<Integer>> factory = new ListSupplier(); Map<Color, Collection<Integer>> map = Maps.newTreeMap(); ListMultimap<Color, Integer> multimap = Multimaps.newListMultimap(map, factory); assertEquals(0, factory.count); multimap.putAll(Color.BLUE, asList(3, 1, 4, 1)); assertEquals(1, factory.count); multimap.putAll(Color.RED, asList(2, 7, 1, 8)); assertEquals(2, factory.count); assertEquals("{BLUE=[3, 1, 4, 1], RED=[2, 7, 1, 8]}", multimap.toString()); assertFalse(multimap.get(Color.BLUE) instanceof RandomAccess); assertTrue(multimap.keySet() instanceof SortedSet); assertTrue(multimap.asMap() instanceof SortedMap); } private static class SetSupplier extends CountingSupplier<Set<Integer>> { @Override public Set<Integer> getImpl() { return new HashSet<Integer>(4); } private static final long serialVersionUID = 0; } public void testNewSetMultimap() { CountingSupplier<Set<Integer>> factory = new SetSupplier(); Map<Color, Collection<Integer>> map = Maps.newHashMap(); SetMultimap<Color, Integer> multimap = Multimaps.newSetMultimap(map, factory); assertEquals(0, factory.count); multimap.putAll(Color.BLUE, asList(3, 1, 4)); assertEquals(1, factory.count); multimap.putAll(Color.RED, asList(2, 7, 1, 8)); assertEquals(2, factory.count); assertEquals(Sets.newHashSet(4, 3, 1), multimap.get(Color.BLUE)); } private static class SortedSetSupplier extends CountingSupplier<TreeSet<Integer>> { @Override public TreeSet<Integer> getImpl() { return Sets.newTreeSet(INT_COMPARATOR); } private static final long serialVersionUID = 0; } public void testNewSortedSetMultimap() { CountingSupplier<TreeSet<Integer>> factory = new SortedSetSupplier(); Map<Color, Collection<Integer>> map = Maps.newEnumMap(Color.class); SortedSetMultimap<Color, Integer> multimap = Multimaps.newSortedSetMultimap(map, factory); // newSortedSetMultimap calls the factory once to determine the comparator. assertEquals(1, factory.count); multimap.putAll(Color.BLUE, asList(3, 1, 4)); assertEquals(2, factory.count); multimap.putAll(Color.RED, asList(2, 7, 1, 8)); assertEquals(3, factory.count); assertEquals("[4, 3, 1]", multimap.get(Color.BLUE).toString()); assertEquals(INT_COMPARATOR, multimap.valueComparator()); } public void testIndex() { final Multimap<String, Object> stringToObject = new ImmutableMultimap.Builder<String, Object>() .put("1", 1) .put("1", 1L) .put("1", "1") .put("2", 2) .put("2", 2L) .build(); ImmutableMultimap<String, Object> outputMap = Multimaps.index(stringToObject.values(), Functions.toStringFunction()); assertEquals(stringToObject, outputMap); } public void testIndexIterator() { final Multimap<String, Object> stringToObject = new ImmutableMultimap.Builder<String, Object>() .put("1", 1) .put("1", 1L) .put("1", "1") .put("2", 2) .put("2", 2L) .build(); ImmutableMultimap<String, Object> outputMap = Multimaps.index(stringToObject.values().iterator(), Functions.toStringFunction()); assertEquals(stringToObject, outputMap); } public void testIndex_ordering() { final Multimap<Integer, String> expectedIndex = new ImmutableListMultimap.Builder<Integer, String>() .put(4, "Inky") .put(6, "Blinky") .put(5, "Pinky") .put(5, "Pinky") .put(5, "Clyde") .build(); final List<String> badGuys = Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde"); final Function<String, Integer> stringLengthFunction = new Function<String, Integer>() { @Override public Integer apply(String input) { return input.length(); } }; Multimap<Integer, String> index = Multimaps.index(badGuys, stringLengthFunction); assertEquals(expectedIndex, index); } public void testIndex_nullValue() { List<Integer> values = Arrays.asList(1, null); try { Multimaps.index(values, Functions.identity()); fail(); } catch (NullPointerException e) {} } public void testIndex_nullKey() { List<Integer> values = Arrays.asList(1, 2); try { Multimaps.index(values, Functions.constant(null)); fail(); } catch (NullPointerException e) {} } public <K, V> void testSynchronizedMultimapSampleCodeCompilation() { K key = null; Multimap<K, V> multimap = Multimaps.synchronizedMultimap( HashMultimap.<K, V>create()); Collection<V> values = multimap.get(key); // Needn't be in synchronized block synchronized (multimap) { // Synchronizing on multimap, not values! Iterator<V> i = values.iterator(); // Must be in synchronized block while (i.hasNext()) { foo(i.next()); } } } private static void foo(Object o) {} public void testFilteredKeysSetMultimapReplaceValues() { SetMultimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("baz", 3); multimap.put("bar", 4); SetMultimap<String, Integer> filtered = Multimaps.filterKeys( multimap, Predicates.in(ImmutableSet.of("foo", "bar"))); assertEquals( ImmutableSet.of(), filtered.replaceValues("baz", ImmutableSet.<Integer>of())); try { filtered.replaceValues("baz", ImmutableSet.of(5)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testFilteredKeysSetMultimapGetBadValue() { SetMultimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("baz", 3); multimap.put("bar", 4); SetMultimap<String, Integer> filtered = Multimaps.filterKeys( multimap, Predicates.in(ImmutableSet.of("foo", "bar"))); Set<Integer> bazSet = filtered.get("baz"); ASSERT.that(bazSet).isEmpty(); try { bazSet.add(5); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { bazSet.addAll(ImmutableSet.of(6, 7)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testFilteredKeysListMultimapGetBadValue() { ListMultimap<String, Integer> multimap = ArrayListMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("baz", 3); multimap.put("bar", 4); ListMultimap<String, Integer> filtered = Multimaps.filterKeys( multimap, Predicates.in(ImmutableSet.of("foo", "bar"))); List<Integer> bazList = filtered.get("baz"); ASSERT.that(bazList).isEmpty(); try { bazList.add(5); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { bazList.add(0, 6); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { bazList.addAll(ImmutableList.of(7, 8)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { bazList.addAll(0, ImmutableList.of(9, 10)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/MultimapsTest.java
Java
asf20
28,703
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; /** * Test cases for {@link Table} read operations. * * @author Jared Levy */ @GwtCompatible(emulated = true) public abstract class AbstractTableReadTest extends TestCase { protected Table<String, Integer, Character> table; /** * Creates a table with the specified data. * * @param data the table data, repeating the sequence row key, column key, * value once per mapping * @throws IllegalArgumentException if the size of {@code data} isn't a * multiple of 3 * @throws ClassCastException if a data element has the wrong type */ protected abstract Table<String, Integer, Character> create(Object... data); protected void assertSize(int expectedSize) { assertEquals(expectedSize, table.size()); } @Override public void setUp() throws Exception { super.setUp(); table = create(); } public void testContains() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.contains("foo", 1)); assertTrue(table.contains("bar", 1)); assertTrue(table.contains("foo", 3)); assertFalse(table.contains("foo", 2)); assertFalse(table.contains("bar", 3)); assertFalse(table.contains("cat", 1)); assertFalse(table.contains("foo", null)); assertFalse(table.contains(null, 1)); assertFalse(table.contains(null, null)); } public void testContainsRow() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.containsRow("foo")); assertTrue(table.containsRow("bar")); assertFalse(table.containsRow("cat")); assertFalse(table.containsRow(null)); } public void testContainsColumn() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.containsColumn(1)); assertTrue(table.containsColumn(3)); assertFalse(table.containsColumn(2)); assertFalse(table.containsColumn(null)); } public void testContainsValue() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.containsValue('a')); assertTrue(table.containsValue('b')); assertTrue(table.containsValue('c')); assertFalse(table.containsValue('x')); assertFalse(table.containsValue(null)); } public void testGet() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals((Character) 'a', table.get("foo", 1)); assertEquals((Character) 'b', table.get("bar", 1)); assertEquals((Character) 'c', table.get("foo", 3)); assertNull(table.get("foo", 2)); assertNull(table.get("bar", 3)); assertNull(table.get("cat", 1)); assertNull(table.get("foo", null)); assertNull(table.get(null, 1)); assertNull(table.get(null, null)); } public void testIsEmpty() { assertTrue(table.isEmpty()); table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertFalse(table.isEmpty()); } public void testSize() { assertSize(0); table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertSize(3); } public void testEquals() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Table<String, Integer, Character> hashCopy = HashBasedTable.create(table); Table<String, Integer, Character> reordered = create("foo", 3, 'c', "foo", 1, 'a', "bar", 1, 'b'); Table<String, Integer, Character> smaller = create("foo", 1, 'a', "bar", 1, 'b'); Table<String, Integer, Character> swapOuter = create("bar", 1, 'a', "foo", 1, 'b', "bar", 3, 'c'); Table<String, Integer, Character> swapValues = create("foo", 1, 'c', "bar", 1, 'b', "foo", 3, 'a'); new EqualsTester() .addEqualityGroup(table, hashCopy, reordered) .addEqualityGroup(smaller) .addEqualityGroup(swapOuter) .addEqualityGroup(swapValues) .testEquals(); } public void testHashCode() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); int expected = Objects.hashCode("foo", 1, 'a') + Objects.hashCode("bar", 1, 'b') + Objects.hashCode("foo", 3, 'c'); assertEquals(expected, table.hashCode()); } public void testToStringSize1() { table = create("foo", 1, 'a'); assertEquals("{foo={1=a}}", table.toString()); } public void testRow() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals(ImmutableMap.of(1, 'a', 3, 'c'), table.row("foo")); } // This test assumes that the implementation does not support null keys. public void testRowNull() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); try { table.row(null); fail(); } catch (NullPointerException expected) {} } public void testColumn() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals(ImmutableMap.of("foo", 'a', "bar", 'b'), table.column(1)); } // This test assumes that the implementation does not support null keys. public void testColumnNull() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); try { table.column(null); fail(); } catch (NullPointerException expected) {} } public void testColumnSetPartialOverlap() { table = create( "foo", 1, 'a', "bar", 1, 'b', "foo", 2, 'c', "bar", 3, 'd'); ASSERT.that(table.columnKeySet()).has().exactly(1, 2, 3); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/AbstractTableReadTest.java
Java
asf20
6,166
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.MapConstraintsTest.TestKeyException; import com.google.common.collect.MapConstraintsTest.TestValueException; import com.google.common.collect.testing.TestStringMapGenerator; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Tests for {@link MapConstraints#constrainedMap}. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class ConstrainedMapTest extends TestCase { private static final String TEST_KEY = "42"; private static final String TEST_VALUE = "test"; private static final MapConstraint<String, String> TEST_CONSTRAINT = new TestConstraint(); public void testPutWithForbiddenKeyForbiddenValue() { Map<String, String> map = MapConstraints.constrainedMap( new HashMap<String, String>(), TEST_CONSTRAINT); try { map.put(TEST_KEY, TEST_VALUE); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // success } } public void testPutWithForbiddenKeyAllowedValue() { Map<String, String> map = MapConstraints.constrainedMap( new HashMap<String, String>(), TEST_CONSTRAINT); try { map.put(TEST_KEY, "allowed"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // success } } public void testPutWithAllowedKeyForbiddenValue() { Map<String, String> map = MapConstraints.constrainedMap( new HashMap<String, String>(), TEST_CONSTRAINT); try { map.put("allowed", TEST_VALUE); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // success } } public static final class ConstrainedMapGenerator extends TestStringMapGenerator { @Override protected Map<String, String> create(Entry<String, String>[] entries) { Map<String, String> map = MapConstraints.constrainedMap( new HashMap<String, String>(), TEST_CONSTRAINT); for (Entry<String, String> entry : entries) { map.put(entry.getKey(), entry.getValue()); } return map; } } private static final class TestConstraint implements MapConstraint<String, String> { @Override public void checkKeyValue(String key, String value) { if (TEST_KEY.equals(key)) { throw new TestKeyException(); } if (TEST_VALUE.equals(value)) { throw new TestValueException(); } } private static final long serialVersionUID = 0; } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ConstrainedMapTest.java
Java
asf20
3,299
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.Iterators.peekingIterator; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static java.util.Collections.emptyList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.IteratorTester; import junit.framework.TestCase; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * Unit test for {@link PeekingIterator}. * * @author Mick Killianey */ @SuppressWarnings("serial") // No serialization is used in this test @GwtCompatible(emulated = true) public class PeekingIteratorTest extends TestCase { /** * Version of {@link IteratorTester} that compares an iterator over * a given collection of elements (used as the reference iterator) * against a {@code PeekingIterator} that *wraps* such an iterator * (used as the target iterator). * * <p>This IteratorTester makes copies of the master so that it can * later verify that {@link PeekingIterator#remove()} removes the * same elements as the reference's iterator {@code #remove()}. */ private static class PeekingIteratorTester<T> extends IteratorTester<T> { private Iterable<T> master; private List<T> targetList; public PeekingIteratorTester(Collection<T> master) { super(master.size() + 3, MODIFIABLE, master, IteratorTester.KnownOrder.KNOWN_ORDER); this.master = master; } @Override protected Iterator<T> newTargetIterator() { // make copy from master to verify later targetList = Lists.newArrayList(master); Iterator<T> iterator = targetList.iterator(); return Iterators.peekingIterator(iterator); } @Override protected void verify(List<T> elements) { // verify same objects were removed from reference and target assertEquals(elements, targetList); } } private <T> void actsLikeIteratorHelper(final List<T> list) { // Check with modifiable copies of the list new PeekingIteratorTester<T>(list).test(); // Check with unmodifiable lists new IteratorTester<T>(list.size() * 2 + 2, UNMODIFIABLE, list, IteratorTester.KnownOrder.KNOWN_ORDER) { @Override protected Iterator<T> newTargetIterator() { Iterator<T> iterator = Collections.unmodifiableList(list).iterator(); return Iterators.peekingIterator(iterator); } }.test(); } public void testPeekingIteratorBehavesLikeIteratorOnEmptyIterable() { actsLikeIteratorHelper(Collections.emptyList()); } public void testPeekingIteratorBehavesLikeIteratorOnSingletonIterable() { actsLikeIteratorHelper(Collections.singletonList(new Object())); } // TODO(cpovirk): instead of skipping, use a smaller number of steps public void testPeekOnEmptyList() { List<?> list = Collections.emptyList(); Iterator<?> iterator = list.iterator(); PeekingIterator<?> peekingIterator = Iterators.peekingIterator(iterator); try { peekingIterator.peek(); fail("Should throw NoSuchElementException if nothing to peek()"); } catch (NoSuchElementException e) { /* expected */ } } public void testPeekDoesntChangeIteration() { List<?> list = Lists.newArrayList("A", "B", "C"); Iterator<?> iterator = list.iterator(); PeekingIterator<?> peekingIterator = Iterators.peekingIterator(iterator); assertEquals("Should be able to peek() at first element", "A", peekingIterator.peek()); assertEquals("Should be able to peek() first element multiple times", "A", peekingIterator.peek()); assertEquals("next() should still return first element after peeking", "A", peekingIterator.next()); assertEquals("Should be able to peek() at middle element", "B", peekingIterator.peek()); assertEquals("Should be able to peek() middle element multiple times", "B", peekingIterator.peek()); assertEquals("next() should still return middle element after peeking", "B", peekingIterator.next()); assertEquals("Should be able to peek() at last element", "C", peekingIterator.peek()); assertEquals("Should be able to peek() last element multiple times", "C", peekingIterator.peek()); assertEquals("next() should still return last element after peeking", "C", peekingIterator.next()); try { peekingIterator.peek(); fail("Should throw exception if no next to peek()"); } catch (NoSuchElementException e) { /* expected */ } try { peekingIterator.peek(); fail("Should continue to throw exception if no next to peek()"); } catch (NoSuchElementException e) { /* expected */ } try { peekingIterator.next(); fail("next() should still throw exception after the end of iteration"); } catch (NoSuchElementException e) { /* expected */ } } public void testCantRemoveAfterPeek() { List<String> list = Lists.newArrayList("A", "B", "C"); Iterator<String> iterator = list.iterator(); PeekingIterator<?> peekingIterator = Iterators.peekingIterator(iterator); assertEquals("A", peekingIterator.next()); assertEquals("B", peekingIterator.peek()); /* Should complain on attempt to remove() after peek(). */ try { peekingIterator.remove(); fail("remove() should throw IllegalStateException after a peek()"); } catch (IllegalStateException e) { /* expected */ } assertEquals("After remove() throws exception, peek should still be ok", "B", peekingIterator.peek()); /* Should recover to be able to remove() after next(). */ assertEquals("B", peekingIterator.next()); peekingIterator.remove(); assertEquals("Should have removed an element", 2, list.size()); assertFalse("Second element should be gone", list.contains("B")); } static class ThrowsAtEndException extends RuntimeException { /* nothing */ } /** * This Iterator claims to have more elements than the underlying * iterable, but when you try to fetch the extra elements, it throws * an unchecked exception. */ static class ThrowsAtEndIterator<E> implements Iterator<E> { Iterator<E> iterator; public ThrowsAtEndIterator(Iterable<E> iterable) { this.iterator = iterable.iterator(); } @Override public boolean hasNext() { return true; // pretend that you have more... } @Override public E next() { // ...but throw an unchecked exception when you ask for it. if (!iterator.hasNext()) { throw new ThrowsAtEndException(); } return iterator.next(); } @Override public void remove() { iterator.remove(); } } public void testPeekingIteratorDoesntAdvancePrematurely() throws Exception { /* * This test will catch problems where the underlying iterator * throws a RuntimeException when retrieving the nth element. * * If the PeekingIterator is caching elements too aggressively, * it may throw the exception on the (n-1)th element (oops!). */ /* Checks the case where the first element throws an exception. */ List<Integer> list = emptyList(); Iterator<Integer> iterator = peekingIterator(new ThrowsAtEndIterator<Integer>(list)); assertNextThrows(iterator); /* Checks the case where a later element throws an exception. */ list = Lists.newArrayList(1, 2); iterator = peekingIterator(new ThrowsAtEndIterator<Integer>(list)); assertTrue(iterator.hasNext()); iterator.next(); assertTrue(iterator.hasNext()); iterator.next(); assertNextThrows(iterator); } private void assertNextThrows(Iterator<?> iterator) { try { iterator.next(); fail(); } catch (ThrowsAtEndException expected) { } } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/PeekingIteratorTest.java
Java
asf20
8,574
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.google.TestBiMapGenerator; import junit.framework.TestCase; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Tests for {@code EnumHashBiMap}. * * @author Mike Bostock */ @GwtCompatible(emulated = true) public class EnumHashBiMapTest extends TestCase { private enum Currency { DOLLAR, FRANC, PESO, POUND, YEN } private enum Country { CANADA, CHILE, JAPAN, SWITZERLAND, UK } public static final class EnumHashBiMapGenerator implements TestBiMapGenerator<Country, String> { @SuppressWarnings("unchecked") @Override public BiMap<Country, String> create(Object... entries) { BiMap<Country, String> result = EnumHashBiMap.create(Country.class); for (Object o : entries) { Entry<Country, String> entry = (Entry<Country, String>) o; result.put(entry.getKey(), entry.getValue()); } return result; } @Override public SampleElements<Entry<Country, String>> samples() { return new SampleElements<Entry<Country, String>>( Maps.immutableEntry(Country.CANADA, "DOLLAR"), Maps.immutableEntry(Country.CHILE, "PESO"), Maps.immutableEntry(Country.UK, "POUND"), Maps.immutableEntry(Country.JAPAN, "YEN"), Maps.immutableEntry(Country.SWITZERLAND, "FRANC")); } @SuppressWarnings("unchecked") @Override public Entry<Country, String>[] createArray(int length) { return new Entry[length]; } @Override public Iterable<Entry<Country, String>> order(List<Entry<Country, String>> insertionOrder) { return insertionOrder; } @Override public Country[] createKeyArray(int length) { return new Country[length]; } @Override public String[] createValueArray(int length) { return new String[length]; } } public void testCreate() { EnumHashBiMap<Currency, String> bimap = EnumHashBiMap.create(Currency.class); assertTrue(bimap.isEmpty()); assertEquals("{}", bimap.toString()); assertEquals(HashBiMap.create(), bimap); bimap.put(Currency.DOLLAR, "dollar"); assertEquals("dollar", bimap.get(Currency.DOLLAR)); assertEquals(Currency.DOLLAR, bimap.inverse().get("dollar")); } public void testCreateFromMap() { /* Test with non-empty Map. */ Map<Currency, String> map = ImmutableMap.of( Currency.DOLLAR, "dollar", Currency.PESO, "peso", Currency.FRANC, "franc"); EnumHashBiMap<Currency, String> bimap = EnumHashBiMap.create(map); assertEquals("dollar", bimap.get(Currency.DOLLAR)); assertEquals(Currency.DOLLAR, bimap.inverse().get("dollar")); /* Map must have at least one entry if not an EnumHashBiMap. */ try { EnumHashBiMap.create( Collections.<Currency, String>emptyMap()); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException expected) {} /* Map can be empty if it's an EnumHashBiMap. */ Map<Currency, String> emptyBimap = EnumHashBiMap.create(Currency.class); bimap = EnumHashBiMap.create(emptyBimap); assertTrue(bimap.isEmpty()); /* Map can be empty if it's an EnumBiMap. */ Map<Currency, Country> emptyBimap2 = EnumBiMap.create(Currency.class, Country.class); EnumHashBiMap<Currency, Country> bimap2 = EnumHashBiMap.create(emptyBimap2); assertTrue(bimap2.isEmpty()); } public void testEnumHashBiMapConstructor() { /* Test that it copies existing entries. */ EnumHashBiMap<Currency, String> bimap1 = EnumHashBiMap.create(Currency.class); bimap1.put(Currency.DOLLAR, "dollar"); EnumHashBiMap<Currency, String> bimap2 = EnumHashBiMap.create(bimap1); assertEquals("dollar", bimap2.get(Currency.DOLLAR)); assertEquals(bimap1, bimap2); bimap2.inverse().put("franc", Currency.FRANC); assertEquals("franc", bimap2.get(Currency.FRANC)); assertNull(bimap1.get(Currency.FRANC)); assertFalse(bimap2.equals(bimap1)); /* Test that it can be empty. */ EnumHashBiMap<Currency, String> emptyBimap = EnumHashBiMap.create(Currency.class); EnumHashBiMap<Currency, String> bimap3 = EnumHashBiMap.create(emptyBimap); assertEquals(bimap3, emptyBimap); } public void testEnumBiMapConstructor() { /* Test that it copies existing entries. */ EnumBiMap<Currency, Country> bimap1 = EnumBiMap.create(Currency.class, Country.class); bimap1.put(Currency.DOLLAR, Country.SWITZERLAND); EnumHashBiMap<Currency, Object> bimap2 = // use supertype EnumHashBiMap.<Currency, Object>create(bimap1); assertEquals(Country.SWITZERLAND, bimap2.get(Currency.DOLLAR)); assertEquals(bimap1, bimap2); bimap2.inverse().put("franc", Currency.FRANC); assertEquals("franc", bimap2.get(Currency.FRANC)); assertNull(bimap1.get(Currency.FRANC)); assertFalse(bimap2.equals(bimap1)); /* Test that it can be empty. */ EnumBiMap<Currency, Country> emptyBimap = EnumBiMap.create(Currency.class, Country.class); EnumHashBiMap<Currency, Country> bimap3 = // use exact type EnumHashBiMap.create(emptyBimap); assertEquals(bimap3, emptyBimap); } public void testKeyType() { EnumHashBiMap<Currency, String> bimap = EnumHashBiMap.create(Currency.class); assertEquals(Currency.class, bimap.keyType()); } public void testEntrySet() { // Bug 3168290 Map<Currency, String> map = ImmutableMap.of( Currency.DOLLAR, "dollar", Currency.PESO, "peso", Currency.FRANC, "franc"); EnumHashBiMap<Currency, String> bimap = EnumHashBiMap.create(map); Set<Object> uniqueEntries = Sets.newIdentityHashSet(); uniqueEntries.addAll(bimap.entrySet()); assertEquals(3, uniqueEntries.size()); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/EnumHashBiMapTest.java
Java
asf20
6,643
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.RandomAccess; /** * Tests for {@code LinkedListMultimap}. * * @author Mike Bostock */ @GwtCompatible(emulated = true) public class LinkedListMultimapTest extends TestCase { protected LinkedListMultimap<String, Integer> create() { return LinkedListMultimap.create(); } /** * Confirm that get() returns a List that doesn't implement RandomAccess. */ public void testGetRandomAccess() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); assertFalse(multimap.get("foo") instanceof RandomAccess); assertFalse(multimap.get("bar") instanceof RandomAccess); } /** * Confirm that removeAll() returns a List that implements RandomAccess, even * though get() doesn't. */ public void testRemoveAllRandomAccess() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); assertTrue(multimap.removeAll("foo") instanceof RandomAccess); assertTrue(multimap.removeAll("bar") instanceof RandomAccess); } /** * Confirm that replaceValues() returns a List that implements RandomAccess, * even though get() doesn't. */ public void testReplaceValuesRandomAccess() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); assertTrue(multimap.replaceValues("foo", Arrays.asList(2, 4)) instanceof RandomAccess); assertTrue(multimap.replaceValues("bar", Arrays.asList(2, 4)) instanceof RandomAccess); } public void testCreateFromMultimap() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 3); multimap.put("foo", 2); LinkedListMultimap<String, Integer> copy = LinkedListMultimap.create(multimap); assertEquals(multimap, copy); ASSERT.that(copy.entries()).has().exactlyAs(multimap.entries()).inOrder(); } public void testCreateFromSize() { LinkedListMultimap<String, Integer> multimap = LinkedListMultimap.create(20); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("foo", 3); assertEquals(ImmutableList.of(1, 3), multimap.get("foo")); } public void testCreateFromIllegalSize() { try { LinkedListMultimap.create(-20); fail(); } catch (IllegalArgumentException expected) {} } public void testLinkedGetAdd() { LinkedListMultimap<String, Integer> map = create(); map.put("bar", 1); Collection<Integer> foos = map.get("foo"); foos.add(2); foos.add(3); map.put("bar", 4); map.put("foo", 5); assertEquals("{bar=[1, 4], foo=[2, 3, 5]}", map.toString()); assertEquals("[bar=1, foo=2, foo=3, bar=4, foo=5]", map.entries().toString()); } public void testLinkedGetInsert() { ListMultimap<String, Integer> map = create(); map.put("bar", 1); List<Integer> foos = map.get("foo"); foos.add(2); foos.add(0, 3); map.put("bar", 4); map.put("foo", 5); assertEquals("{bar=[1, 4], foo=[3, 2, 5]}", map.toString()); assertEquals("[bar=1, foo=3, foo=2, bar=4, foo=5]", map.entries().toString()); } public void testLinkedPutInOrder() { Multimap<String, Integer> map = create(); map.put("foo", 1); map.put("bar", 2); map.put("bar", 3); assertEquals("{foo=[1], bar=[2, 3]}", map.toString()); assertEquals("[foo=1, bar=2, bar=3]", map.entries().toString()); } public void testLinkedPutOutOfOrder() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); assertEquals("{bar=[1, 3], foo=[2]}", map.toString()); assertEquals("[bar=1, foo=2, bar=3]", map.entries().toString()); } public void testLinkedPutAllMultimap() { Multimap<String, Integer> src = create(); src.put("bar", 1); src.put("foo", 2); src.put("bar", 3); Multimap<String, Integer> dst = create(); dst.putAll(src); assertEquals("{bar=[1, 3], foo=[2]}", dst.toString()); assertEquals("[bar=1, foo=2, bar=3]", src.entries().toString()); } public void testLinkedReplaceValues() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); map.put("bar", 4); assertEquals("{bar=[1, 3, 4], foo=[2]}", map.toString()); map.replaceValues("bar", asList(1, 2)); assertEquals("[bar=1, foo=2, bar=2]", map.entries().toString()); assertEquals("{bar=[1, 2], foo=[2]}", map.toString()); } public void testLinkedClear() { ListMultimap<String, Integer> map = create(); map.put("foo", 1); map.put("foo", 2); map.put("bar", 3); List<Integer> foos = map.get("foo"); Collection<Integer> values = map.values(); assertEquals(asList(1, 2), foos); ASSERT.that(values).has().exactly(1, 2, 3).inOrder(); map.clear(); assertEquals(Collections.emptyList(), foos); ASSERT.that(values).isEmpty(); assertEquals("[]", map.entries().toString()); assertEquals("{}", map.toString()); } public void testLinkedKeySet() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); map.put("bar", 4); assertEquals("[bar, foo]", map.keySet().toString()); map.keySet().remove("bar"); assertEquals("{foo=[2]}", map.toString()); } public void testLinkedKeys() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); map.put("bar", 4); assertEquals("[bar=1, foo=2, bar=3, bar=4]", map.entries().toString()); ASSERT.that(map.keys()).has().exactly("bar", "foo", "bar", "bar").inOrder(); map.keys().remove("bar"); // bar is no longer the first key! assertEquals("{foo=[2], bar=[3, 4]}", map.toString()); } public void testLinkedValues() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); map.put("bar", 4); assertEquals("[1, 2, 3, 4]", map.values().toString()); map.values().remove(2); assertEquals("{bar=[1, 3, 4]}", map.toString()); } public void testLinkedEntries() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); Iterator<Map.Entry<String, Integer>> entries = map.entries().iterator(); Map.Entry<String, Integer> entry = entries.next(); assertEquals("bar", entry.getKey()); assertEquals(1, (int) entry.getValue()); entry = entries.next(); assertEquals("foo", entry.getKey()); assertEquals(2, (int) entry.getValue()); entry.setValue(4); entry = entries.next(); assertEquals("bar", entry.getKey()); assertEquals(3, (int) entry.getValue()); assertFalse(entries.hasNext()); entries.remove(); assertEquals("{bar=[1], foo=[4]}", map.toString()); } public void testLinkedAsMapEntries() { Multimap<String, Integer> map = create(); map.put("bar", 1); map.put("foo", 2); map.put("bar", 3); Iterator<Map.Entry<String, Collection<Integer>>> entries = map.asMap().entrySet().iterator(); Map.Entry<String, Collection<Integer>> entry = entries.next(); assertEquals("bar", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(1, 3).inOrder(); try { entry.setValue(Arrays.<Integer>asList()); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} entries.remove(); // clear entry = entries.next(); assertEquals("foo", entry.getKey()); ASSERT.that(entry.getValue()).has().item(2); assertFalse(entries.hasNext()); assertEquals("{foo=[2]}", map.toString()); } public void testEntriesAfterMultimapUpdate() { ListMultimap<String, Integer> multimap = create(); multimap.put("foo", 2); multimap.put("bar", 3); Collection<Map.Entry<String, Integer>> entries = multimap.entries(); Iterator<Map.Entry<String, Integer>> iterator = entries.iterator(); Map.Entry<String, Integer> entrya = iterator.next(); Map.Entry<String, Integer> entryb = iterator.next(); assertEquals(2, (int) multimap.get("foo").set(0, 4)); assertFalse(multimap.containsEntry("foo", 2)); assertTrue(multimap.containsEntry("foo", 4)); assertTrue(multimap.containsEntry("bar", 3)); assertEquals(4, (int) entrya.getValue()); assertEquals(3, (int) entryb.getValue()); assertTrue(multimap.put("foo", 5)); assertTrue(multimap.containsEntry("foo", 5)); assertTrue(multimap.containsEntry("foo", 4)); assertTrue(multimap.containsEntry("bar", 3)); assertEquals(4, (int) entrya.getValue()); assertEquals(3, (int) entryb.getValue()); } public void testEquals() { new EqualsTester() .addEqualityGroup( LinkedListMultimap.create(), LinkedListMultimap.create(), LinkedListMultimap.create(1)) .testEquals(); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/LinkedListMultimapTest.java
Java
asf20
10,010
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.Iterators.advance; import static com.google.common.collect.Iterators.get; import static com.google.common.collect.Iterators.getLast; import static com.google.common.collect.Lists.newArrayList; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.RandomAccess; import java.util.Set; import java.util.Vector; /** * Unit test for {@code Iterators}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class IteratorsTest extends TestCase { public void testEmptyIterator() { Iterator<String> iterator = Iterators.emptyIterator(); assertFalse(iterator.hasNext()); try { iterator.next(); fail("no exception thrown"); } catch (NoSuchElementException expected) { } try { iterator.remove(); fail("no exception thrown"); } catch (UnsupportedOperationException expected) { } } public void testEmptyListIterator() { ListIterator<String> iterator = Iterators.emptyListIterator(); assertFalse(iterator.hasNext()); assertFalse(iterator.hasPrevious()); assertEquals(0, iterator.nextIndex()); assertEquals(-1, iterator.previousIndex()); try { iterator.next(); fail("no exception thrown"); } catch (NoSuchElementException expected) { } try { iterator.previous(); fail("no exception thrown"); } catch (NoSuchElementException expected) { } try { iterator.remove(); fail("no exception thrown"); } catch (UnsupportedOperationException expected) { } try { iterator.set("a"); fail("no exception thrown"); } catch (UnsupportedOperationException expected) { } try { iterator.add("a"); fail("no exception thrown"); } catch (UnsupportedOperationException expected) { } } public void testEmptyModifiableIterator() { Iterator<String> iterator = Iterators.emptyModifiableIterator(); assertFalse(iterator.hasNext()); try { iterator.next(); fail("Expected NoSuchElementException"); } catch (NoSuchElementException expected) { } try { iterator.remove(); fail("Expected IllegalStateException"); } catch (IllegalStateException expected) { } } public void testSize0() { Iterator<String> iterator = Iterators.emptyIterator(); assertEquals(0, Iterators.size(iterator)); } public void testSize1() { Iterator<Integer> iterator = Collections.singleton(0).iterator(); assertEquals(1, Iterators.size(iterator)); } public void testSize_partiallyConsumed() { Iterator<Integer> iterator = asList(1, 2, 3, 4, 5).iterator(); iterator.next(); iterator.next(); assertEquals(3, Iterators.size(iterator)); } public void test_contains_nonnull_yes() { Iterator<String> set = asList("a", null, "b").iterator(); assertTrue(Iterators.contains(set, "b")); } public void test_contains_nonnull_no() { Iterator<String> set = asList("a", "b").iterator(); assertFalse(Iterators.contains(set, "c")); } public void test_contains_null_yes() { Iterator<String> set = asList("a", null, "b").iterator(); assertTrue(Iterators.contains(set, null)); } public void test_contains_null_no() { Iterator<String> set = asList("a", "b").iterator(); assertFalse(Iterators.contains(set, null)); } public void testGetOnlyElement_noDefault_valid() { Iterator<String> iterator = Collections.singletonList("foo").iterator(); assertEquals("foo", Iterators.getOnlyElement(iterator)); } public void testGetOnlyElement_noDefault_empty() { Iterator<String> iterator = Iterators.emptyIterator(); try { Iterators.getOnlyElement(iterator); fail(); } catch (NoSuchElementException expected) { } } public void testGetOnlyElement_noDefault_moreThanOneLessThanFiveElements() { Iterator<String> iterator = asList("one", "two").iterator(); try { Iterators.getOnlyElement(iterator); fail(); } catch (IllegalArgumentException expected) { assertEquals("expected one element but was: <one, two>", expected.getMessage()); } } public void testGetOnlyElement_noDefault_fiveElements() { Iterator<String> iterator = asList("one", "two", "three", "four", "five").iterator(); try { Iterators.getOnlyElement(iterator); fail(); } catch (IllegalArgumentException expected) { assertEquals("expected one element but was: " + "<one, two, three, four, five>", expected.getMessage()); } } public void testGetOnlyElement_noDefault_moreThanFiveElements() { Iterator<String> iterator = asList("one", "two", "three", "four", "five", "six").iterator(); try { Iterators.getOnlyElement(iterator); fail(); } catch (IllegalArgumentException expected) { assertEquals("expected one element but was: " + "<one, two, three, four, five, ...>", expected.getMessage()); } } public void testGetOnlyElement_withDefault_singleton() { Iterator<String> iterator = Collections.singletonList("foo").iterator(); assertEquals("foo", Iterators.getOnlyElement(iterator, "bar")); } public void testGetOnlyElement_withDefault_empty() { Iterator<String> iterator = Iterators.emptyIterator(); assertEquals("bar", Iterators.getOnlyElement(iterator, "bar")); } public void testGetOnlyElement_withDefault_empty_null() { Iterator<String> iterator = Iterators.emptyIterator(); assertNull(Iterators.getOnlyElement(iterator, null)); } public void testGetOnlyElement_withDefault_two() { Iterator<String> iterator = asList("foo", "bar").iterator(); try { Iterators.getOnlyElement(iterator, "x"); fail(); } catch (IllegalArgumentException expected) { assertEquals("expected one element but was: <foo, bar>", expected.getMessage()); } } public void testFilterSimple() { Iterator<String> unfiltered = Lists.newArrayList("foo", "bar").iterator(); Iterator<String> filtered = Iterators.filter(unfiltered, Predicates.equalTo("foo")); List<String> expected = Collections.singletonList("foo"); List<String> actual = Lists.newArrayList(filtered); assertEquals(expected, actual); } public void testFilterNoMatch() { Iterator<String> unfiltered = Lists.newArrayList("foo", "bar").iterator(); Iterator<String> filtered = Iterators.filter(unfiltered, Predicates.alwaysFalse()); List<String> expected = Collections.emptyList(); List<String> actual = Lists.newArrayList(filtered); assertEquals(expected, actual); } public void testFilterMatchAll() { Iterator<String> unfiltered = Lists.newArrayList("foo", "bar").iterator(); Iterator<String> filtered = Iterators.filter(unfiltered, Predicates.alwaysTrue()); List<String> expected = Lists.newArrayList("foo", "bar"); List<String> actual = Lists.newArrayList(filtered); assertEquals(expected, actual); } public void testFilterNothing() { Iterator<String> unfiltered = Collections.<String>emptyList().iterator(); Iterator<String> filtered = Iterators.filter(unfiltered, new Predicate<String>() { @Override public boolean apply(String s) { throw new AssertionFailedError("Should never be evaluated"); } }); List<String> expected = Collections.emptyList(); List<String> actual = Lists.newArrayList(filtered); assertEquals(expected, actual); } public void testAny() { List<String> list = Lists.newArrayList(); Predicate<String> predicate = Predicates.equalTo("pants"); assertFalse(Iterators.any(list.iterator(), predicate)); list.add("cool"); assertFalse(Iterators.any(list.iterator(), predicate)); list.add("pants"); assertTrue(Iterators.any(list.iterator(), predicate)); } public void testAll() { List<String> list = Lists.newArrayList(); Predicate<String> predicate = Predicates.equalTo("cool"); assertTrue(Iterators.all(list.iterator(), predicate)); list.add("cool"); assertTrue(Iterators.all(list.iterator(), predicate)); list.add("pants"); assertFalse(Iterators.all(list.iterator(), predicate)); } public void testFind_firstElement() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("cool", Iterators.find(iterator, Predicates.equalTo("cool"))); assertEquals("pants", iterator.next()); } public void testFind_lastElement() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("pants", Iterators.find(iterator, Predicates.equalTo("pants"))); assertFalse(iterator.hasNext()); } public void testFind_notPresent() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); try { Iterators.find(iterator, Predicates.alwaysFalse()); fail(); } catch (NoSuchElementException e) { } assertFalse(iterator.hasNext()); } public void testFind_matchAlways() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("cool", Iterators.find(iterator, Predicates.alwaysTrue())); } public void testFind_withDefault_first() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("cool", Iterators.find(iterator, Predicates.equalTo("cool"), "woot")); assertEquals("pants", iterator.next()); } public void testFind_withDefault_last() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("pants", Iterators.find(iterator, Predicates.equalTo("pants"), "woot")); assertFalse(iterator.hasNext()); } public void testFind_withDefault_notPresent() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("woot", Iterators.find(iterator, Predicates.alwaysFalse(), "woot")); assertFalse(iterator.hasNext()); } public void testFind_withDefault_notPresent_nullReturn() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertNull( Iterators.find(iterator, Predicates.alwaysFalse(), null)); assertFalse(iterator.hasNext()); } public void testFind_withDefault_matchAlways() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("cool", Iterators.find(iterator, Predicates.alwaysTrue(), "woot")); assertEquals("pants", iterator.next()); } public void testTryFind_firstElement() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("cool", Iterators.tryFind(iterator, Predicates.equalTo("cool")).get()); } public void testTryFind_lastElement() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("pants", Iterators.tryFind(iterator, Predicates.equalTo("pants")).get()); } public void testTryFind_alwaysTrue() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("cool", Iterators.tryFind(iterator, Predicates.alwaysTrue()).get()); } public void testTryFind_alwaysFalse_orDefault() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertEquals("woot", Iterators.tryFind(iterator, Predicates.alwaysFalse()).or("woot")); assertFalse(iterator.hasNext()); } public void testTryFind_alwaysFalse_isPresent() { Iterable<String> list = Lists.newArrayList("cool", "pants"); Iterator<String> iterator = list.iterator(); assertFalse( Iterators.tryFind(iterator, Predicates.alwaysFalse()).isPresent()); assertFalse(iterator.hasNext()); } public void testTransform() { Iterator<String> input = asList("1", "2", "3").iterator(); Iterator<Integer> result = Iterators.transform(input, new Function<String, Integer>() { @Override public Integer apply(String from) { return Integer.valueOf(from); } }); List<Integer> actual = Lists.newArrayList(result); List<Integer> expected = asList(1, 2, 3); assertEquals(expected, actual); } public void testTransformRemove() { List<String> list = Lists.newArrayList("1", "2", "3"); Iterator<String> input = list.iterator(); Iterator<Integer> iterator = Iterators.transform(input, new Function<String, Integer>() { @Override public Integer apply(String from) { return Integer.valueOf(from); } }); assertEquals(Integer.valueOf(1), iterator.next()); assertEquals(Integer.valueOf(2), iterator.next()); iterator.remove(); assertEquals(asList("1", "3"), list); } public void testPoorlyBehavedTransform() { Iterator<String> input = asList("1", null, "3").iterator(); Iterator<Integer> result = Iterators.transform(input, new Function<String, Integer>() { @Override public Integer apply(String from) { return Integer.valueOf(from); } }); result.next(); try { result.next(); fail("Expected NFE"); } catch (NumberFormatException nfe) { // Expected to fail. } } public void testNullFriendlyTransform() { Iterator<Integer> input = asList(1, 2, null, 3).iterator(); Iterator<String> result = Iterators.transform(input, new Function<Integer, String>() { @Override public String apply(Integer from) { return String.valueOf(from); } }); List<String> actual = Lists.newArrayList(result); List<String> expected = asList("1", "2", "null", "3"); assertEquals(expected, actual); } public void testCycleOfEmpty() { // "<String>" for javac 1.5. Iterator<String> cycle = Iterators.<String>cycle(); assertFalse(cycle.hasNext()); } public void testCycleOfOne() { Iterator<String> cycle = Iterators.cycle("a"); for (int i = 0; i < 3; i++) { assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); } } public void testCycleOfOneWithRemove() { Iterable<String> iterable = Lists.newArrayList("a"); Iterator<String> cycle = Iterators.cycle(iterable); assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); cycle.remove(); assertEquals(Collections.emptyList(), iterable); assertFalse(cycle.hasNext()); } public void testCycleOfTwo() { Iterator<String> cycle = Iterators.cycle("a", "b"); for (int i = 0; i < 3; i++) { assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); assertTrue(cycle.hasNext()); assertEquals("b", cycle.next()); } } public void testCycleOfTwoWithRemove() { Iterable<String> iterable = Lists.newArrayList("a", "b"); Iterator<String> cycle = Iterators.cycle(iterable); assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); assertTrue(cycle.hasNext()); assertEquals("b", cycle.next()); assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); cycle.remove(); assertEquals(Collections.singletonList("b"), iterable); assertTrue(cycle.hasNext()); assertEquals("b", cycle.next()); assertTrue(cycle.hasNext()); assertEquals("b", cycle.next()); cycle.remove(); assertEquals(Collections.emptyList(), iterable); assertFalse(cycle.hasNext()); } public void testCycleRemoveWithoutNext() { Iterator<String> cycle = Iterators.cycle("a", "b"); assertTrue(cycle.hasNext()); try { cycle.remove(); fail("no exception thrown"); } catch (IllegalStateException expected) { } } public void testCycleRemoveSameElementTwice() { Iterator<String> cycle = Iterators.cycle("a", "b"); cycle.next(); cycle.remove(); try { cycle.remove(); fail("no exception thrown"); } catch (IllegalStateException expected) { } } public void testCycleWhenRemoveIsNotSupported() { Iterable<String> iterable = asList("a", "b"); Iterator<String> cycle = Iterators.cycle(iterable); cycle.next(); try { cycle.remove(); fail("no exception thrown"); } catch (UnsupportedOperationException expected) { } } public void testCycleRemoveAfterHasNext() { Iterable<String> iterable = Lists.newArrayList("a"); Iterator<String> cycle = Iterators.cycle(iterable); assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); assertTrue(cycle.hasNext()); cycle.remove(); assertEquals(Collections.emptyList(), iterable); assertFalse(cycle.hasNext()); } public void testCycleNoSuchElementException() { Iterable<String> iterable = Lists.newArrayList("a"); Iterator<String> cycle = Iterators.cycle(iterable); assertTrue(cycle.hasNext()); assertEquals("a", cycle.next()); cycle.remove(); assertFalse(cycle.hasNext()); try { cycle.next(); fail(); } catch (NoSuchElementException expected) {} } /** * Illustrates the somewhat bizarre behavior when a null is passed in. */ public void testConcatContainingNull() { @SuppressWarnings("unchecked") Iterator<Iterator<Integer>> input = asList(iterateOver(1, 2), null, iterateOver(3)).iterator(); Iterator<Integer> result = Iterators.concat(input); assertEquals(1, (int) result.next()); assertEquals(2, (int) result.next()); try { result.hasNext(); fail("no exception thrown"); } catch (NullPointerException e) { } try { result.next(); fail("no exception thrown"); } catch (NullPointerException e) { } // There is no way to get "through" to the 3. Buh-bye } @SuppressWarnings("unchecked") public void testConcatVarArgsContainingNull() { try { Iterators.concat(iterateOver(1, 2), null, iterateOver(3), iterateOver(4), iterateOver(5)); fail("no exception thrown"); } catch (NullPointerException e) { } } public void testAddAllWithEmptyIterator() { List<String> alreadyThere = Lists.newArrayList("already", "there"); boolean changed = Iterators.addAll(alreadyThere, Iterators.<String>emptyIterator()); ASSERT.that(alreadyThere).has().exactly("already", "there").inOrder(); assertFalse(changed); } public void testAddAllToList() { List<String> alreadyThere = Lists.newArrayList("already", "there"); List<String> freshlyAdded = Lists.newArrayList("freshly", "added"); boolean changed = Iterators.addAll(alreadyThere, freshlyAdded.iterator()); ASSERT.that(alreadyThere).has().exactly("already", "there", "freshly", "added"); assertTrue(changed); } public void testAddAllToSet() { Set<String> alreadyThere = Sets.newLinkedHashSet(asList("already", "there")); List<String> oneMore = Lists.newArrayList("there"); boolean changed = Iterators.addAll(alreadyThere, oneMore.iterator()); ASSERT.that(alreadyThere).has().exactly("already", "there").inOrder(); assertFalse(changed); } private static Iterator<Integer> iterateOver(final Integer... values) { return newArrayList(values).iterator(); } public void testElementsEqual() { Iterable<?> a; Iterable<?> b; // Base case. a = Lists.newArrayList(); b = Collections.emptySet(); assertTrue(Iterators.elementsEqual(a.iterator(), b.iterator())); // A few elements. a = asList(4, 8, 15, 16, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertTrue(Iterators.elementsEqual(a.iterator(), b.iterator())); // The same, but with nulls. a = asList(4, 8, null, 16, 23, 42); b = asList(4, 8, null, 16, 23, 42); assertTrue(Iterators.elementsEqual(a.iterator(), b.iterator())); // Different Iterable types (still equal elements, though). a = ImmutableList.of(4, 8, 15, 16, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertTrue(Iterators.elementsEqual(a.iterator(), b.iterator())); // An element differs. a = asList(4, 8, 15, 12, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterators.elementsEqual(a.iterator(), b.iterator())); // null versus non-null. a = asList(4, 8, 15, null, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterators.elementsEqual(a.iterator(), b.iterator())); assertFalse(Iterators.elementsEqual(b.iterator(), a.iterator())); // Different lengths. a = asList(4, 8, 15, 16, 23); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterators.elementsEqual(a.iterator(), b.iterator())); assertFalse(Iterators.elementsEqual(b.iterator(), a.iterator())); // Different lengths, one is empty. a = Collections.emptySet(); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterators.elementsEqual(a.iterator(), b.iterator())); assertFalse(Iterators.elementsEqual(b.iterator(), a.iterator())); } public void testPartition_badSize() { Iterator<Integer> source = Iterators.singletonIterator(1); try { Iterators.partition(source, 0); fail(); } catch (IllegalArgumentException expected) { } } public void testPartition_empty() { Iterator<Integer> source = Iterators.emptyIterator(); Iterator<List<Integer>> partitions = Iterators.partition(source, 1); assertFalse(partitions.hasNext()); } public void testPartition_singleton1() { Iterator<Integer> source = Iterators.singletonIterator(1); Iterator<List<Integer>> partitions = Iterators.partition(source, 1); assertTrue(partitions.hasNext()); assertTrue(partitions.hasNext()); assertEquals(ImmutableList.of(1), partitions.next()); assertFalse(partitions.hasNext()); } public void testPartition_singleton2() { Iterator<Integer> source = Iterators.singletonIterator(1); Iterator<List<Integer>> partitions = Iterators.partition(source, 2); assertTrue(partitions.hasNext()); assertTrue(partitions.hasNext()); assertEquals(ImmutableList.of(1), partitions.next()); assertFalse(partitions.hasNext()); } public void testPartition_view() { List<Integer> list = asList(1, 2); Iterator<List<Integer>> partitions = Iterators.partition(list.iterator(), 1); // Changes before the partition is retrieved are reflected list.set(0, 3); List<Integer> first = partitions.next(); // Changes after are not list.set(0, 4); assertEquals(ImmutableList.of(3), first); } public void testPaddedPartition_badSize() { Iterator<Integer> source = Iterators.singletonIterator(1); try { Iterators.paddedPartition(source, 0); fail(); } catch (IllegalArgumentException expected) { } } public void testPaddedPartition_empty() { Iterator<Integer> source = Iterators.emptyIterator(); Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 1); assertFalse(partitions.hasNext()); } public void testPaddedPartition_singleton1() { Iterator<Integer> source = Iterators.singletonIterator(1); Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 1); assertTrue(partitions.hasNext()); assertTrue(partitions.hasNext()); assertEquals(ImmutableList.of(1), partitions.next()); assertFalse(partitions.hasNext()); } public void testPaddedPartition_singleton2() { Iterator<Integer> source = Iterators.singletonIterator(1); Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 2); assertTrue(partitions.hasNext()); assertTrue(partitions.hasNext()); assertEquals(asList(1, null), partitions.next()); assertFalse(partitions.hasNext()); } public void testPaddedPartition_view() { List<Integer> list = asList(1, 2); Iterator<List<Integer>> partitions = Iterators.paddedPartition(list.iterator(), 1); // Changes before the PaddedPartition is retrieved are reflected list.set(0, 3); List<Integer> first = partitions.next(); // Changes after are not list.set(0, 4); assertEquals(ImmutableList.of(3), first); } public void testPaddedPartitionRandomAccess() { Iterator<Integer> source = asList(1, 2, 3).iterator(); Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 2); assertTrue(partitions.next() instanceof RandomAccess); assertTrue(partitions.next() instanceof RandomAccess); } public void testForArrayEmpty() { String[] array = new String[0]; Iterator<String> iterator = Iterators.forArray(array); assertFalse(iterator.hasNext()); try { iterator.next(); fail(); } catch (NoSuchElementException expected) {} } public void testForArrayTypical() { String[] array = {"foo", "bar"}; Iterator<String> iterator = Iterators.forArray(array); assertTrue(iterator.hasNext()); assertEquals("foo", iterator.next()); assertTrue(iterator.hasNext()); try { iterator.remove(); fail(); } catch (UnsupportedOperationException expected) {} assertEquals("bar", iterator.next()); assertFalse(iterator.hasNext()); try { iterator.next(); fail(); } catch (NoSuchElementException expected) {} } public void testForArrayOffset() { String[] array = {"foo", "bar", "cat", "dog"}; Iterator<String> iterator = Iterators.forArray(array, 1, 2, 0); assertTrue(iterator.hasNext()); assertEquals("bar", iterator.next()); assertTrue(iterator.hasNext()); assertEquals("cat", iterator.next()); assertFalse(iterator.hasNext()); try { Iterators.forArray(array, 2, 3, 0); fail(); } catch (IndexOutOfBoundsException expected) {} } public void testForArrayLength0() { String[] array = {"foo", "bar"}; assertFalse(Iterators.forArray(array, 0, 0, 0).hasNext()); assertFalse(Iterators.forArray(array, 1, 0, 0).hasNext()); assertFalse(Iterators.forArray(array, 2, 0, 0).hasNext()); try { Iterators.forArray(array, -1, 0, 0); fail(); } catch (IndexOutOfBoundsException expected) {} try { Iterators.forArray(array, 3, 0, 0); fail(); } catch (IndexOutOfBoundsException expected) {} } public void testForEnumerationEmpty() { Enumeration<Integer> enumer = enumerate(); Iterator<Integer> iter = Iterators.forEnumeration(enumer); assertFalse(iter.hasNext()); try { iter.next(); fail(); } catch (NoSuchElementException expected) { } } public void testForEnumerationSingleton() { Enumeration<Integer> enumer = enumerate(1); Iterator<Integer> iter = Iterators.forEnumeration(enumer); assertTrue(iter.hasNext()); assertTrue(iter.hasNext()); assertEquals(1, (int) iter.next()); try { iter.remove(); fail(); } catch (UnsupportedOperationException expected) { } assertFalse(iter.hasNext()); try { iter.next(); fail(); } catch (NoSuchElementException expected) { } } public void testForEnumerationTypical() { Enumeration<Integer> enumer = enumerate(1, 2, 3); Iterator<Integer> iter = Iterators.forEnumeration(enumer); assertTrue(iter.hasNext()); assertEquals(1, (int) iter.next()); assertTrue(iter.hasNext()); assertEquals(2, (int) iter.next()); assertTrue(iter.hasNext()); assertEquals(3, (int) iter.next()); assertFalse(iter.hasNext()); } public void testAsEnumerationEmpty() { Iterator<Integer> iter = Iterators.emptyIterator(); Enumeration<Integer> enumer = Iterators.asEnumeration(iter); assertFalse(enumer.hasMoreElements()); try { enumer.nextElement(); fail(); } catch (NoSuchElementException expected) { } } public void testAsEnumerationSingleton() { Iterator<Integer> iter = ImmutableList.of(1).iterator(); Enumeration<Integer> enumer = Iterators.asEnumeration(iter); assertTrue(enumer.hasMoreElements()); assertTrue(enumer.hasMoreElements()); assertEquals(1, (int) enumer.nextElement()); assertFalse(enumer.hasMoreElements()); try { enumer.nextElement(); fail(); } catch (NoSuchElementException expected) { } } public void testAsEnumerationTypical() { Iterator<Integer> iter = ImmutableList.of(1, 2, 3).iterator(); Enumeration<Integer> enumer = Iterators.asEnumeration(iter); assertTrue(enumer.hasMoreElements()); assertEquals(1, (int) enumer.nextElement()); assertTrue(enumer.hasMoreElements()); assertEquals(2, (int) enumer.nextElement()); assertTrue(enumer.hasMoreElements()); assertEquals(3, (int) enumer.nextElement()); assertFalse(enumer.hasMoreElements()); } private static Enumeration<Integer> enumerate(Integer... ints) { Vector<Integer> vector = new Vector<Integer>(); vector.addAll(asList(ints)); return vector.elements(); } public void testToString() { Iterator<String> iterator = Lists.newArrayList("yam", "bam", "jam", "ham").iterator(); assertEquals("[yam, bam, jam, ham]", Iterators.toString(iterator)); } public void testToStringWithNull() { Iterator<String> iterator = Lists.newArrayList("hello", null, "world").iterator(); assertEquals("[hello, null, world]", Iterators.toString(iterator)); } public void testToStringEmptyIterator() { Iterator<String> iterator = Collections.<String>emptyList().iterator(); assertEquals("[]", Iterators.toString(iterator)); } public void testLimit() { List<String> list = newArrayList(); try { Iterators.limit(list.iterator(), -1); fail("expected exception"); } catch (IllegalArgumentException expected) { // expected } assertFalse(Iterators.limit(list.iterator(), 0).hasNext()); assertFalse(Iterators.limit(list.iterator(), 1).hasNext()); list.add("cool"); assertFalse(Iterators.limit(list.iterator(), 0).hasNext()); assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 1))); assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 2))); list.add("pants"); assertFalse(Iterators.limit(list.iterator(), 0).hasNext()); assertEquals(ImmutableList.of("cool"), newArrayList(Iterators.limit(list.iterator(), 1))); assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 2))); assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 3))); } public void testLimitRemove() { List<String> list = newArrayList(); list.add("cool"); list.add("pants"); Iterator<String> iterator = Iterators.limit(list.iterator(), 1); iterator.next(); iterator.remove(); assertFalse(iterator.hasNext()); assertEquals(1, list.size()); assertEquals("pants", list.get(0)); } public void testGetNext_withDefault_singleton() { Iterator<String> iterator = Collections.singletonList("foo").iterator(); assertEquals("foo", Iterators.getNext(iterator, "bar")); } public void testGetNext_withDefault_empty() { Iterator<String> iterator = Iterators.emptyIterator(); assertEquals("bar", Iterators.getNext(iterator, "bar")); } public void testGetNext_withDefault_empty_null() { Iterator<String> iterator = Iterators.emptyIterator(); assertNull(Iterators.getNext(iterator, null)); } public void testGetNext_withDefault_two() { Iterator<String> iterator = asList("foo", "bar").iterator(); assertEquals("foo", Iterators.getNext(iterator, "x")); } public void testGetLast_basic() { List<String> list = newArrayList(); list.add("a"); list.add("b"); assertEquals("b", getLast(list.iterator())); } public void testGetLast_exception() { List<String> list = newArrayList(); try { getLast(list.iterator()); fail(); } catch (NoSuchElementException expected) { } } public void testGetLast_withDefault_singleton() { Iterator<String> iterator = Collections.singletonList("foo").iterator(); assertEquals("foo", Iterators.getLast(iterator, "bar")); } public void testGetLast_withDefault_empty() { Iterator<String> iterator = Iterators.emptyIterator(); assertEquals("bar", Iterators.getLast(iterator, "bar")); } public void testGetLast_withDefault_empty_null() { Iterator<String> iterator = Iterators.emptyIterator(); assertNull(Iterators.getLast(iterator, null)); } public void testGetLast_withDefault_two() { Iterator<String> iterator = asList("foo", "bar").iterator(); assertEquals("bar", Iterators.getLast(iterator, "x")); } public void testGet_basic() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); assertEquals("b", get(iterator, 1)); assertFalse(iterator.hasNext()); } public void testGet_atSize() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); try { get(iterator, 2); fail(); } catch (IndexOutOfBoundsException expected) {} assertFalse(iterator.hasNext()); } public void testGet_pastEnd() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); try { get(iterator, 5); fail(); } catch (IndexOutOfBoundsException expected) {} assertFalse(iterator.hasNext()); } public void testGet_empty() { List<String> list = newArrayList(); Iterator<String> iterator = list.iterator(); try { get(iterator, 0); fail(); } catch (IndexOutOfBoundsException expected) {} assertFalse(iterator.hasNext()); } public void testGet_negativeIndex() { List<String> list = newArrayList("a", "b", "c"); Iterator<String> iterator = list.iterator(); try { get(iterator, -1); fail(); } catch (IndexOutOfBoundsException expected) {} } public void testGet_withDefault_basic() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); assertEquals("a", get(iterator, 0, "c")); assertTrue(iterator.hasNext()); } public void testGet_withDefault_atSize() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); assertEquals("c", get(iterator, 2, "c")); assertFalse(iterator.hasNext()); } public void testGet_withDefault_pastEnd() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); assertEquals("c", get(iterator, 3, "c")); assertFalse(iterator.hasNext()); } public void testGet_withDefault_negativeIndex() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); try { get(iterator, -1, "c"); fail(); } catch (IndexOutOfBoundsException expected) { // pass } assertTrue(iterator.hasNext()); } public void testAdvance_basic() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); advance(iterator, 1); assertEquals("b", iterator.next()); } public void testAdvance_pastEnd() { List<String> list = newArrayList(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); advance(iterator, 5); assertFalse(iterator.hasNext()); } public void testAdvance_illegalArgument() { List<String> list = newArrayList("a", "b", "c"); Iterator<String> iterator = list.iterator(); try { advance(iterator, -1); fail(); } catch (IllegalArgumentException expected) {} } public void testFrequency() { List<String> list = newArrayList("a", null, "b", null, "a", null); assertEquals(2, Iterators.frequency(list.iterator(), "a")); assertEquals(1, Iterators.frequency(list.iterator(), "b")); assertEquals(0, Iterators.frequency(list.iterator(), "c")); assertEquals(0, Iterators.frequency(list.iterator(), 4.2)); assertEquals(3, Iterators.frequency(list.iterator(), null)); } public void testRemoveAll() { List<String> list = newArrayList("a", "b", "c", "d", "e"); assertTrue(Iterators.removeAll( list.iterator(), newArrayList("b", "d", "f"))); assertEquals(newArrayList("a", "c", "e"), list); assertFalse(Iterators.removeAll( list.iterator(), newArrayList("x", "y", "z"))); assertEquals(newArrayList("a", "c", "e"), list); } public void testRemoveIf() { List<String> list = newArrayList("a", "b", "c", "d", "e"); assertTrue(Iterators.removeIf( list.iterator(), new Predicate<String>() { @Override public boolean apply(String s) { return s.equals("b") || s.equals("d") || s.equals("f"); } })); assertEquals(newArrayList("a", "c", "e"), list); assertFalse(Iterators.removeIf( list.iterator(), new Predicate<String>() { @Override public boolean apply(String s) { return s.equals("x") || s.equals("y") || s.equals("z"); } })); assertEquals(newArrayList("a", "c", "e"), list); } public void testRetainAll() { List<String> list = newArrayList("a", "b", "c", "d", "e"); assertTrue(Iterators.retainAll( list.iterator(), newArrayList("b", "d", "f"))); assertEquals(newArrayList("b", "d"), list); assertFalse(Iterators.retainAll( list.iterator(), newArrayList("b", "e", "d"))); assertEquals(newArrayList("b", "d"), list); } public void testConsumingIterator() { // Test data List<String> list = Lists.newArrayList("a", "b"); // Test & Verify Iterator<String> consumingIterator = Iterators.consumingIterator(list.iterator()); assertEquals("Iterators.consumingIterator(...)", consumingIterator.toString()); ASSERT.that(list).has().exactly("a", "b").inOrder(); assertTrue(consumingIterator.hasNext()); ASSERT.that(list).has().exactly("a", "b").inOrder(); assertEquals("a", consumingIterator.next()); ASSERT.that(list).has().item("b"); assertTrue(consumingIterator.hasNext()); assertEquals("b", consumingIterator.next()); ASSERT.that(list).isEmpty(); assertFalse(consumingIterator.hasNext()); } public void testIndexOf_consumedData() { Iterator<String> iterator = Lists.newArrayList("manny", "mo", "jack").iterator(); assertEquals(1, Iterators.indexOf(iterator, Predicates.equalTo("mo"))); assertEquals("jack", iterator.next()); assertFalse(iterator.hasNext()); } public void testIndexOf_consumedDataWithDuplicates() { Iterator<String> iterator = Lists.newArrayList("manny", "mo", "mo", "jack").iterator(); assertEquals(1, Iterators.indexOf(iterator, Predicates.equalTo("mo"))); assertEquals("mo", iterator.next()); assertEquals("jack", iterator.next()); assertFalse(iterator.hasNext()); } public void testIndexOf_consumedDataNoMatch() { Iterator<String> iterator = Lists.newArrayList("manny", "mo", "mo", "jack").iterator(); assertEquals(-1, Iterators.indexOf(iterator, Predicates.equalTo("bob"))); assertFalse(iterator.hasNext()); } @SuppressWarnings("deprecation") public void testUnmodifiableIteratorShortCircuit() { Iterator<String> mod = Lists.newArrayList("a", "b", "c").iterator(); UnmodifiableIterator<String> unmod = Iterators.unmodifiableIterator(mod); assertNotSame(mod, unmod); assertSame(unmod, Iterators.unmodifiableIterator(unmod)); assertSame(unmod, Iterators.unmodifiableIterator((Iterator<String>) unmod)); } @SuppressWarnings("deprecation") public void testPeekingIteratorShortCircuit() { Iterator<String> nonpeek = Lists.newArrayList("a", "b", "c").iterator(); PeekingIterator<String> peek = Iterators.peekingIterator(nonpeek); assertNotSame(peek, nonpeek); assertSame(peek, Iterators.peekingIterator(peek)); assertSame(peek, Iterators.peekingIterator((Iterator<String>) peek)); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/IteratorsTest.java
Java
asf20
41,982
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.Iterables.unmodifiableIterable; import static com.google.common.collect.Sets.newEnumSet; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.Sets.powerSet; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.IteratorTester; import com.google.common.collect.testing.MinimalIterable; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nullable; /** * Unit test for {@code Sets}. * * @author Kevin Bourrillion * @author Jared Levy */ @GwtCompatible(emulated = true) public class SetsTest extends TestCase { private static final IteratorTester.KnownOrder KNOWN_ORDER = IteratorTester.KnownOrder.KNOWN_ORDER; private static final Collection<Integer> EMPTY_COLLECTION = Arrays.<Integer>asList(); private static final Collection<Integer> SOME_COLLECTION = Arrays.asList(0, 1, 1); private static final Iterable<Integer> SOME_ITERABLE = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return SOME_COLLECTION.iterator(); } }; private static final List<Integer> LONGER_LIST = Arrays.asList(8, 6, 7, 5, 3, 0, 9); private static final Comparator<Integer> SOME_COMPARATOR = Collections.reverseOrder(); private enum SomeEnum { A, B, C, D } public void testImmutableEnumSet() { Set<SomeEnum> units = Sets.immutableEnumSet(SomeEnum.D, SomeEnum.B); ASSERT.that(units).has().exactly(SomeEnum.B, SomeEnum.D).inOrder(); try { units.remove(SomeEnum.B); fail("ImmutableEnumSet should throw an exception on remove()"); } catch (UnsupportedOperationException expected) {} try { units.add(SomeEnum.C); fail("ImmutableEnumSet should throw an exception on add()"); } catch (UnsupportedOperationException expected) {} } public void testImmutableEnumSet_fromIterable() { ImmutableSet<SomeEnum> none = Sets.immutableEnumSet(MinimalIterable.<SomeEnum>of()); ASSERT.that(none).isEmpty(); ImmutableSet<SomeEnum> one = Sets.immutableEnumSet(MinimalIterable.of(SomeEnum.B)); ASSERT.that(one).has().item(SomeEnum.B); ImmutableSet<SomeEnum> two = Sets.immutableEnumSet(MinimalIterable.of(SomeEnum.D, SomeEnum.B)); ASSERT.that(two).has().exactly(SomeEnum.B, SomeEnum.D).inOrder(); } private static byte[] prepended(byte b, byte[] array) { byte[] out = new byte[array.length + 1]; out[0] = b; System.arraycopy(array, 0, out, 1, array.length); return out; } public void testNewEnumSet_empty() { EnumSet<SomeEnum> copy = newEnumSet(Collections.<SomeEnum>emptySet(), SomeEnum.class); assertEquals(EnumSet.noneOf(SomeEnum.class), copy); } public void testNewEnumSet_enumSet() { EnumSet<SomeEnum> set = EnumSet.of(SomeEnum.A, SomeEnum.D); assertEquals(set, newEnumSet(set, SomeEnum.class)); } public void testNewEnumSet_collection() { Set<SomeEnum> set = ImmutableSet.of(SomeEnum.B, SomeEnum.C); assertEquals(set, newEnumSet(set, SomeEnum.class)); } public void testNewEnumSet_iterable() { Set<SomeEnum> set = ImmutableSet.of(SomeEnum.A, SomeEnum.B, SomeEnum.C); assertEquals(set, newEnumSet(unmodifiableIterable(set), SomeEnum.class)); } public void testNewHashSetEmpty() { HashSet<Integer> set = Sets.newHashSet(); verifySetContents(set, EMPTY_COLLECTION); } public void testNewHashSetVarArgs() { HashSet<Integer> set = Sets.newHashSet(0, 1, 1); verifySetContents(set, Arrays.asList(0, 1)); } public void testNewHashSetFromCollection() { HashSet<Integer> set = Sets.newHashSet(SOME_COLLECTION); verifySetContents(set, SOME_COLLECTION); } public void testNewHashSetFromIterable() { HashSet<Integer> set = Sets.newHashSet(SOME_ITERABLE); verifySetContents(set, SOME_ITERABLE); } public void testNewHashSetWithExpectedSizeSmall() { HashSet<Integer> set = Sets.newHashSetWithExpectedSize(0); verifySetContents(set, EMPTY_COLLECTION); } public void testNewHashSetWithExpectedSizeLarge() { HashSet<Integer> set = Sets.newHashSetWithExpectedSize(1000); verifySetContents(set, EMPTY_COLLECTION); } public void testNewHashSetFromIterator() { HashSet<Integer> set = Sets.newHashSet(SOME_COLLECTION.iterator()); verifySetContents(set, SOME_COLLECTION); } public void testNewConcurrentHashSetEmpty() { Set<Integer> set = Sets.newConcurrentHashSet(); verifySetContents(set, EMPTY_COLLECTION); } public void testNewConcurrentHashSetFromCollection() { Set<Integer> set = Sets.newConcurrentHashSet(SOME_COLLECTION); verifySetContents(set, SOME_COLLECTION); } public void testNewLinkedHashSetEmpty() { LinkedHashSet<Integer> set = Sets.newLinkedHashSet(); verifyLinkedHashSetContents(set, EMPTY_COLLECTION); } public void testNewLinkedHashSetFromCollection() { LinkedHashSet<Integer> set = Sets.newLinkedHashSet(LONGER_LIST); verifyLinkedHashSetContents(set, LONGER_LIST); } public void testNewLinkedHashSetFromIterable() { LinkedHashSet<Integer> set = Sets.newLinkedHashSet(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return LONGER_LIST.iterator(); } }); verifyLinkedHashSetContents(set, LONGER_LIST); } public void testNewLinkedHashSetWithExpectedSizeSmall() { LinkedHashSet<Integer> set = Sets.newLinkedHashSetWithExpectedSize(0); verifySetContents(set, EMPTY_COLLECTION); } public void testNewLinkedHashSetWithExpectedSizeLarge() { LinkedHashSet<Integer> set = Sets.newLinkedHashSetWithExpectedSize(1000); verifySetContents(set, EMPTY_COLLECTION); } public void testNewTreeSetEmpty() { TreeSet<Integer> set = Sets.newTreeSet(); verifySortedSetContents(set, EMPTY_COLLECTION, null); } public void testNewTreeSetEmptyDerived() { TreeSet<Derived> set = Sets.newTreeSet(); assertTrue(set.isEmpty()); set.add(new Derived("foo")); set.add(new Derived("bar")); ASSERT.that(set).has().exactly(new Derived("bar"), new Derived("foo")).inOrder(); } public void testNewTreeSetEmptyNonGeneric() { TreeSet<LegacyComparable> set = Sets.newTreeSet(); assertTrue(set.isEmpty()); set.add(new LegacyComparable("foo")); set.add(new LegacyComparable("bar")); ASSERT.that(set).has() .exactly(new LegacyComparable("bar"), new LegacyComparable("foo")).inOrder(); } public void testNewTreeSetFromCollection() { TreeSet<Integer> set = Sets.newTreeSet(SOME_COLLECTION); verifySortedSetContents(set, SOME_COLLECTION, null); } public void testNewTreeSetFromIterable() { TreeSet<Integer> set = Sets.newTreeSet(SOME_ITERABLE); verifySortedSetContents(set, SOME_ITERABLE, null); } public void testNewTreeSetFromIterableDerived() { Iterable<Derived> iterable = Arrays.asList(new Derived("foo"), new Derived("bar")); TreeSet<Derived> set = Sets.newTreeSet(iterable); ASSERT.that(set).has().exactly( new Derived("bar"), new Derived("foo")).inOrder(); } public void testNewTreeSetFromIterableNonGeneric() { Iterable<LegacyComparable> iterable = Arrays.asList(new LegacyComparable("foo"), new LegacyComparable("bar")); TreeSet<LegacyComparable> set = Sets.newTreeSet(iterable); ASSERT.that(set).has().exactly( new LegacyComparable("bar"), new LegacyComparable("foo")).inOrder(); } public void testNewTreeSetEmptyWithComparator() { TreeSet<Integer> set = Sets.newTreeSet(SOME_COMPARATOR); verifySortedSetContents(set, EMPTY_COLLECTION, SOME_COMPARATOR); } public void testNewIdentityHashSet() { Set<Integer> set = Sets.newIdentityHashSet(); Integer value1 = new Integer(12357); Integer value2 = new Integer(12357); assertTrue(set.add(value1)); assertFalse(set.contains(value2)); assertTrue(set.contains(value1)); assertTrue(set.add(value2)); assertEquals(2, set.size()); } public void testComplementOfEnumSet() { Set<SomeEnum> units = EnumSet.of(SomeEnum.B, SomeEnum.D); EnumSet<SomeEnum> otherUnits = Sets.complementOf(units); verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C)); } public void testComplementOfEnumSetWithType() { Set<SomeEnum> units = EnumSet.of(SomeEnum.B, SomeEnum.D); EnumSet<SomeEnum> otherUnits = Sets.complementOf(units, SomeEnum.class); verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C)); } public void testComplementOfRegularSet() { Set<SomeEnum> units = Sets.newHashSet(SomeEnum.B, SomeEnum.D); EnumSet<SomeEnum> otherUnits = Sets.complementOf(units); verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C)); } public void testComplementOfRegularSetWithType() { Set<SomeEnum> units = Sets.newHashSet(SomeEnum.B, SomeEnum.D); EnumSet<SomeEnum> otherUnits = Sets.complementOf(units, SomeEnum.class); verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C)); } public void testComplementOfEmptySet() { Set<SomeEnum> noUnits = Collections.emptySet(); EnumSet<SomeEnum> allUnits = Sets.complementOf(noUnits, SomeEnum.class); verifySetContents(EnumSet.allOf(SomeEnum.class), allUnits); } public void testComplementOfFullSet() { Set<SomeEnum> allUnits = Sets.newHashSet(SomeEnum.values()); EnumSet<SomeEnum> noUnits = Sets.complementOf(allUnits, SomeEnum.class); verifySetContents(noUnits, EnumSet.noneOf(SomeEnum.class)); } public void testComplementOfEmptyEnumSetWithoutType() { Set<SomeEnum> noUnits = EnumSet.noneOf(SomeEnum.class); EnumSet<SomeEnum> allUnits = Sets.complementOf(noUnits); verifySetContents(allUnits, EnumSet.allOf(SomeEnum.class)); } public void testComplementOfEmptySetWithoutTypeDoesntWork() { Set<SomeEnum> set = Collections.emptySet(); try { Sets.complementOf(set); fail(); } catch (IllegalArgumentException expected) {} } public void testNewSetFromMap() { Set<Integer> set = Sets.newSetFromMap(new HashMap<Integer, Boolean>()); set.addAll(SOME_COLLECTION); verifySetContents(set, SOME_COLLECTION); } public void testNewSetFromMapIllegal() { Map<Integer, Boolean> map = new LinkedHashMap<Integer, Boolean>(); map.put(2, true); try { Sets.newSetFromMap(map); fail(); } catch (IllegalArgumentException expected) {} } // TODO: the overwhelming number of suppressions below suggests that maybe // it's not worth having a varargs form of this method at all... /** * The 0-ary cartesian product is a single empty list. */ @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_zeroary() { ASSERT.that(Sets.cartesianProduct()).has().exactly(list()); } /** * A unary cartesian product is one list of size 1 for each element in the * input set. */ @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_unary() { ASSERT.that(Sets.cartesianProduct(set(1, 2))).has().exactly(list(1), list(2)); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary0x0() { Set<Integer> mt = emptySet(); assertEmpty(Sets.cartesianProduct(mt, mt)); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary0x1() { Set<Integer> mt = emptySet(); assertEmpty(Sets.cartesianProduct(mt, set(1))); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x0() { Set<Integer> mt = emptySet(); assertEmpty(Sets.cartesianProduct(set(1), mt)); } private static void assertEmpty(Set<? extends List<?>> set) { assertTrue(set.isEmpty()); assertEquals(0, set.size()); assertFalse(set.iterator().hasNext()); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x1() { ASSERT.that(Sets.cartesianProduct(set(1), set(2))).has().item(list(1, 2)); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x2() { ASSERT.that(Sets.cartesianProduct(set(1), set(2, 3))) .has().exactly(list(1, 2), list(1, 3)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary2x2() { ASSERT.that(Sets.cartesianProduct(set(1, 2), set(3, 4))) .has().exactly(list(1, 3), list(1, 4), list(2, 3), list(2, 4)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_2x2x2() { ASSERT.that(Sets.cartesianProduct(set(0, 1), set(0, 1), set(0, 1))).has().exactly( list(0, 0, 0), list(0, 0, 1), list(0, 1, 0), list(0, 1, 1), list(1, 0, 0), list(1, 0, 1), list(1, 1, 0), list(1, 1, 1)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_contains() { Set<List<Integer>> actual = Sets.cartesianProduct(set(1, 2), set(3, 4)); assertTrue(actual.contains(list(1, 3))); assertTrue(actual.contains(list(1, 4))); assertTrue(actual.contains(list(2, 3))); assertTrue(actual.contains(list(2, 4))); assertFalse(actual.contains(list(3, 1))); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_unrelatedTypes() { Set<Integer> x = set(1, 2); Set<String> y = set("3", "4"); List<Object> exp1 = list((Object) 1, "3"); List<Object> exp2 = list((Object) 1, "4"); List<Object> exp3 = list((Object) 2, "3"); List<Object> exp4 = list((Object) 2, "4"); ASSERT.that(Sets.<Object>cartesianProduct(x, y)) .has().exactly(exp1, exp2, exp3, exp4).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProductTooBig() { Set<Integer> set = ContiguousSet.create(Range.closed(0, 10000), DiscreteDomain.integers()); try { Sets.cartesianProduct(set, set, set, set, set); fail("Expected IAE"); } catch (IllegalArgumentException expected) {} } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_hashCode() { // Run through the same cartesian products we tested above Set<List<Integer>> degenerate = Sets.cartesianProduct(); checkHashCode(degenerate); checkHashCode(Sets.cartesianProduct(set(1, 2))); int num = Integer.MAX_VALUE / 3 * 2; // tickle overflow-related problems checkHashCode(Sets.cartesianProduct(set(1, 2, num))); Set<Integer> mt = emptySet(); checkHashCode(Sets.cartesianProduct(mt, mt)); checkHashCode(Sets.cartesianProduct(mt, set(num))); checkHashCode(Sets.cartesianProduct(set(num), mt)); checkHashCode(Sets.cartesianProduct(set(num), set(1))); checkHashCode(Sets.cartesianProduct(set(1), set(2, num))); checkHashCode(Sets.cartesianProduct(set(1, num), set(2, num - 1))); checkHashCode(Sets.cartesianProduct( set(1, num), set(2, num - 1), set(3, num + 1))); // a bigger one checkHashCode(Sets.cartesianProduct( set(1, num, num + 1), set(2), set(3, num + 2), set(4, 5, 6, 7, 8))); } public void testPowerSetEmpty() { ImmutableSet<Integer> elements = ImmutableSet.of(); Set<Set<Integer>> powerSet = powerSet(elements); assertEquals(1, powerSet.size()); assertEquals(ImmutableSet.of(ImmutableSet.of()), powerSet); assertEquals(0, powerSet.hashCode()); } public void testPowerSetContents() { ImmutableSet<Integer> elements = ImmutableSet.of(1, 2, 3); Set<Set<Integer>> powerSet = powerSet(elements); assertEquals(8, powerSet.size()); assertEquals(4 * 1 + 4 * 2 + 4 * 3, powerSet.hashCode()); Set<Set<Integer>> expected = newHashSet(); expected.add(ImmutableSet.<Integer>of()); expected.add(ImmutableSet.of(1)); expected.add(ImmutableSet.of(2)); expected.add(ImmutableSet.of(3)); expected.add(ImmutableSet.of(1, 2)); expected.add(ImmutableSet.of(1, 3)); expected.add(ImmutableSet.of(2, 3)); expected.add(ImmutableSet.of(1, 2, 3)); Set<Set<Integer>> almostPowerSet = newHashSet(expected); almostPowerSet.remove(ImmutableSet.of(1, 2, 3)); almostPowerSet.add(ImmutableSet.of(1, 2, 4)); new EqualsTester() .addEqualityGroup(expected, powerSet) .addEqualityGroup(ImmutableSet.of(1, 2, 3)) .addEqualityGroup(almostPowerSet) .testEquals(); for (Set<Integer> subset : expected) { assertTrue(powerSet.contains(subset)); } assertFalse(powerSet.contains(ImmutableSet.of(1, 2, 4))); assertFalse(powerSet.contains(singleton(null))); assertFalse(powerSet.contains(null)); assertFalse(powerSet.contains("notASet")); } public void testPowerSetIteration_manual() { ImmutableSet<Integer> elements = ImmutableSet.of(1, 2, 3); Set<Set<Integer>> powerSet = powerSet(elements); // The API doesn't promise this iteration order, but it's convenient here. Iterator<Set<Integer>> i = powerSet.iterator(); assertEquals(ImmutableSet.of(), i.next()); assertEquals(ImmutableSet.of(1), i.next()); assertEquals(ImmutableSet.of(2), i.next()); assertEquals(ImmutableSet.of(2, 1), i.next()); assertEquals(ImmutableSet.of(3), i.next()); assertEquals(ImmutableSet.of(3, 1), i.next()); assertEquals(ImmutableSet.of(3, 2), i.next()); assertEquals(ImmutableSet.of(3, 2, 1), i.next()); assertFalse(i.hasNext()); try { i.next(); fail(); } catch (NoSuchElementException expected) { } } public void testPowerSetIteration_iteratorTester_fast() { ImmutableSet<Integer> elements = ImmutableSet.of(1, 2); Set<Set<Integer>> expected = newLinkedHashSet(); expected.add(ImmutableSet.<Integer>of()); expected.add(ImmutableSet.of(1)); expected.add(ImmutableSet.of(2)); expected.add(ImmutableSet.of(1, 2)); final Set<Set<Integer>> powerSet = powerSet(elements); new IteratorTester<Set<Integer>>(4, UNMODIFIABLE, expected, KNOWN_ORDER) { @Override protected Iterator<Set<Integer>> newTargetIterator() { return powerSet.iterator(); } }.test(); } public void testPowerSetSize() { assertPowerSetSize(1); assertPowerSetSize(2, 'a'); assertPowerSetSize(4, 'a', 'b'); assertPowerSetSize(8, 'a', 'b', 'c'); assertPowerSetSize(16, 'a', 'b', 'd', 'e'); assertPowerSetSize(1 << 30, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4'); } public void testPowerSetCreationErrors() { try { powerSet(newHashSet('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5')); fail(); } catch (IllegalArgumentException expected) { } try { powerSet(singleton(null)); fail(); } catch (NullPointerException expected) { } } public void testPowerSetEqualsAndHashCode_verifyAgainstHashSet() { ImmutableList<Integer> allElements = ImmutableList.of(4233352, 3284593, 3794208, 3849533, 4013967, 2902658, 1886275, 2131109, 985872, 1843868); for (int i = 0; i < allElements.size(); i++) { Set<Integer> elements = newHashSet(allElements.subList(0, i)); Set<Set<Integer>> powerSet1 = powerSet(elements); Set<Set<Integer>> powerSet2 = powerSet(elements); new EqualsTester() .addEqualityGroup(powerSet1, powerSet2, toHashSets(powerSet1)) .addEqualityGroup(ImmutableSet.of()) .addEqualityGroup(ImmutableSet.of(9999999)) .addEqualityGroup("notASet") .testEquals(); assertEquals(toHashSets(powerSet1).hashCode(), powerSet1.hashCode()); } } /** * Test that a hash code miscomputed by "input.hashCode() * tooFarValue / 2" * is correct under our {@code hashCode} implementation. */ public void testPowerSetHashCode_inputHashCodeTimesTooFarValueIsZero() { Set<Object> sumToEighthMaxIntElements = newHashSet(objectWithHashCode(1 << 29), objectWithHashCode(0)); assertPowerSetHashCode(1 << 30, sumToEighthMaxIntElements); Set<Object> sumToQuarterMaxIntElements = newHashSet(objectWithHashCode(1 << 30), objectWithHashCode(0)); assertPowerSetHashCode(1 << 31, sumToQuarterMaxIntElements); } public void testPowerSetShowOff() { Set<Object> zero = ImmutableSet.of(); Set<Set<Object>> one = powerSet(zero); Set<Set<Set<Object>>> two = powerSet(one); Set<Set<Set<Set<Object>>>> four = powerSet(two); Set<Set<Set<Set<Set<Object>>>>> sixteen = powerSet(four); Set<Set<Set<Set<Set<Set<Object>>>>>> sixtyFiveThousandish = powerSet(sixteen); assertEquals(1 << 16, sixtyFiveThousandish.size()); assertTrue(powerSet(makeSetOfZeroToTwentyNine()) .contains(makeSetOfZeroToTwentyNine())); assertFalse(powerSet(makeSetOfZeroToTwentyNine()) .contains(ImmutableSet.of(30))); } private static Set<Integer> makeSetOfZeroToTwentyNine() { // TODO: use Range once it's publicly available Set<Integer> zeroToTwentyNine = newHashSet(); for (int i = 0; i < 30; i++) { zeroToTwentyNine.add(i); } return zeroToTwentyNine; } private static <E> Set<Set<E>> toHashSets(Set<Set<E>> powerSet) { Set<Set<E>> result = newHashSet(); for (Set<E> subset : powerSet) { result.add(new HashSet<E>(subset)); } return result; } private static Object objectWithHashCode(final int hashCode) { return new Object() { @Override public int hashCode() { return hashCode; } }; } private static void assertPowerSetHashCode(int expected, Set<?> elements) { assertEquals(expected, powerSet(elements).hashCode()); } private static void assertPowerSetSize(int i, Object... elements) { assertEquals(i, powerSet(newHashSet(elements)).size()); } private static void checkHashCode(Set<?> set) { assertEquals(Sets.newHashSet(set).hashCode(), set.hashCode()); } private static <E> Set<E> set(E... elements) { return ImmutableSet.copyOf(elements); } private static <E> List<E> list(E... elements) { return ImmutableList.copyOf(elements); } /** * Utility method to verify that the given LinkedHashSet is equal to and * hashes identically to a set constructed with the elements in the given * collection. Also verifies that the ordering in the set is the same * as the ordering of the given contents. */ private static <E> void verifyLinkedHashSetContents( LinkedHashSet<E> set, Collection<E> contents) { assertEquals("LinkedHashSet should have preserved order for iteration", new ArrayList<E>(set), new ArrayList<E>(contents)); verifySetContents(set, contents); } /** * Utility method to verify that the given SortedSet is equal to and * hashes identically to a set constructed with the elements in the * given iterable. Also verifies that the comparator is the same as the * given comparator. */ private static <E> void verifySortedSetContents( SortedSet<E> set, Iterable<E> iterable, @Nullable Comparator<E> comparator) { assertSame(comparator, set.comparator()); verifySetContents(set, iterable); } /** * Utility method that verifies that the given set is equal to and hashes * identically to a set constructed with the elements in the given iterable. */ private static <E> void verifySetContents(Set<E> set, Iterable<E> contents) { Set<E> expected = null; if (contents instanceof Set) { expected = (Set<E>) contents; } else { expected = new HashSet<E>(); for (E element : contents) { expected.add(element); } } assertEquals(expected, set); } /** * Simple base class to verify that we handle generics correctly. */ static class Base implements Comparable<Base>, Serializable { private final String s; public Base(String s) { this.s = s; } @Override public int hashCode() { // delegate to 's' return s.hashCode(); } @Override public boolean equals(Object other) { if (other == null) { return false; } else if (other instanceof Base) { return s.equals(((Base) other).s); } else { return false; } } @Override public int compareTo(Base o) { return s.compareTo(o.s); } private static final long serialVersionUID = 0; } /** * Simple derived class to verify that we handle generics correctly. */ static class Derived extends Base { public Derived(String s) { super(s); } private static final long serialVersionUID = 0; } void ensureNotDirectlyModifiable(SortedSet<Integer> unmod) { try { unmod.add(4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { unmod.remove(4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { unmod.addAll(Collections.singleton(4)); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { Iterator<Integer> iterator = unmod.iterator(); iterator.next(); iterator.remove(); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/SetsTest.java
Java
asf20
27,043
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.io.Serializable; import java.util.Iterator; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; /** * Unit test for {@link AbstractMultiset}. * * @author Kevin Bourrillion * @author Louis Wasserman */ @SuppressWarnings("serial") // No serialization is used in this test @GwtCompatible(emulated = true) public class SimpleAbstractMultisetTest extends TestCase { public void testFastAddAllMultiset() { final AtomicInteger addCalls = new AtomicInteger(); Multiset<String> multiset = new NoRemoveMultiset<String>() { @Override public int add(String element, int occurrences) { addCalls.incrementAndGet(); return super.add(element, occurrences); } }; ImmutableMultiset<String> adds = new ImmutableMultiset.Builder<String>().addCopies("x", 10).build(); multiset.addAll(adds); assertEquals(addCalls.get(), 1); } public void testRemoveUnsupported() { Multiset<String> multiset = new NoRemoveMultiset<String>(); multiset.add("a"); try { multiset.remove("a"); fail(); } catch (UnsupportedOperationException expected) {} assertTrue(multiset.contains("a")); } private static class NoRemoveMultiset<E> extends AbstractMultiset<E> implements Serializable { final Map<E, Integer> backingMap = Maps.newHashMap(); @Override public int add(@Nullable E element, int occurrences) { checkArgument(occurrences >= 0); Integer frequency = backingMap.get(element); if (frequency == null) { frequency = 0; } if (occurrences == 0) { return frequency; } checkArgument(occurrences <= Integer.MAX_VALUE - frequency); backingMap.put(element, frequency + occurrences); return frequency; } @Override Iterator<Entry<E>> entryIterator() { final Iterator<Map.Entry<E, Integer>> backingEntries = backingMap.entrySet().iterator(); return new UnmodifiableIterator<Multiset.Entry<E>>() { @Override public boolean hasNext() { return backingEntries.hasNext(); } @Override public Multiset.Entry<E> next() { final Map.Entry<E, Integer> mapEntry = backingEntries.next(); return new Multisets.AbstractEntry<E>() { @Override public E getElement() { return mapEntry.getKey(); } @Override public int getCount() { Integer frequency = backingMap.get(getElement()); return (frequency == null) ? 0 : frequency; } }; } }; } @Override int distinctElements() { return backingMap.size(); } } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/SimpleAbstractMultisetTest.java
Java
asf20
3,553
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.Iterables.skip; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.testing.IteratorTester; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * Unit test for {@code Iterables}. * * @author Kevin Bourrillion * @author Jared Levy */ @GwtCompatible(emulated = true) public class IterablesTest extends TestCase { public void testSize0() { Iterable<String> iterable = Collections.emptySet(); assertEquals(0, Iterables.size(iterable)); } public void testSize1Collection() { Iterable<String> iterable = Collections.singleton("a"); assertEquals(1, Iterables.size(iterable)); } public void testSize2NonCollection() { Iterable<Integer> iterable = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return asList(0, 1).iterator(); } }; assertEquals(2, Iterables.size(iterable)); } @SuppressWarnings("serial") public void testSize_collection_doesntIterate() { List<Integer> nums = asList(1, 2, 3, 4, 5); List<Integer> collection = new ArrayList<Integer>(nums) { @Override public Iterator<Integer> iterator() { throw new AssertionFailedError("Don't iterate me!"); } }; assertEquals(5, Iterables.size(collection)); } private static Iterable<String> iterable(String... elements) { final List<String> list = asList(elements); return new Iterable<String>() { @Override public Iterator<String> iterator() { return list.iterator(); } }; } public void test_contains_null_set_yes() { Iterable<String> set = Sets.newHashSet("a", null, "b"); assertTrue(Iterables.contains(set, null)); } public void test_contains_null_set_no() { Iterable<String> set = Sets.newHashSet("a", "b"); assertFalse(Iterables.contains(set, null)); } public void test_contains_null_iterable_yes() { Iterable<String> set = iterable("a", null, "b"); assertTrue(Iterables.contains(set, null)); } public void test_contains_null_iterable_no() { Iterable<String> set = iterable("a", "b"); assertFalse(Iterables.contains(set, null)); } public void test_contains_nonnull_set_yes() { Iterable<String> set = Sets.newHashSet("a", null, "b"); assertTrue(Iterables.contains(set, "b")); } public void test_contains_nonnull_set_no() { Iterable<String> set = Sets.newHashSet("a", "b"); assertFalse(Iterables.contains(set, "c")); } public void test_contains_nonnull_iterable_yes() { Iterable<String> set = iterable("a", null, "b"); assertTrue(Iterables.contains(set, "b")); } public void test_contains_nonnull_iterable_no() { Iterable<String> set = iterable("a", "b"); assertFalse(Iterables.contains(set, "c")); } public void testGetOnlyElement_noDefault_valid() { Iterable<String> iterable = Collections.singletonList("foo"); assertEquals("foo", Iterables.getOnlyElement(iterable)); } public void testGetOnlyElement_noDefault_empty() { Iterable<String> iterable = Collections.emptyList(); try { Iterables.getOnlyElement(iterable); fail(); } catch (NoSuchElementException expected) { } } public void testGetOnlyElement_noDefault_multiple() { Iterable<String> iterable = asList("foo", "bar"); try { Iterables.getOnlyElement(iterable); fail(); } catch (IllegalArgumentException expected) { } } public void testGetOnlyElement_withDefault_singleton() { Iterable<String> iterable = Collections.singletonList("foo"); assertEquals("foo", Iterables.getOnlyElement(iterable, "bar")); } public void testGetOnlyElement_withDefault_empty() { Iterable<String> iterable = Collections.emptyList(); assertEquals("bar", Iterables.getOnlyElement(iterable, "bar")); } public void testGetOnlyElement_withDefault_empty_null() { Iterable<String> iterable = Collections.emptyList(); assertNull(Iterables.getOnlyElement(iterable, null)); } public void testGetOnlyElement_withDefault_multiple() { Iterable<String> iterable = asList("foo", "bar"); try { Iterables.getOnlyElement(iterable, "x"); fail(); } catch (IllegalArgumentException expected) { } } public void testAny() { List<String> list = newArrayList(); Predicate<String> predicate = Predicates.equalTo("pants"); assertFalse(Iterables.any(list, predicate)); list.add("cool"); assertFalse(Iterables.any(list, predicate)); list.add("pants"); assertTrue(Iterables.any(list, predicate)); } public void testAll() { List<String> list = newArrayList(); Predicate<String> predicate = Predicates.equalTo("cool"); assertTrue(Iterables.all(list, predicate)); list.add("cool"); assertTrue(Iterables.all(list, predicate)); list.add("pants"); assertFalse(Iterables.all(list, predicate)); } public void testFind() { Iterable<String> list = newArrayList("cool", "pants"); assertEquals("cool", Iterables.find(list, Predicates.equalTo("cool"))); assertEquals("pants", Iterables.find(list, Predicates.equalTo("pants"))); try { Iterables.find(list, Predicates.alwaysFalse()); fail(); } catch (NoSuchElementException e) { } assertEquals("cool", Iterables.find(list, Predicates.alwaysTrue())); assertCanIterateAgain(list); } public void testFind_withDefault() { Iterable<String> list = Lists.newArrayList("cool", "pants"); assertEquals("cool", Iterables.find(list, Predicates.equalTo("cool"), "woot")); assertEquals("pants", Iterables.find(list, Predicates.equalTo("pants"), "woot")); assertEquals("woot", Iterables.find(list, Predicates.alwaysFalse(), "woot")); assertNull(Iterables.find(list, Predicates.alwaysFalse(), null)); assertEquals("cool", Iterables.find(list, Predicates.alwaysTrue(), "woot")); assertCanIterateAgain(list); } public void testTryFind() { Iterable<String> list = newArrayList("cool", "pants"); assertEquals(Optional.of("cool"), Iterables.tryFind(list, Predicates.equalTo("cool"))); assertEquals(Optional.of("pants"), Iterables.tryFind(list, Predicates.equalTo("pants"))); assertEquals(Optional.of("cool"), Iterables.tryFind(list, Predicates.alwaysTrue())); assertEquals(Optional.absent(), Iterables.tryFind(list, Predicates.alwaysFalse())); assertCanIterateAgain(list); } private static class TypeA {} private interface TypeB {} private static class HasBoth extends TypeA implements TypeB {} public void testTransform() { List<String> input = asList("1", "2", "3"); Iterable<Integer> result = Iterables.transform(input, new Function<String, Integer>() { @Override public Integer apply(String from) { return Integer.valueOf(from); } }); List<Integer> actual = newArrayList(result); List<Integer> expected = asList(1, 2, 3); assertEquals(expected, actual); assertCanIterateAgain(result); assertEquals("[1, 2, 3]", result.toString()); } public void testPoorlyBehavedTransform() { List<String> input = asList("1", null, "3"); Iterable<Integer> result = Iterables.transform(input, new Function<String, Integer>() { @Override public Integer apply(String from) { return Integer.valueOf(from); } }); Iterator<Integer> resultIterator = result.iterator(); resultIterator.next(); try { resultIterator.next(); fail("Expected NFE"); } catch (NumberFormatException nfe) { // Expected to fail. } } public void testNullFriendlyTransform() { List<Integer> input = asList(1, 2, null, 3); Iterable<String> result = Iterables.transform(input, new Function<Integer, String>() { @Override public String apply(Integer from) { return String.valueOf(from); } }); List<String> actual = newArrayList(result); List<String> expected = asList("1", "2", "null", "3"); assertEquals(expected, actual); } // Far less exhaustive than the tests in IteratorsTest public void testCycle() { Iterable<String> cycle = Iterables.cycle("a", "b"); int howManyChecked = 0; for (String string : cycle) { String expected = (howManyChecked % 2 == 0) ? "a" : "b"; assertEquals(expected, string); if (howManyChecked++ == 5) { break; } } // We left the last iterator pointing to "b". But a new iterator should // always point to "a". for (String string : cycle) { assertEquals("a", string); break; } assertEquals("[a, b] (cycled)", cycle.toString()); } // Again, the exhaustive tests are in IteratorsTest public void testConcatIterable() { List<Integer> list1 = newArrayList(1); List<Integer> list2 = newArrayList(4); @SuppressWarnings("unchecked") List<List<Integer>> input = newArrayList(list1, list2); Iterable<Integer> result = Iterables.concat(input); assertEquals(asList(1, 4), newArrayList(result)); // Now change the inputs and see result dynamically change as well list1.add(2); List<Integer> list3 = newArrayList(3); input.add(1, list3); assertEquals(asList(1, 2, 3, 4), newArrayList(result)); assertEquals("[1, 2, 3, 4]", result.toString()); } public void testConcatVarargs() { List<Integer> list1 = newArrayList(1); List<Integer> list2 = newArrayList(4); List<Integer> list3 = newArrayList(7, 8); List<Integer> list4 = newArrayList(9); List<Integer> list5 = newArrayList(10); @SuppressWarnings("unchecked") Iterable<Integer> result = Iterables.concat(list1, list2, list3, list4, list5); assertEquals(asList(1, 4, 7, 8, 9, 10), newArrayList(result)); assertEquals("[1, 4, 7, 8, 9, 10]", result.toString()); } public void testConcatNullPointerException() { List<Integer> list1 = newArrayList(1); List<Integer> list2 = newArrayList(4); try { Iterables.concat(list1, null, list2); fail(); } catch (NullPointerException expected) {} } public void testConcatPeformingFiniteCycle() { Iterable<Integer> iterable = asList(1, 2, 3); int n = 4; Iterable<Integer> repeated = Iterables.concat(Collections.nCopies(n, iterable)); ASSERT.that(repeated).iteratesOverSequence( 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3); } public void testPartition_badSize() { Iterable<Integer> source = Collections.singleton(1); try { Iterables.partition(source, 0); fail(); } catch (IllegalArgumentException expected) { } } public void testPartition_empty() { Iterable<Integer> source = Collections.emptySet(); Iterable<List<Integer>> partitions = Iterables.partition(source, 1); assertTrue(Iterables.isEmpty(partitions)); } public void testPartition_singleton1() { Iterable<Integer> source = Collections.singleton(1); Iterable<List<Integer>> partitions = Iterables.partition(source, 1); assertEquals(1, Iterables.size(partitions)); assertEquals(Collections.singletonList(1), partitions.iterator().next()); } public void testPartition_view() { List<Integer> list = asList(1, 2); Iterable<List<Integer>> partitions = Iterables.partition(list, 2); // Changes before the partition is retrieved are reflected list.set(0, 3); Iterator<List<Integer>> iterator = partitions.iterator(); // Changes before the partition is retrieved are reflected list.set(1, 4); List<Integer> first = iterator.next(); // Changes after are not list.set(0, 5); assertEquals(ImmutableList.of(3, 4), first); } public void testPaddedPartition_basic() { List<Integer> list = asList(1, 2, 3, 4, 5); Iterable<List<Integer>> partitions = Iterables.paddedPartition(list, 2); assertEquals(3, Iterables.size(partitions)); assertEquals(asList(5, null), Iterables.getLast(partitions)); } public void testPaddedPartitionRandomAccessInput() { Iterable<Integer> source = asList(1, 2, 3); Iterable<List<Integer>> partitions = Iterables.paddedPartition(source, 2); Iterator<List<Integer>> iterator = partitions.iterator(); assertTrue(iterator.next() instanceof RandomAccess); assertTrue(iterator.next() instanceof RandomAccess); } public void testPaddedPartitionNonRandomAccessInput() { Iterable<Integer> source = Lists.newLinkedList(asList(1, 2, 3)); Iterable<List<Integer>> partitions = Iterables.paddedPartition(source, 2); Iterator<List<Integer>> iterator = partitions.iterator(); // Even though the input list doesn't implement RandomAccess, the output // lists do. assertTrue(iterator.next() instanceof RandomAccess); assertTrue(iterator.next() instanceof RandomAccess); } // More tests in IteratorsTest public void testAddAllToList() { List<String> alreadyThere = newArrayList("already", "there"); List<String> freshlyAdded = newArrayList("freshly", "added"); boolean changed = Iterables.addAll(alreadyThere, freshlyAdded); ASSERT.that(alreadyThere).has().exactly( "already", "there", "freshly", "added").inOrder(); assertTrue(changed); } private static void assertCanIterateAgain(Iterable<?> iterable) { for (@SuppressWarnings("unused") Object obj : iterable) { } } // More exhaustive tests are in IteratorsTest. public void testElementsEqual() throws Exception { Iterable<?> a; Iterable<?> b; // A few elements. a = asList(4, 8, 15, 16, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertTrue(Iterables.elementsEqual(a, b)); // An element differs. a = asList(4, 8, 15, 12, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterables.elementsEqual(a, b)); // null versus non-null. a = asList(4, 8, 15, null, 23, 42); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterables.elementsEqual(a, b)); assertFalse(Iterables.elementsEqual(b, a)); // Different lengths. a = asList(4, 8, 15, 16, 23); b = asList(4, 8, 15, 16, 23, 42); assertFalse(Iterables.elementsEqual(a, b)); assertFalse(Iterables.elementsEqual(b, a)); } public void testToString() { List<String> list = Collections.emptyList(); assertEquals("[]", Iterables.toString(list)); list = newArrayList("yam", "bam", "jam", "ham"); assertEquals("[yam, bam, jam, ham]", Iterables.toString(list)); } public void testLimit() { Iterable<String> iterable = newArrayList("foo", "bar", "baz"); Iterable<String> limited = Iterables.limit(iterable, 2); List<String> expected = ImmutableList.of("foo", "bar"); List<String> actual = newArrayList(limited); assertEquals(expected, actual); assertCanIterateAgain(limited); assertEquals("[foo, bar]", limited.toString()); } public void testLimit_illegalArgument() { List<String> list = newArrayList("a", "b", "c"); try { Iterables.limit(list, -1); fail(); } catch (IllegalArgumentException expected) {} } public void testIsEmpty() { Iterable<String> emptyList = Collections.emptyList(); assertTrue(Iterables.isEmpty(emptyList)); Iterable<String> singletonList = Collections.singletonList("foo"); assertFalse(Iterables.isEmpty(singletonList)); } public void testSkip_simple() { Collection<String> set = ImmutableSet.of("a", "b", "c", "d", "e"); assertEquals(newArrayList("c", "d", "e"), newArrayList(skip(set, 2))); assertEquals("[c, d, e]", skip(set, 2).toString()); } public void testSkip_simpleList() { Collection<String> list = newArrayList("a", "b", "c", "d", "e"); assertEquals(newArrayList("c", "d", "e"), newArrayList(skip(list, 2))); assertEquals("[c, d, e]", skip(list, 2).toString()); } public void testSkip_pastEnd() { Collection<String> set = ImmutableSet.of("a", "b"); assertEquals(emptyList(), newArrayList(skip(set, 20))); } public void testSkip_pastEndList() { Collection<String> list = newArrayList("a", "b"); assertEquals(emptyList(), newArrayList(skip(list, 20))); } public void testSkip_skipNone() { Collection<String> set = ImmutableSet.of("a", "b"); assertEquals(newArrayList("a", "b"), newArrayList(skip(set, 0))); } public void testSkip_skipNoneList() { Collection<String> list = newArrayList("a", "b"); assertEquals(newArrayList("a", "b"), newArrayList(skip(list, 0))); } public void testSkip_removal() { Collection<String> set = Sets.newHashSet("a", "b"); Iterator<String> iterator = skip(set, 2).iterator(); try { iterator.next(); } catch (NoSuchElementException suppressed) { // We want remove() to fail even after a failed call to next(). } try { iterator.remove(); fail("Expected IllegalStateException"); } catch (IllegalStateException expected) {} } public void testSkip_allOfMutableList_modifiable() { List<String> list = newArrayList("a", "b"); Iterator<String> iterator = skip(list, 2).iterator(); try { iterator.remove(); fail("Expected IllegalStateException"); } catch (IllegalStateException expected) {} } public void testSkip_allOfImmutableList_modifiable() { List<String> list = ImmutableList.of("a", "b"); Iterator<String> iterator = skip(list, 2).iterator(); try { iterator.remove(); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException expected) {} } public void testSkip_nonStructurallyModifiedList() throws Exception { List<String> list = newArrayList("a", "b", "c"); Iterable<String> tail = skip(list, 1); Iterator<String> tailIterator = tail.iterator(); list.set(2, "C"); assertEquals("b", tailIterator.next()); assertEquals("C", tailIterator.next()); assertFalse(tailIterator.hasNext()); } public void testSkip_structurallyModifiedSkipSome() throws Exception { Collection<String> set = newLinkedHashSet(asList("a", "b", "c")); Iterable<String> tail = skip(set, 1); set.remove("b"); set.addAll(newArrayList("A", "B", "C")); ASSERT.that(tail).iteratesOverSequence("c", "A", "B", "C"); } public void testSkip_structurallyModifiedSkipSomeList() throws Exception { List<String> list = newArrayList("a", "b", "c"); Iterable<String> tail = skip(list, 1); list.subList(1, 3).clear(); list.addAll(0, newArrayList("A", "B", "C")); ASSERT.that(tail).iteratesOverSequence("B", "C", "a"); } public void testSkip_structurallyModifiedSkipAll() throws Exception { Collection<String> set = newLinkedHashSet(asList("a", "b", "c")); Iterable<String> tail = skip(set, 2); set.remove("a"); set.remove("b"); assertFalse(tail.iterator().hasNext()); } public void testSkip_structurallyModifiedSkipAllList() throws Exception { List<String> list = newArrayList("a", "b", "c"); Iterable<String> tail = skip(list, 2); list.subList(0, 2).clear(); assertTrue(Iterables.isEmpty(tail)); } public void testSkip_illegalArgument() { List<String> list = newArrayList("a", "b", "c"); try { skip(list, -1); fail(); } catch (IllegalArgumentException expected) {} } private void testGetOnAbc(Iterable<String> iterable) { try { Iterables.get(iterable, -1); fail(); } catch (IndexOutOfBoundsException expected) {} assertEquals("a", Iterables.get(iterable, 0)); assertEquals("b", Iterables.get(iterable, 1)); assertEquals("c", Iterables.get(iterable, 2)); try { Iterables.get(iterable, 3); fail(); } catch (IndexOutOfBoundsException nsee) {} try { Iterables.get(iterable, 4); fail(); } catch (IndexOutOfBoundsException nsee) {} } private void testGetOnEmpty(Iterable<String> iterable) { try { Iterables.get(iterable, 0); fail(); } catch (IndexOutOfBoundsException expected) {} } public void testGet_list() { testGetOnAbc(newArrayList("a", "b", "c")); } public void testGet_emptyList() { testGetOnEmpty(Collections.<String>emptyList()); } public void testGet_sortedSet() { testGetOnAbc(ImmutableSortedSet.of("b", "c", "a")); } public void testGet_emptySortedSet() { testGetOnEmpty(ImmutableSortedSet.<String>of()); } public void testGet_iterable() { testGetOnAbc(ImmutableSet.of("a", "b", "c")); } public void testGet_emptyIterable() { testGetOnEmpty(Sets.<String>newHashSet()); } public void testGet_withDefault_negativePosition() { try { Iterables.get(newArrayList("a", "b", "c"), -1, "d"); fail(); } catch (IndexOutOfBoundsException expected) { // pass } } public void testGet_withDefault_simple() { ArrayList<String> list = newArrayList("a", "b", "c"); assertEquals("b", Iterables.get(list, 1, "d")); } public void testGet_withDefault_iterable() { Set<String> set = ImmutableSet.of("a", "b", "c"); assertEquals("b", Iterables.get(set, 1, "d")); } public void testGet_withDefault_last() { ArrayList<String> list = newArrayList("a", "b", "c"); assertEquals("c", Iterables.get(list, 2, "d")); } public void testGet_withDefault_lastPlusOne() { ArrayList<String> list = newArrayList("a", "b", "c"); assertEquals("d", Iterables.get(list, 3, "d")); } public void testGet_withDefault_doesntIterate() { List<String> list = new DiesOnIteratorArrayList(); list.add("a"); assertEquals("a", Iterables.get(list, 0, "b")); } public void testGetFirst_withDefault_singleton() { Iterable<String> iterable = Collections.singletonList("foo"); assertEquals("foo", Iterables.getFirst(iterable, "bar")); } public void testGetFirst_withDefault_empty() { Iterable<String> iterable = Collections.emptyList(); assertEquals("bar", Iterables.getFirst(iterable, "bar")); } public void testGetFirst_withDefault_empty_null() { Iterable<String> iterable = Collections.emptyList(); assertNull(Iterables.getFirst(iterable, null)); } public void testGetFirst_withDefault_multiple() { Iterable<String> iterable = asList("foo", "bar"); assertEquals("foo", Iterables.getFirst(iterable, "qux")); } public void testGetLast_list() { List<String> list = newArrayList("a", "b", "c"); assertEquals("c", Iterables.getLast(list)); } public void testGetLast_emptyList() { List<String> list = Collections.emptyList(); try { Iterables.getLast(list); fail(); } catch (NoSuchElementException e) {} } public void testGetLast_sortedSet() { SortedSet<String> sortedSet = ImmutableSortedSet.of("b", "c", "a"); assertEquals("c", Iterables.getLast(sortedSet)); } public void testGetLast_withDefault_singleton() { Iterable<String> iterable = Collections.singletonList("foo"); assertEquals("foo", Iterables.getLast(iterable, "bar")); } public void testGetLast_withDefault_empty() { Iterable<String> iterable = Collections.emptyList(); assertEquals("bar", Iterables.getLast(iterable, "bar")); } public void testGetLast_withDefault_empty_null() { Iterable<String> iterable = Collections.emptyList(); assertNull(Iterables.getLast(iterable, null)); } public void testGetLast_withDefault_multiple() { Iterable<String> iterable = asList("foo", "bar"); assertEquals("bar", Iterables.getLast(iterable, "qux")); } /** * {@link ArrayList} extension that forbids the use of * {@link Collection#iterator} for tests that need to prove that it isn't * called. */ private static class DiesOnIteratorArrayList extends ArrayList<String> { /** * @throws UnsupportedOperationException all the time */ @Override public Iterator<String> iterator() { throw new UnsupportedOperationException(); } } public void testGetLast_withDefault_not_empty_list() { // TODO: verify that this is the best testing strategy. List<String> diesOnIteratorList = new DiesOnIteratorArrayList(); diesOnIteratorList.add("bar"); assertEquals("bar", Iterables.getLast(diesOnIteratorList, "qux")); } /** * {@link TreeSet} extension that forbids the use of * {@link Collection#iterator} for tests that need to prove that it isn't * called. */ private static final class DiesOnIteratorTreeSet extends TreeSet<String> { /** * @throws UnsupportedOperationException all the time */ @Override public Iterator<String> iterator() { throw new UnsupportedOperationException(); } } public void testGetLast_emptySortedSet() { SortedSet<String> sortedSet = ImmutableSortedSet.of(); try { Iterables.getLast(sortedSet); fail(); } catch (NoSuchElementException e) {} } public void testGetLast_iterable() { Set<String> set = ImmutableSet.of("a", "b", "c"); assertEquals("c", Iterables.getLast(set)); } public void testGetLast_emptyIterable() { Set<String> set = Sets.newHashSet(); try { Iterables.getLast(set); fail(); } catch (NoSuchElementException e) {} } public void testUnmodifiableIterable() { List<String> list = newArrayList("a", "b", "c"); Iterable<String> iterable = Iterables.unmodifiableIterable(list); Iterator<String> iterator = iterable.iterator(); iterator.next(); try { iterator.remove(); fail(); } catch (UnsupportedOperationException expected) {} assertEquals("[a, b, c]", iterable.toString()); } @SuppressWarnings("deprecation") // test of deprecated method public void testUnmodifiableIterableShortCircuit() { List<String> list = newArrayList("a", "b", "c"); Iterable<String> iterable = Iterables.unmodifiableIterable(list); Iterable<String> iterable2 = Iterables.unmodifiableIterable(iterable); assertSame(iterable, iterable2); ImmutableList<String> immutableList = ImmutableList.of("a", "b", "c"); assertSame(immutableList, Iterables.unmodifiableIterable(immutableList)); assertSame(immutableList, Iterables.unmodifiableIterable((List<String>) immutableList)); } public void testFrequency_multiset() { Multiset<String> multiset = ImmutableMultiset.of("a", "b", "a", "c", "b", "a"); assertEquals(3, Iterables.frequency(multiset, "a")); assertEquals(2, Iterables.frequency(multiset, "b")); assertEquals(1, Iterables.frequency(multiset, "c")); assertEquals(0, Iterables.frequency(multiset, "d")); assertEquals(0, Iterables.frequency(multiset, 4.2)); assertEquals(0, Iterables.frequency(multiset, null)); } public void testFrequency_set() { Set<String> set = Sets.newHashSet("a", "b", "c"); assertEquals(1, Iterables.frequency(set, "a")); assertEquals(1, Iterables.frequency(set, "b")); assertEquals(1, Iterables.frequency(set, "c")); assertEquals(0, Iterables.frequency(set, "d")); assertEquals(0, Iterables.frequency(set, 4.2)); assertEquals(0, Iterables.frequency(set, null)); } public void testFrequency_list() { List<String> list = newArrayList("a", "b", "a", "c", "b", "a"); assertEquals(3, Iterables.frequency(list, "a")); assertEquals(2, Iterables.frequency(list, "b")); assertEquals(1, Iterables.frequency(list, "c")); assertEquals(0, Iterables.frequency(list, "d")); assertEquals(0, Iterables.frequency(list, 4.2)); assertEquals(0, Iterables.frequency(list, null)); } public void testRemoveAll_collection() { List<String> list = newArrayList("a", "b", "c", "d", "e"); assertTrue(Iterables.removeAll(list, newArrayList("b", "d", "f"))); assertEquals(newArrayList("a", "c", "e"), list); assertFalse(Iterables.removeAll(list, newArrayList("x", "y", "z"))); assertEquals(newArrayList("a", "c", "e"), list); } public void testRemoveAll_iterable() { final List<String> list = newArrayList("a", "b", "c", "d", "e"); Iterable<String> iterable = new Iterable<String>() { @Override public Iterator<String> iterator() { return list.iterator(); } }; assertTrue(Iterables.removeAll(iterable, newArrayList("b", "d", "f"))); assertEquals(newArrayList("a", "c", "e"), list); assertFalse(Iterables.removeAll(iterable, newArrayList("x", "y", "z"))); assertEquals(newArrayList("a", "c", "e"), list); } public void testRetainAll_collection() { List<String> list = newArrayList("a", "b", "c", "d", "e"); assertTrue(Iterables.retainAll(list, newArrayList("b", "d", "f"))); assertEquals(newArrayList("b", "d"), list); assertFalse(Iterables.retainAll(list, newArrayList("b", "e", "d"))); assertEquals(newArrayList("b", "d"), list); } public void testRetainAll_iterable() { final List<String> list = newArrayList("a", "b", "c", "d", "e"); Iterable<String> iterable = new Iterable<String>() { @Override public Iterator<String> iterator() { return list.iterator(); } }; assertTrue(Iterables.retainAll(iterable, newArrayList("b", "d", "f"))); assertEquals(newArrayList("b", "d"), list); assertFalse(Iterables.retainAll(iterable, newArrayList("b", "e", "d"))); assertEquals(newArrayList("b", "d"), list); } public void testRemoveIf_randomAccess() { List<String> list = newArrayList("a", "b", "c", "d", "e"); assertTrue(Iterables.removeIf(list, new Predicate<String>() { @Override public boolean apply(String s) { return s.equals("b") || s.equals("d") || s.equals("f"); } })); assertEquals(newArrayList("a", "c", "e"), list); assertFalse(Iterables.removeIf(list, new Predicate<String>() { @Override public boolean apply(String s) { return s.equals("x") || s.equals("y") || s.equals("z"); } })); assertEquals(newArrayList("a", "c", "e"), list); } public void testRemoveIf_transformedList() { List<String> list = newArrayList("1", "2", "3", "4", "5"); List<Integer> transformed = Lists.transform(list, new Function<String, Integer>() { @Override public Integer apply(String s) { return Integer.valueOf(s); } }); assertTrue(Iterables.removeIf(transformed, new Predicate<Integer>() { @Override public boolean apply(Integer n) { return (n & 1) == 0; // isEven() } })); assertEquals(newArrayList("1", "3", "5"), list); assertFalse(Iterables.removeIf(transformed, new Predicate<Integer>() { @Override public boolean apply(Integer n) { return (n & 1) == 0; // isEven() } })); assertEquals(newArrayList("1", "3", "5"), list); } public void testRemoveIf_noRandomAccess() { List<String> list = Lists.newLinkedList(asList("a", "b", "c", "d", "e")); assertTrue(Iterables.removeIf(list, new Predicate<String>() { @Override public boolean apply(String s) { return s.equals("b") || s.equals("d") || s.equals("f"); } })); assertEquals(newArrayList("a", "c", "e"), list); assertFalse(Iterables.removeIf(list, new Predicate<String>() { @Override public boolean apply(String s) { return s.equals("x") || s.equals("y") || s.equals("z"); } })); assertEquals(newArrayList("a", "c", "e"), list); } // The Maps returned by Maps.filterEntries(), Maps.filterKeys(), and // Maps.filterValues() are not tested with removeIf() since Maps are not // Iterable. Those returned by Iterators.filter() and Iterables.filter() // are not tested because they are unmodifiable. public void testIterableWithToString() { assertEquals("[]", create().toString()); assertEquals("[a]", create("a").toString()); assertEquals("[a, b, c]", create("a", "b", "c").toString()); assertEquals("[c, a, a]", create("c", "a", "a").toString()); } public void testIterableWithToStringNull() { assertEquals("[null]", create((String) null).toString()); assertEquals("[null, null]", create(null, null).toString()); assertEquals("[, null, a]", create("", null, "a").toString()); } /** Returns a new iterable over the specified strings. */ private static Iterable<String> create(String... strings) { final List<String> list = asList(strings); return new FluentIterable<String>() { @Override public Iterator<String> iterator() { return list.iterator(); } }; } public void testConsumingIterable() { // Test data List<String> list = Lists.newArrayList(asList("a", "b")); // Test & Verify Iterable<String> consumingIterable = Iterables.consumingIterable(list); assertEquals("Iterables.consumingIterable(...)", consumingIterable.toString()); Iterator<String> consumingIterator = consumingIterable.iterator(); ASSERT.that(list).has().exactly("a", "b").inOrder(); assertTrue(consumingIterator.hasNext()); ASSERT.that(list).has().exactly("a", "b").inOrder(); assertEquals("a", consumingIterator.next()); ASSERT.that(list).has().item("b"); assertTrue(consumingIterator.hasNext()); assertEquals("b", consumingIterator.next()); ASSERT.that(list).isEmpty(); assertFalse(consumingIterator.hasNext()); } public void testConsumingIterable_queue_iterator() { final List<Integer> items = ImmutableList.of(4, 8, 15, 16, 23, 42); new IteratorTester<Integer>( 3, UNMODIFIABLE, items, IteratorTester.KnownOrder.KNOWN_ORDER) { @Override protected Iterator<Integer> newTargetIterator() { return Iterables.consumingIterable(Lists.newLinkedList(items)) .iterator(); } }.test(); } public void testConsumingIterable_queue_removesFromQueue() { Queue<Integer> queue = Lists.newLinkedList(asList(5, 14)); Iterator<Integer> consumingIterator = Iterables.consumingIterable(queue).iterator(); assertEquals(5, queue.peek().intValue()); assertEquals(5, consumingIterator.next().intValue()); assertEquals(14, queue.peek().intValue()); assertTrue(consumingIterator.hasNext()); assertTrue(queue.isEmpty()); } public void testConsumingIterable_noIteratorCall() { Queue<Integer> queue = new UnIterableQueue<Integer>(Lists.newLinkedList(asList(5, 14))); Iterator<Integer> consumingIterator = Iterables.consumingIterable(queue).iterator(); /* * Make sure that we can get an element off without calling * UnIterableQueue.iterator(). */ assertEquals(5, consumingIterator.next().intValue()); } private static class UnIterableQueue<T> extends ForwardingQueue<T> { private Queue<T> queue; UnIterableQueue(Queue<T> queue) { this.queue = queue; } @Override public Iterator<T> iterator() { throw new UnsupportedOperationException(); } @Override protected Queue<T> delegate() { return queue; } } public void testIndexOf_empty() { List<String> list = new ArrayList<String>(); assertEquals(-1, Iterables.indexOf(list, Predicates.equalTo(""))); } public void testIndexOf_oneElement() { List<String> list = Lists.newArrayList("bob"); assertEquals(0, Iterables.indexOf(list, Predicates.equalTo("bob"))); assertEquals(-1, Iterables.indexOf(list, Predicates.equalTo("jack"))); } public void testIndexOf_twoElements() { List<String> list = Lists.newArrayList("mary", "bob"); assertEquals(0, Iterables.indexOf(list, Predicates.equalTo("mary"))); assertEquals(1, Iterables.indexOf(list, Predicates.equalTo("bob"))); assertEquals(-1, Iterables.indexOf(list, Predicates.equalTo("jack"))); } public void testIndexOf_withDuplicates() { List<String> list = Lists.newArrayList("mary", "bob", "bob", "bob", "sam"); assertEquals(0, Iterables.indexOf(list, Predicates.equalTo("mary"))); assertEquals(1, Iterables.indexOf(list, Predicates.equalTo("bob"))); assertEquals(4, Iterables.indexOf(list, Predicates.equalTo("sam"))); assertEquals(-1, Iterables.indexOf(list, Predicates.equalTo("jack"))); } private static final Predicate<CharSequence> STARTSWITH_A = new Predicate<CharSequence>() { @Override public boolean apply(CharSequence input) { return (input.length() > 0) && (input.charAt(0) == 'a'); } }; public void testIndexOf_genericPredicate() { List<CharSequence> sequences = Lists.newArrayList(); sequences.add("bob"); sequences.add(new StringBuilder("charlie")); sequences.add(new StringBuffer("henry")); sequences.add(new StringBuilder("apple")); sequences.add("lemon"); assertEquals(3, Iterables.indexOf(sequences, STARTSWITH_A)); } public void testIndexOf_genericPredicate2() { List<String> sequences = Lists.newArrayList("bob", "charlie", "henry", "apple", "lemon"); assertEquals(3, Iterables.indexOf(sequences, STARTSWITH_A)); } public void testMergeSorted_empty() { // Setup Iterable<Iterable<Integer>> elements = ImmutableList.of(); // Test Iterable<Integer> iterable = Iterables.mergeSorted(elements, Ordering.natural()); // Verify Iterator<Integer> iterator = iterable.iterator(); assertFalse(iterator.hasNext()); try { iterator.next(); fail("next() on empty iterator should throw NoSuchElementException"); } catch (NoSuchElementException e) { // Huzzah! } } public void testMergeSorted_single_empty() { // Setup Iterable<Integer> iterable0 = ImmutableList.of(); Iterable<Iterable<Integer>> iterables = ImmutableList.of(iterable0); // Test & Verify verifyMergeSorted(iterables, ImmutableList.<Integer>of()); } public void testMergeSorted_single() { // Setup Iterable<Integer> iterable0 = ImmutableList.of(1, 2, 3); Iterable<Iterable<Integer>> iterables = ImmutableList.of(iterable0); // Test & Verify verifyMergeSorted(iterables, iterable0); } public void testMergeSorted_pyramid() { List<Iterable<Integer>> iterables = Lists.newLinkedList(); List<Integer> allIntegers = Lists.newArrayList(); // Creates iterators like: {{}, {0}, {0, 1}, {0, 1, 2}, ...} for (int i = 0; i < 10; i++) { List<Integer> list = Lists.newLinkedList(); for (int j = 0; j < i; j++) { list.add(j); allIntegers.add(j); } iterables.add(Ordering.natural().sortedCopy(list)); } verifyMergeSorted(iterables, allIntegers); } // Like the pyramid, but creates more unique values, along with repeated ones. public void testMergeSorted_skipping_pyramid() { List<Iterable<Integer>> iterables = Lists.newLinkedList(); List<Integer> allIntegers = Lists.newArrayList(); for (int i = 0; i < 20; i++) { List<Integer> list = Lists.newLinkedList(); for (int j = 0; j < i; j++) { list.add(j * i); allIntegers.add(j * i); } iterables.add(Ordering.natural().sortedCopy(list)); } verifyMergeSorted(iterables, allIntegers); } private static void verifyMergeSorted(Iterable<Iterable<Integer>> iterables, Iterable<Integer> unsortedExpected) { Iterable<Integer> expected = Ordering.natural().sortedCopy(unsortedExpected); Iterable<Integer> mergedIterator = Iterables.mergeSorted(iterables, Ordering.natural()); assertEquals(Lists.newLinkedList(expected), Lists.newLinkedList(mergedIterator)); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/IterablesTest.java
Java
asf20
41,251
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * Unit tests for {@code LinkedHashMultimap}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class LinkedHashMultimapTest extends TestCase { public void testValueSetHashTableExpansion() { LinkedHashMultimap<String, Integer> multimap = LinkedHashMultimap.create(); for (int z = 1; z <= 100; z++) { multimap.put("a", z); // The Eclipse compiler (and hence GWT) rejects a parameterized cast. @SuppressWarnings("unchecked") LinkedHashMultimap<String, Integer>.ValueSet valueSet = (LinkedHashMultimap.ValueSet) multimap.backingMap().get("a"); assertEquals(z, valueSet.size()); assertFalse(Hashing.needsResizing(valueSet.size(), valueSet.hashTable.length, LinkedHashMultimap.VALUE_SET_LOAD_FACTOR)); } } private Multimap<String, Integer> initializeMultimap5() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 5); multimap.put("bar", 4); multimap.put("foo", 3); multimap.put("cow", 2); multimap.put("bar", 1); return multimap; } public void testToString() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 3); multimap.put("bar", 1); multimap.putAll("foo", Arrays.asList(-1, 2, 4)); multimap.putAll("bar", Arrays.asList(2, 3)); multimap.put("foo", 1); assertEquals("{foo=[3, -1, 2, 4, 1], bar=[1, 2, 3]}", multimap.toString()); } public void testOrderingReadOnly() { Multimap<String, Integer> multimap = initializeMultimap5(); assertOrderingReadOnly(multimap); } public void testOrderingUnmodifiable() { Multimap<String, Integer> multimap = initializeMultimap5(); assertOrderingReadOnly(Multimaps.unmodifiableMultimap(multimap)); } public void testOrderingSynchronized() { Multimap<String, Integer> multimap = initializeMultimap5(); assertOrderingReadOnly(Multimaps.synchronizedMultimap(multimap)); } private void assertOrderingReadOnly(Multimap<String, Integer> multimap) { ASSERT.that(multimap.get("foo")).has().exactly(5, 3).inOrder(); ASSERT.that(multimap.get("bar")).has().exactly(4, 1).inOrder(); ASSERT.that(multimap.get("cow")).has().item(2); ASSERT.that(multimap.keySet()).has().exactly("foo", "bar", "cow").inOrder(); ASSERT.that(multimap.values()).has().exactly(5, 4, 3, 2, 1).inOrder(); Iterator<Map.Entry<String, Integer>> entryIterator = multimap.entries().iterator(); assertEquals(Maps.immutableEntry("foo", 5), entryIterator.next()); assertEquals(Maps.immutableEntry("bar", 4), entryIterator.next()); assertEquals(Maps.immutableEntry("foo", 3), entryIterator.next()); assertEquals(Maps.immutableEntry("cow", 2), entryIterator.next()); assertEquals(Maps.immutableEntry("bar", 1), entryIterator.next()); Iterator<Map.Entry<String, Collection<Integer>>> collectionIterator = multimap.asMap().entrySet().iterator(); Map.Entry<String, Collection<Integer>> entry = collectionIterator.next(); assertEquals("foo", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(5, 3).inOrder(); entry = collectionIterator.next(); assertEquals("bar", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(4, 1).inOrder(); entry = collectionIterator.next(); assertEquals("cow", entry.getKey()); ASSERT.that(entry.getValue()).has().item(2); } public void testOrderingUpdates() { Multimap<String, Integer> multimap = initializeMultimap5(); ASSERT.that(multimap.replaceValues("foo", asList(6, 7))).has().exactly(5, 3).inOrder(); ASSERT.that(multimap.keySet()).has().exactly("foo", "bar", "cow").inOrder(); ASSERT.that(multimap.removeAll("foo")).has().exactly(6, 7).inOrder(); ASSERT.that(multimap.keySet()).has().exactly("bar", "cow").inOrder(); assertTrue(multimap.remove("bar", 4)); ASSERT.that(multimap.keySet()).has().exactly("bar", "cow").inOrder(); assertTrue(multimap.remove("bar", 1)); ASSERT.that(multimap.keySet()).has().item("cow"); multimap.put("bar", 9); ASSERT.that(multimap.keySet()).has().exactly("cow", "bar").inOrder(); } public void testToStringNullExact() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 3); multimap.put("foo", -1); multimap.put(null, null); multimap.put("bar", 1); multimap.put("foo", 2); multimap.put(null, 0); multimap.put("bar", 2); multimap.put("bar", null); multimap.put("foo", null); multimap.put("foo", 4); multimap.put(null, -1); multimap.put("bar", 3); multimap.put("bar", 1); multimap.put("foo", 1); assertEquals( "{foo=[3, -1, 2, null, 4, 1], null=[null, 0, -1], bar=[1, 2, null, 3]}", multimap.toString()); } public void testPutMultimapOrdered() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.putAll(initializeMultimap5()); assertOrderingReadOnly(multimap); } public void testKeysToString_ordering() { Multimap<String, Integer> multimap = initializeMultimap5(); assertEquals("[foo x 2, bar x 2, cow]", multimap.keys().toString()); } public void testCreate() { LinkedHashMultimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("foo", 3); assertEquals(ImmutableSet.of(1, 3), multimap.get("foo")); } public void testCreateFromMultimap() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("a", 1); multimap.put("b", 2); multimap.put("a", 3); multimap.put("c", 4); LinkedHashMultimap<String, Integer> copy = LinkedHashMultimap.create(multimap); new EqualsTester() .addEqualityGroup(multimap, copy) .testEquals(); } public void testCreateFromSizes() { LinkedHashMultimap<String, Integer> multimap = LinkedHashMultimap.create(20, 15); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("foo", 3); assertEquals(ImmutableSet.of(1, 3), multimap.get("foo")); } public void testCreateFromIllegalSizes() { try { LinkedHashMultimap.create(-20, 15); fail(); } catch (IllegalArgumentException expected) {} try { LinkedHashMultimap.create(20, -15); fail(); } catch (IllegalArgumentException expected) {} } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/LinkedHashMultimapTest.java
Java
asf20
7,403
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableMultimap.Builder; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.SampleElements.Unhashables; import com.google.common.collect.testing.UnhashableObject; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Map.Entry; /** * Tests for {@link ImmutableMultimap}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class ImmutableMultimapTest extends TestCase { public void testBuilder_withImmutableEntry() { ImmutableMultimap<String, Integer> multimap = new Builder<String, Integer>() .put(Maps.immutableEntry("one", 1)) .build(); assertEquals(Arrays.asList(1), multimap.get("one")); } public void testBuilder_withImmutableEntryAndNullContents() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(Maps.immutableEntry("one", (Integer) null)); fail(); } catch (NullPointerException expected) { } try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) { } } private static class StringHolder { String string; } public void testBuilder_withMutableEntry() { ImmutableMultimap.Builder<String, Integer> builder = new Builder<String, Integer>(); final StringHolder holder = new StringHolder(); holder.string = "one"; Entry<String, Integer> entry = new AbstractMapEntry<String, Integer>() { @Override public String getKey() { return holder.string; } @Override public Integer getValue() { return 1; } }; builder.put(entry); holder.string = "two"; assertEquals(Arrays.asList(1), builder.build().get("one")); } // TODO: test ImmutableMultimap builder and factory methods public void testCopyOf() { ImmutableSetMultimap<String, String> setMultimap = ImmutableSetMultimap.of("k1", "v1"); ImmutableMultimap<String, String> setMultimapCopy = ImmutableMultimap.copyOf(setMultimap); assertSame("copyOf(ImmutableSetMultimap) should not create a new instance", setMultimap, setMultimapCopy); ImmutableListMultimap<String, String> listMultimap = ImmutableListMultimap.of("k1", "v1"); ImmutableMultimap<String, String> listMultimapCopy = ImmutableMultimap.copyOf(listMultimap); assertSame("copyOf(ImmutableListMultimap) should not create a new instance", listMultimap, listMultimapCopy); } public void testUnhashableSingletonValue() { SampleElements<UnhashableObject> unhashables = new Unhashables(); Multimap<Integer, UnhashableObject> multimap = ImmutableMultimap.of( 0, unhashables.e0); assertEquals(1, multimap.get(0).size()); assertTrue(multimap.get(0).contains(unhashables.e0)); } public void testUnhashableMixedValues() { SampleElements<UnhashableObject> unhashables = new Unhashables(); Multimap<Integer, Object> multimap = ImmutableMultimap.<Integer, Object>of( 0, unhashables.e0, 2, "hey you", 0, unhashables.e1); assertEquals(2, multimap.get(0).size()); assertTrue(multimap.get(0).contains(unhashables.e0)); assertTrue(multimap.get(0).contains(unhashables.e1)); assertTrue(multimap.get(2).contains("hey you")); } public void testEquals() { new EqualsTester() .addEqualityGroup(ImmutableMultimap.of(), ImmutableMultimap.of()) .addEqualityGroup(ImmutableMultimap.of(1, "a"), ImmutableMultimap.of(1, "a")) .addEqualityGroup( ImmutableMultimap.of(1, "a", 2, "b"), ImmutableMultimap.of(2, "b", 1, "a")) .testEquals(); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ImmutableMultimapTest.java
Java
asf20
4,456
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; /** * Test cases for {@link Tables#transformValues}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class TablesTransformValuesTest extends AbstractTableTest { private static final Function<String, Character> FIRST_CHARACTER = new Function<String, Character>() { @Override public Character apply(String input) { return input == null ? null : input.charAt(0); } }; @Override protected Table<String, Integer, Character> create( Object... data) { Table<String, Integer, String> table = HashBasedTable.create(); checkArgument(data.length % 3 == 0); for (int i = 0; i < data.length; i += 3) { String value = (data[i + 2] == null) ? null : (data[i + 2] + "transformed"); table.put((String) data[i], (Integer) data[i + 1], value); } return Tables.transformValues(table, FIRST_CHARACTER); } // Null support depends on the underlying table and function. // put() and putAll() aren't supported. @Override public void testPut() { try { table.put("foo", 1, 'a'); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException expected) {} assertSize(0); } @Override public void testPutAllTable() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Table<String, Integer, Character> other = HashBasedTable.create(); other.put("foo", 1, 'd'); other.put("bar", 2, 'e'); other.put("cat", 2, 'f'); try { table.putAll(other); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException expected) {} assertEquals((Character) 'a', table.get("foo", 1)); assertEquals((Character) 'b', table.get("bar", 1)); assertEquals((Character) 'c', table.get("foo", 3)); assertSize(3); } @Override public void testPutNull() {} @Override public void testPutNullReplace() {} @Override public void testRowClearAndPut() {} }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/TablesTransformValuesTest.java
Java
asf20
2,754
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.MinimalIterable; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Unit test for {@link ImmutableList}. * * @author Kevin Bourrillion * @author George van den Driessche * @author Jared Levy */ @GwtCompatible(emulated = true) public class ImmutableListTest extends TestCase { public static class CreationTests extends TestCase { public void testCreation_noArgs() { List<String> list = ImmutableList.of(); assertEquals(Collections.emptyList(), list); } public void testCreation_oneElement() { List<String> list = ImmutableList.of("a"); assertEquals(Collections.singletonList("a"), list); } public void testCreation_twoElements() { List<String> list = ImmutableList.of("a", "b"); assertEquals(Lists.newArrayList("a", "b"), list); } public void testCreation_threeElements() { List<String> list = ImmutableList.of("a", "b", "c"); assertEquals(Lists.newArrayList("a", "b", "c"), list); } public void testCreation_fourElements() { List<String> list = ImmutableList.of("a", "b", "c", "d"); assertEquals(Lists.newArrayList("a", "b", "c", "d"), list); } public void testCreation_fiveElements() { List<String> list = ImmutableList.of("a", "b", "c", "d", "e"); assertEquals(Lists.newArrayList("a", "b", "c", "d", "e"), list); } public void testCreation_sixElements() { List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f"); assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f"), list); } public void testCreation_sevenElements() { List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g"); assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g"), list); } public void testCreation_eightElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h"), list); } public void testCreation_nineElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h", "i"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i"), list); } public void testCreation_tenElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"), list); } public void testCreation_elevenElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"), list); } // Varargs versions public void testCreation_twelveElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"), list); } public void testCreation_thirteenElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"), list); } public void testCreation_fourteenElements() { List<String> list = ImmutableList.of( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"), list); } public void testCreation_singletonNull() { try { ImmutableList.of((String) null); fail(); } catch (NullPointerException expected) { } } public void testCreation_withNull() { try { ImmutableList.of("a", null, "b"); fail(); } catch (NullPointerException expected) { } } public void testCreation_generic() { List<String> a = ImmutableList.of("a"); // only verify that there is no compile warning ImmutableList.of(a, a); } public void testCreation_arrayOfArray() { String[] array = new String[] { "a" }; List<String[]> list = ImmutableList.<String[]>of(array); assertEquals(Collections.singletonList(array), list); } public void testCopyOf_emptyArray() { String[] array = new String[0]; List<String> list = ImmutableList.copyOf(array); assertEquals(Collections.emptyList(), list); } public void testCopyOf_arrayOfOneElement() { String[] array = new String[] { "a" }; List<String> list = ImmutableList.copyOf(array); assertEquals(Collections.singletonList("a"), list); } public void testCopyOf_nullArray() { try { ImmutableList.copyOf((String[]) null); fail(); } catch (NullPointerException expected) { } } public void testCopyOf_arrayContainingOnlyNull() { String[] array = new String[] { null }; try { ImmutableList.copyOf(array); fail(); } catch (NullPointerException expected) { } } public void testCopyOf_collection_empty() { // "<String>" is required to work around a javac 1.5 bug. Collection<String> c = MinimalCollection.<String>of(); List<String> list = ImmutableList.copyOf(c); assertEquals(Collections.emptyList(), list); } public void testCopyOf_collection_oneElement() { Collection<String> c = MinimalCollection.of("a"); List<String> list = ImmutableList.copyOf(c); assertEquals(Collections.singletonList("a"), list); } public void testCopyOf_collection_general() { Collection<String> c = MinimalCollection.of("a", "b", "a"); List<String> list = ImmutableList.copyOf(c); assertEquals(asList("a", "b", "a"), list); List<String> mutableList = asList("a", "b"); list = ImmutableList.copyOf(mutableList); mutableList.set(0, "c"); assertEquals(asList("a", "b"), list); } public void testCopyOf_collectionContainingNull() { Collection<String> c = MinimalCollection.of("a", null, "b"); try { ImmutableList.copyOf(c); fail(); } catch (NullPointerException expected) { } } public void testCopyOf_iterator_empty() { Iterator<String> iterator = Iterators.emptyIterator(); List<String> list = ImmutableList.copyOf(iterator); assertEquals(Collections.emptyList(), list); } public void testCopyOf_iterator_oneElement() { Iterator<String> iterator = Iterators.singletonIterator("a"); List<String> list = ImmutableList.copyOf(iterator); assertEquals(Collections.singletonList("a"), list); } public void testCopyOf_iterator_general() { Iterator<String> iterator = asList("a", "b", "a").iterator(); List<String> list = ImmutableList.copyOf(iterator); assertEquals(asList("a", "b", "a"), list); } public void testCopyOf_iteratorContainingNull() { Iterator<String> iterator = asList("a", null, "b").iterator(); try { ImmutableList.copyOf(iterator); fail(); } catch (NullPointerException expected) { } } public void testCopyOf_iteratorNull() { try { ImmutableList.copyOf((Iterator<String>) null); fail(); } catch (NullPointerException expected) { } } public void testCopyOf_concurrentlyMutating() { List<String> sample = Lists.newArrayList("a", "b", "c"); for (int delta : new int[] {-1, 0, 1}) { for (int i = 0; i < sample.size(); i++) { Collection<String> misleading = Helpers.misleadingSizeCollection(delta); List<String> expected = sample.subList(0, i); misleading.addAll(expected); assertEquals(expected, ImmutableList.copyOf(misleading)); assertEquals(expected, ImmutableList.copyOf((Iterable<String>) misleading)); } } } private static class CountingIterable implements Iterable<String> { int count = 0; @Override public Iterator<String> iterator() { count++; return asList("a", "b", "a").iterator(); } } public void testCopyOf_plainIterable() { CountingIterable iterable = new CountingIterable(); List<String> list = ImmutableList.copyOf(iterable); assertEquals(asList("a", "b", "a"), list); } public void testCopyOf_plainIterable_iteratesOnce() { CountingIterable iterable = new CountingIterable(); ImmutableList.copyOf(iterable); assertEquals(1, iterable.count); } public void testCopyOf_shortcut_empty() { Collection<String> c = ImmutableList.of(); assertSame(c, ImmutableList.copyOf(c)); } public void testCopyOf_shortcut_singleton() { Collection<String> c = ImmutableList.of("a"); assertSame(c, ImmutableList.copyOf(c)); } public void testCopyOf_shortcut_immutableList() { Collection<String> c = ImmutableList.of("a", "b", "c"); assertSame(c, ImmutableList.copyOf(c)); } public void testBuilderAddArrayHandlesNulls() { String[] elements = {"a", null, "b"}; ImmutableList.Builder<String> builder = ImmutableList.builder(); try { builder.add(elements); fail ("Expected NullPointerException"); } catch (NullPointerException expected) { } ImmutableList<String> result = builder.build(); /* * Maybe it rejects all elements, or maybe it adds "a" before failing. * Either way is fine with us. */ if (result.isEmpty()) { return; } assertTrue(ImmutableList.of("a").equals(result)); assertEquals(1, result.size()); } public void testBuilderAddCollectionHandlesNulls() { List<String> elements = Arrays.asList("a", null, "b"); ImmutableList.Builder<String> builder = ImmutableList.builder(); try { builder.addAll(elements); fail ("Expected NullPointerException"); } catch (NullPointerException expected) { } ImmutableList<String> result = builder.build(); assertEquals(ImmutableList.of("a"), result); assertEquals(1, result.size()); } } public static class BasicTests extends TestCase { public void testEquals_immutableList() { Collection<String> c = ImmutableList.of("a", "b", "c"); assertTrue(c.equals(ImmutableList.of("a", "b", "c"))); assertFalse(c.equals(ImmutableList.of("a", "c", "b"))); assertFalse(c.equals(ImmutableList.of("a", "b"))); assertFalse(c.equals(ImmutableList.of("a", "b", "c", "d"))); } public void testBuilderAdd() { ImmutableList<String> list = new ImmutableList.Builder<String>() .add("a") .add("b") .add("a") .add("c") .build(); assertEquals(asList("a", "b", "a", "c"), list); } public void testBuilderAdd_varargs() { ImmutableList<String> list = new ImmutableList.Builder<String>() .add("a", "b", "a", "c") .build(); assertEquals(asList("a", "b", "a", "c"), list); } public void testBuilderAddAll_iterable() { List<String> a = asList("a", "b"); List<String> b = asList("c", "d"); ImmutableList<String> list = new ImmutableList.Builder<String>() .addAll(a) .addAll(b) .build(); assertEquals(asList( "a", "b", "c", "d"), list); b.set(0, "f"); assertEquals(asList( "a", "b", "c", "d"), list); } public void testBuilderAddAll_iterator() { List<String> a = asList("a", "b"); List<String> b = asList("c", "d"); ImmutableList<String> list = new ImmutableList.Builder<String>() .addAll(a.iterator()) .addAll(b.iterator()) .build(); assertEquals(asList( "a", "b", "c", "d"), list); b.set(0, "f"); assertEquals(asList( "a", "b", "c", "d"), list); } public void testComplexBuilder() { List<Integer> colorElem = asList(0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF); ImmutableList.Builder<Integer> webSafeColorsBuilder = ImmutableList.builder(); for (Integer red : colorElem) { for (Integer green : colorElem) { for (Integer blue : colorElem) { webSafeColorsBuilder.add((red << 16) + (green << 8) + blue); } } } ImmutableList<Integer> webSafeColors = webSafeColorsBuilder.build(); assertEquals(216, webSafeColors.size()); Integer[] webSafeColorArray = webSafeColors.toArray(new Integer[webSafeColors.size()]); assertEquals(0x000000, (int) webSafeColorArray[0]); assertEquals(0x000033, (int) webSafeColorArray[1]); assertEquals(0x000066, (int) webSafeColorArray[2]); assertEquals(0x003300, (int) webSafeColorArray[6]); assertEquals(0x330000, (int) webSafeColorArray[36]); assertEquals(0x000066, (int) webSafeColors.get(2)); assertEquals(0x003300, (int) webSafeColors.get(6)); ImmutableList<Integer> addedColor = webSafeColorsBuilder.add(0x00BFFF).build(); assertEquals("Modifying the builder should not have changed any already" + " built sets", 216, webSafeColors.size()); assertEquals("the new array should be one bigger than webSafeColors", 217, addedColor.size()); Integer[] appendColorArray = addedColor.toArray(new Integer[addedColor.size()]); assertEquals(0x00BFFF, (int) appendColorArray[216]); } public void testBuilderAddHandlesNullsCorrectly() { ImmutableList.Builder<String> builder = ImmutableList.builder(); try { builder.add((String) null); fail("expected NullPointerException"); } catch (NullPointerException expected) { } try { builder.add((String[]) null); fail("expected NullPointerException"); } catch (NullPointerException expected) { } try { builder.add("a", null, "b"); fail("expected NullPointerException"); } catch (NullPointerException expected) { } } public void testBuilderAddAllHandlesNullsCorrectly() { ImmutableList.Builder<String> builder = ImmutableList.builder(); try { builder.addAll((Iterable<String>) null); fail("expected NullPointerException"); } catch (NullPointerException expected) { } try { builder.addAll((Iterator<String>) null); fail("expected NullPointerException"); } catch (NullPointerException expected) { } builder = ImmutableList.builder(); List<String> listWithNulls = asList("a", null, "b"); try { builder.addAll(listWithNulls); fail("expected NullPointerException"); } catch (NullPointerException expected) { } builder = ImmutableList.builder(); Iterator<String> iteratorWithNulls = asList("a", null, "b").iterator(); try { builder.addAll(iteratorWithNulls); fail("expected NullPointerException"); } catch (NullPointerException expected) { } Iterable<String> iterableWithNulls = MinimalIterable.of("a", null, "b"); try { builder.addAll(iterableWithNulls); fail("expected NullPointerException"); } catch (NullPointerException expected) { } } public void testAsList() { ImmutableList<String> list = ImmutableList.of("a", "b"); assertSame(list, list.asList()); } } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ImmutableListTest.java
Java
asf20
16,765
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableSet.Builder; import com.google.common.testing.EqualsTester; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; /** * Unit test for {@link ImmutableSet}. * * @author Kevin Bourrillion * @author Jared Levy * @author Nick Kralevich */ @GwtCompatible(emulated = true) public class ImmutableSetTest extends AbstractImmutableSetTest { @Override protected Set<String> of() { return ImmutableSet.of(); } @Override protected Set<String> of(String e) { return ImmutableSet.of(e); } @Override protected Set<String> of(String e1, String e2) { return ImmutableSet.of(e1, e2); } @Override protected Set<String> of(String e1, String e2, String e3) { return ImmutableSet.of(e1, e2, e3); } @Override protected Set<String> of( String e1, String e2, String e3, String e4) { return ImmutableSet.of(e1, e2, e3, e4); } @Override protected Set<String> of( String e1, String e2, String e3, String e4, String e5) { return ImmutableSet.of(e1, e2, e3, e4, e5); } @Override protected Set<String> of(String e1, String e2, String e3, String e4, String e5, String e6, String... rest) { return ImmutableSet.of(e1, e2, e3, e4, e5, e6, rest); } @Override protected Set<String> copyOf(String[] elements) { return ImmutableSet.copyOf(elements); } @Override protected Set<String> copyOf(Collection<String> elements) { return ImmutableSet.copyOf(elements); } @Override protected Set<String> copyOf(Iterable<String> elements) { return ImmutableSet.copyOf(elements); } @Override protected Set<String> copyOf(Iterator<String> elements) { return ImmutableSet.copyOf(elements); } public void testCreation_allDuplicates() { ImmutableSet<String> set = ImmutableSet.copyOf(Lists.newArrayList("a", "a")); assertTrue(set instanceof SingletonImmutableSet); assertEquals(Lists.newArrayList("a"), Lists.newArrayList(set)); } public void testCreation_oneDuplicate() { // now we'll get the varargs overload ImmutableSet<String> set = ImmutableSet.of( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "a"); assertEquals(Lists.newArrayList( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"), Lists.newArrayList(set)); } public void testCreation_manyDuplicates() { // now we'll get the varargs overload ImmutableSet<String> set = ImmutableSet.of( "a", "b", "c", "c", "c", "c", "b", "b", "a", "a", "c", "c", "c", "a"); ASSERT.that(set).has().exactly("a", "b", "c").inOrder(); } public void testCreation_arrayOfArray() { String[] array = new String[] { "a" }; Set<String[]> set = ImmutableSet.<String[]>of(array); assertEquals(Collections.singleton(array), set); } public void testCopyOf_copiesImmutableSortedSet() { ImmutableSortedSet<String> sortedSet = ImmutableSortedSet.of("a"); ImmutableSet<String> copy = ImmutableSet.copyOf(sortedSet); assertNotSame(sortedSet, copy); } @Override <E extends Comparable<E>> Builder<E> builder() { return ImmutableSet.builder(); } @Override int getComplexBuilderSetLastElement() { return LAST_COLOR_ADDED; } public void testEquals() { new EqualsTester() .addEqualityGroup(ImmutableSet.of(), ImmutableSet.of()) .addEqualityGroup(ImmutableSet.of(1), ImmutableSet.of(1), ImmutableSet.of(1, 1)) .addEqualityGroup(ImmutableSet.of(1, 2, 1), ImmutableSet.of(2, 1, 1)) .testEquals(); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ImmutableSetTest.java
Java
asf20
4,323
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.Arrays; import java.util.List; /** * Unit test for {@code ObjectArrays}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class ObjectArraysTest extends TestCase { public void testNewArray_fromArray_Empty() { String[] in = new String[0]; String[] empty = ObjectArrays.newArray(in, 0); assertEquals(0, empty.length); } public void testNewArray_fromArray_Nonempty() { String[] array = ObjectArrays.newArray(new String[0], 2); assertEquals(String[].class, array.getClass()); assertEquals(2, array.length); assertNull(array[0]); } public void testNewArray_fromArray_OfArray() { String[][] array = ObjectArrays.newArray(new String[0][0], 1); assertEquals(String[][].class, array.getClass()); assertEquals(1, array.length); assertNull(array[0]); } public void testToArrayImpl1() { doTestToArrayImpl1(Lists.<Integer>newArrayList()); doTestToArrayImpl1(Lists.newArrayList(1)); doTestToArrayImpl1(Lists.newArrayList(1, null, 3)); } private void doTestToArrayImpl1(List<Integer> list) { Object[] reference = list.toArray(); Object[] target = ObjectArrays.toArrayImpl(list); assertEquals(reference.getClass(), target.getClass()); assertTrue(Arrays.equals(reference, target)); } public void testToArrayImpl2() { doTestToArrayImpl2(Lists.<Integer>newArrayList(), new Integer[0], false); doTestToArrayImpl2(Lists.<Integer>newArrayList(), new Integer[1], true); doTestToArrayImpl2(Lists.newArrayList(1), new Integer[0], false); doTestToArrayImpl2(Lists.newArrayList(1), new Integer[1], true); doTestToArrayImpl2(Lists.newArrayList(1), new Integer[] { 2, 3 }, true); doTestToArrayImpl2(Lists.newArrayList(1, null, 3), new Integer[0], false); doTestToArrayImpl2(Lists.newArrayList(1, null, 3), new Integer[2], false); doTestToArrayImpl2(Lists.newArrayList(1, null, 3), new Integer[3], true); } private void doTestToArrayImpl2(List<Integer> list, Integer[] array1, boolean expectModify) { Integer[] starting = ObjectArrays.arraysCopyOf(array1, array1.length); Integer[] array2 = ObjectArrays.arraysCopyOf(array1, array1.length); Object[] reference = list.toArray(array1); Object[] target = ObjectArrays.toArrayImpl(list, array2); assertEquals(reference.getClass(), target.getClass()); assertTrue(Arrays.equals(reference, target)); assertTrue(Arrays.equals(reference, target)); Object[] expectedArray1 = expectModify ? reference : starting; Object[] expectedArray2 = expectModify ? target : starting; assertTrue(Arrays.equals(expectedArray1, array1)); assertTrue(Arrays.equals(expectedArray2, array2)); } public void testPrependZeroElements() { String[] result = ObjectArrays.concat("foo", new String[] {}); ASSERT.that(result).has().item("foo"); } public void testPrependOneElement() { String[] result = ObjectArrays.concat("foo", new String[] { "bar" }); ASSERT.that(result).has().exactly("foo", "bar").inOrder(); } public void testPrependTwoElements() { String[] result = ObjectArrays.concat("foo", new String[] { "bar", "baz" }); ASSERT.that(result).has().exactly("foo", "bar", "baz").inOrder(); } public void testAppendZeroElements() { String[] result = ObjectArrays.concat(new String[] {}, "foo"); ASSERT.that(result).has().item("foo"); } public void testAppendOneElement() { String[] result = ObjectArrays.concat(new String[] { "foo" }, "bar"); ASSERT.that(result).has().exactly("foo", "bar").inOrder(); } public void testAppendTwoElements() { String[] result = ObjectArrays.concat(new String[] { "foo", "bar" }, "baz"); ASSERT.that(result).has().exactly("foo", "bar", "baz").inOrder(); } public void testEmptyArrayToEmpty() { doTestNewArrayEquals(new Object[0], 0); } public void testEmptyArrayToNonEmpty() { checkArrayEquals(new Long[5], ObjectArrays.newArray(new Long[0], 5)); } public void testNonEmptyToShorter() { checkArrayEquals(new String[9], ObjectArrays.newArray(new String[10], 9)); } public void testNonEmptyToSameLength() { doTestNewArrayEquals(new String[10], 10); } public void testNonEmptyToLonger() { checkArrayEquals(new String[10], ObjectArrays.newArray(new String[] { "a", "b", "c", "d", "e" }, 10)); } private static void checkArrayEquals(Object[] expected, Object[] actual) { assertTrue("expected(" + expected.getClass() + "): " + Arrays.toString(expected) + " actual(" + actual.getClass() + "): " + Arrays.toString(actual), arrayEquals(expected, actual)); } private static boolean arrayEquals(Object[] array1, Object[] array2) { assertSame(array1.getClass(), array2.getClass()); return Arrays.equals(array1, array2); } private static void doTestNewArrayEquals(Object[] expected, int length) { checkArrayEquals(expected, ObjectArrays.newArray(expected, length)); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ObjectArraysTest.java
Java
asf20
5,761
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.ConcurrentModificationException; import java.util.List; import java.util.RandomAccess; /** * Unit tests for {@code ArrayListMultimap}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class ArrayListMultimapTest extends TestCase { protected ListMultimap<String, Integer> create() { return ArrayListMultimap.create(); } /** * Confirm that get() returns a List implementing RandomAccess. */ public void testGetRandomAccess() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); assertTrue(multimap.get("foo") instanceof RandomAccess); assertTrue(multimap.get("bar") instanceof RandomAccess); } /** * Confirm that removeAll() returns a List implementing RandomAccess. */ public void testRemoveAllRandomAccess() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); assertTrue(multimap.removeAll("foo") instanceof RandomAccess); assertTrue(multimap.removeAll("bar") instanceof RandomAccess); } /** * Confirm that replaceValues() returns a List implementing RandomAccess. */ public void testReplaceValuesRandomAccess() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); assertTrue(multimap.replaceValues("foo", asList(2, 4)) instanceof RandomAccess); assertTrue(multimap.replaceValues("bar", asList(2, 4)) instanceof RandomAccess); } /** * Test throwing ConcurrentModificationException when a sublist's ancestor's * delegate changes. */ public void testSublistConcurrentModificationException() { ListMultimap<String, Integer> multimap = create(); multimap.putAll("foo", asList(1, 2, 3, 4, 5)); List<Integer> list = multimap.get("foo"); ASSERT.that(multimap.get("foo")).has().exactly(1, 2, 3, 4, 5).inOrder(); List<Integer> sublist = list.subList(0, 5); ASSERT.that(sublist).has().exactly(1, 2, 3, 4, 5).inOrder(); sublist.clear(); assertTrue(sublist.isEmpty()); multimap.put("foo", 6); try { sublist.isEmpty(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) {} } public void testCreateFromMultimap() { Multimap<String, Integer> multimap = create(); multimap.put("foo", 1); multimap.put("foo", 3); multimap.put("bar", 2); ArrayListMultimap<String, Integer> copy = ArrayListMultimap.create(multimap); assertEquals(multimap, copy); } public void testCreate() { ArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create(); assertEquals(3, multimap.expectedValuesPerKey); } public void testCreateFromSizes() { ArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create(15, 20); assertEquals(20, multimap.expectedValuesPerKey); } public void testCreateFromIllegalSizes() { try { ArrayListMultimap.create(15, -2); fail(); } catch (IllegalArgumentException expected) {} try { ArrayListMultimap.create(-15, 2); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateFromHashMultimap() { Multimap<String, Integer> original = HashMultimap.create(); ArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create(original); assertEquals(3, multimap.expectedValuesPerKey); } public void testCreateFromArrayListMultimap() { ArrayListMultimap<String, Integer> original = ArrayListMultimap.create(15, 20); ArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create(original); assertEquals(20, multimap.expectedValuesPerKey); } public void testTrimToSize() { ArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create(); multimap.put("foo", 1); multimap.put("foo", 2); multimap.put("bar", 3); multimap.trimToSize(); assertEquals(3, multimap.size()); ASSERT.that(multimap.get("foo")).has().exactly(1, 2).inOrder(); ASSERT.that(multimap.get("bar")).has().item(3); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ArrayListMultimapTest.java
Java
asf20
4,981
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.testing.EqualsTester; /** * Tests {@link EmptyImmutableTable} * * @author Gregory Kick */ @GwtCompatible(emulated = true) public class EmptyImmutableTableTest extends AbstractImmutableTableTest { private static final ImmutableTable<Character, Integer, String> INSTANCE = ImmutableTable.of(); @Override Iterable<ImmutableTable<Character, Integer, String>> getTestInstances() { return ImmutableSet.of(INSTANCE); } public void testHashCode() { assertEquals(0, INSTANCE.hashCode()); } public void testEqualsObject() { Table<Character, Integer, String> nonEmptyTable = HashBasedTable.create(); nonEmptyTable.put('A', 1, "blah"); new EqualsTester() .addEqualityGroup(INSTANCE, HashBasedTable.create(), TreeBasedTable.create()) .addEqualityGroup(nonEmptyTable) .testEquals(); } public void testToString() { assertEquals("{}", INSTANCE.toString()); } public void testSize() { assertEquals(0, INSTANCE.size()); } public void testGet() { assertNull(INSTANCE.get('a', 1)); } public void testIsEmpty() { assertTrue(INSTANCE.isEmpty()); } public void testCellSet() { assertEquals(ImmutableSet.of(), INSTANCE.cellSet()); } public void testColumn() { assertEquals(ImmutableMap.of(), INSTANCE.column(1)); } public void testColumnKeySet() { assertEquals(ImmutableSet.of(), INSTANCE.columnKeySet()); } public void testColumnMap() { assertEquals(ImmutableMap.of(), INSTANCE.columnMap()); } public void testContains() { assertFalse(INSTANCE.contains('a', 1)); } public void testContainsColumn() { assertFalse(INSTANCE.containsColumn(1)); } public void testContainsRow() { assertFalse(INSTANCE.containsRow('a')); } public void testContainsValue() { assertFalse(INSTANCE.containsValue("blah")); } public void testRow() { assertEquals(ImmutableMap.of(), INSTANCE.row('a')); } public void testRowKeySet() { assertEquals(ImmutableSet.of(), INSTANCE.rowKeySet()); } public void testRowMap() { assertEquals(ImmutableMap.of(), INSTANCE.rowMap()); } public void testValues() { assertTrue(INSTANCE.values().isEmpty()); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/EmptyImmutableTableTest.java
Java
asf20
2,920
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import java.util.Iterator; import java.util.NoSuchElementException; /** Tests for {@link AbstractSequentialIterator}. */ @GwtCompatible(emulated = true) public class AbstractSequentialIteratorTest extends TestCase { public void testDoubler() { Iterable<Integer> doubled = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return newDoubler(2, 32); } }; ASSERT.that(doubled).iteratesOverSequence(2, 4, 8, 16, 32); } public void testSampleCode() { Iterable<Integer> actual = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { Iterator<Integer> powersOfTwo = new AbstractSequentialIterator<Integer>(1) { protected Integer computeNext(Integer previous) { return (previous == 1 << 30) ? null : previous * 2; } }; return powersOfTwo; } }; ASSERT.that(actual).iteratesOverSequence(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824); } public void testEmpty() { Iterator<Object> empty = newEmpty(); assertFalse(empty.hasNext()); try { empty.next(); fail(); } catch (NoSuchElementException expected) { } try { empty.remove(); fail(); } catch (UnsupportedOperationException expected) { } } public void testBroken() { Iterator<Object> broken = newBroken(); assertTrue(broken.hasNext()); // We can't retrieve even the known first element: try { broken.next(); fail(); } catch (MyException expected) { } try { broken.next(); fail(); } catch (MyException expected) { } } private static Iterator<Integer> newDoubler(int first, final int last) { return new AbstractSequentialIterator<Integer>(first) { @Override protected Integer computeNext(Integer previous) { return (previous == last) ? null : previous * 2; } }; } private static <T> Iterator<T> newEmpty() { return new AbstractSequentialIterator<T>(null) { @Override protected T computeNext(T previous) { throw new AssertionFailedError(); } }; } private static Iterator<Object> newBroken() { return new AbstractSequentialIterator<Object>("UNUSED") { @Override protected Object computeNext(Object previous) { throw new MyException(); } }; } private static class MyException extends RuntimeException {} }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/AbstractSequentialIteratorTest.java
Java
asf20
3,464
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SortedMapInterfaceTest; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.SortedMap; /** * Test cases for {@link TreeBasedTable}. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class TreeBasedTableTest extends AbstractTableTest { public static class TreeRowTest extends SortedMapInterfaceTest<String, String> { public TreeRowTest() { super(false, false, true, true, true); } @Override protected SortedMap<String, String> makeEmptyMap() { TreeBasedTable<String, String, String> table = TreeBasedTable.create(); table.put("a", "b", "c"); table.put("c", "b", "a"); table.put("a", "a", "d"); return table.row("b"); } @Override protected SortedMap<String, String> makePopulatedMap() { TreeBasedTable<String, String, String> table = TreeBasedTable.create(); table.put("a", "b", "c"); table.put("c", "b", "a"); table.put("b", "b", "x"); table.put("b", "c", "y"); table.put("b", "x", "n"); table.put("a", "a", "d"); return table.row("b"); } @Override protected String getKeyNotInPopulatedMap() { return "q"; } @Override protected String getValueNotInPopulatedMap() { return "p"; } public void testClearSubMapOfRowMap() { TreeBasedTable<String, String, String> table = TreeBasedTable.create(); table.put("a", "b", "c"); table.put("c", "b", "a"); table.put("b", "b", "x"); table.put("b", "c", "y"); table.put("b", "x", "n"); table.put("a", "a", "d"); table.row("b").subMap("c", "x").clear(); assertEquals(table.row("b"), ImmutableMap.of("b", "x", "x", "n")); table.row("b").subMap("b", "y").clear(); assertEquals(table.row("b"), ImmutableMap.of()); assertFalse(table.backingMap.containsKey("b")); } } private TreeBasedTable<String, Integer, Character> sortedTable; protected TreeBasedTable<String, Integer, Character> create( Comparator<? super String> rowComparator, Comparator<? super Integer> columnComparator, Object... data) { TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create(rowComparator, columnComparator); table.put("foo", 4, 'a'); table.put("cat", 1, 'b'); table.clear(); populate(table, data); return table; } @Override protected TreeBasedTable<String, Integer, Character> create( Object... data) { TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create(); table.put("foo", 4, 'a'); table.put("cat", 1, 'b'); table.clear(); populate(table, data); return table; } public void testCreateExplicitComparators() { table = TreeBasedTable.create( Collections.reverseOrder(), Ordering.usingToString()); table.put("foo", 3, 'a'); table.put("foo", 12, 'b'); table.put("bar", 5, 'c'); table.put("cat", 8, 'd'); ASSERT.that(table.rowKeySet()).has().exactly("foo", "cat", "bar").inOrder(); ASSERT.that(table.row("foo").keySet()).has().exactly(12, 3).inOrder(); } public void testCreateCopy() { TreeBasedTable<String, Integer, Character> original = TreeBasedTable.create( Collections.reverseOrder(), Ordering.usingToString()); original.put("foo", 3, 'a'); original.put("foo", 12, 'b'); original.put("bar", 5, 'c'); original.put("cat", 8, 'd'); table = TreeBasedTable.create(original); ASSERT.that(table.rowKeySet()).has().exactly("foo", "cat", "bar").inOrder(); ASSERT.that(table.row("foo").keySet()).has().exactly(12, 3).inOrder(); assertEquals(original, table); } public void testToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("{bar={1=b}, foo={1=a, 3=c}}", table.toString()); assertEquals("{bar={1=b}, foo={1=a, 3=c}}", table.rowMap().toString()); } public void testCellSetToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[(bar,1)=b, (foo,1)=a, (foo,3)=c]", table.cellSet().toString()); } public void testRowKeySetToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[bar, foo]", table.rowKeySet().toString()); } public void testValuesToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[b, a, c]", table.values().toString()); } public void testRowComparator() { sortedTable = TreeBasedTable.create(); assertSame(Ordering.natural(), sortedTable.rowComparator()); sortedTable = TreeBasedTable.create( Collections.reverseOrder(), Ordering.usingToString()); assertSame(Collections.reverseOrder(), sortedTable.rowComparator()); } public void testColumnComparator() { sortedTable = TreeBasedTable.create(); assertSame(Ordering.natural(), sortedTable.columnComparator()); sortedTable = TreeBasedTable.create( Collections.reverseOrder(), Ordering.usingToString()); assertSame(Ordering.usingToString(), sortedTable.columnComparator()); } public void testRowKeySetComparator() { sortedTable = TreeBasedTable.create(); assertSame(Ordering.natural(), sortedTable.rowKeySet().comparator()); sortedTable = TreeBasedTable.create( Collections.reverseOrder(), Ordering.usingToString()); assertSame(Collections.reverseOrder(), sortedTable.rowKeySet().comparator()); } public void testRowKeySetFirst() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertSame("bar", sortedTable.rowKeySet().first()); } public void testRowKeySetLast() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertSame("foo", sortedTable.rowKeySet().last()); } public void testRowKeySetHeadSet() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Set<String> set = sortedTable.rowKeySet().headSet("cat"); assertEquals(Collections.singleton("bar"), set); set.clear(); assertTrue(set.isEmpty()); assertEquals(Collections.singleton("foo"), sortedTable.rowKeySet()); } public void testRowKeySetTailSet() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Set<String> set = sortedTable.rowKeySet().tailSet("cat"); assertEquals(Collections.singleton("foo"), set); set.clear(); assertTrue(set.isEmpty()); assertEquals(Collections.singleton("bar"), sortedTable.rowKeySet()); } public void testRowKeySetSubSet() { sortedTable = create( "foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c', "dog", 2, 'd'); Set<String> set = sortedTable.rowKeySet().subSet("cat", "egg"); assertEquals(Collections.singleton("dog"), set); set.clear(); assertTrue(set.isEmpty()); assertEquals(ImmutableSet.of("bar", "foo"), sortedTable.rowKeySet()); } public void testRowMapComparator() { sortedTable = TreeBasedTable.create(); assertSame(Ordering.natural(), sortedTable.rowMap().comparator()); sortedTable = TreeBasedTable.create( Collections.reverseOrder(), Ordering.usingToString()); assertSame(Collections.reverseOrder(), sortedTable.rowMap().comparator()); } public void testRowMapFirstKey() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertSame("bar", sortedTable.rowMap().firstKey()); } public void testRowMapLastKey() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertSame("foo", sortedTable.rowMap().lastKey()); } public void testRowKeyMapHeadMap() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<String, Map<Integer, Character>> map = sortedTable.rowMap().headMap("cat"); assertEquals(1, map.size()); assertEquals(ImmutableMap.of(1, 'b'), map.get("bar")); map.clear(); assertTrue(map.isEmpty()); assertEquals(Collections.singleton("foo"), sortedTable.rowKeySet()); } public void testRowKeyMapTailMap() { sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<String, Map<Integer, Character>> map = sortedTable.rowMap().tailMap("cat"); assertEquals(1, map.size()); assertEquals(ImmutableMap.of(1, 'a', 3, 'c'), map.get("foo")); map.clear(); assertTrue(map.isEmpty()); assertEquals(Collections.singleton("bar"), sortedTable.rowKeySet()); } public void testRowKeyMapSubMap() { sortedTable = create( "foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c', "dog", 2, 'd'); Map<String, Map<Integer, Character>> map = sortedTable.rowMap().subMap("cat", "egg"); assertEquals(ImmutableMap.of(2, 'd'), map.get("dog")); map.clear(); assertTrue(map.isEmpty()); assertEquals(ImmutableSet.of("bar", "foo"), sortedTable.rowKeySet()); } public void testRowMapValuesAreSorted() { sortedTable = create( "foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c', "dog", 2, 'd'); assertTrue(sortedTable.rowMap().get("foo") instanceof SortedMap); } public void testColumnKeySet_isSorted() { table = create("a", 2, 'X', "a", 2, 'X', "b", 3, 'X', "b", 2, 'X', "c", 10, 'X', "c", 10, 'X', "c", 20, 'X', "d", 15, 'X', "d", 20, 'X', "d", 1, 'X', "e", 5, 'X' ); assertEquals("[1, 2, 3, 5, 10, 15, 20]", table.columnKeySet().toString()); } public void testColumnKeySet_isSortedWithRealComparator() { table = create(String.CASE_INSENSITIVE_ORDER, Ordering.natural().reverse(), "a", 2, 'X', "a", 2, 'X', "b", 3, 'X', "b", 2, 'X', "c", 10, 'X', "c", 10, 'X', "c", 20, 'X', "d", 15, 'X', "d", 20, 'X', "d", 1, 'X', "e", 5, 'X' ); assertEquals("[20, 15, 10, 5, 3, 2, 1]", table.columnKeySet().toString()); } public void testColumnKeySet_empty() { table = create(); assertEquals("[]", table.columnKeySet().toString()); } public void testColumnKeySet_oneRow() { table = create("a", 2, 'X', "a", 1, 'X' ); assertEquals("[1, 2]", table.columnKeySet().toString()); } public void testColumnKeySet_oneColumn() { table = create("a", 1, 'X', "b", 1, 'X' ); assertEquals("[1]", table.columnKeySet().toString()); } public void testColumnKeySet_oneEntry() { table = create("a", 1, 'X'); assertEquals("[1]", table.columnKeySet().toString()); } public void testRowEntrySetContains() { table = sortedTable = create("a", 2, 'X', "a", 2, 'X', "b", 3, 'X', "b", 2, 'X', "c", 10, 'X', "c", 10, 'X', "c", 20, 'X', "d", 15, 'X', "d", 20, 'X', "d", 1, 'X', "e", 5, 'X'); SortedMap<Integer, Character> row = sortedTable.row("c"); Set<Map.Entry<Integer, Character>> entrySet = row.entrySet(); assertTrue(entrySet.contains(Maps.immutableEntry(10, 'X'))); assertTrue(entrySet.contains(Maps.immutableEntry(20, 'X'))); assertFalse(entrySet.contains(Maps.immutableEntry(15, 'X'))); entrySet = row.tailMap(15).entrySet(); assertFalse(entrySet.contains(Maps.immutableEntry(10, 'X'))); assertTrue(entrySet.contains(Maps.immutableEntry(20, 'X'))); assertFalse(entrySet.contains(Maps.immutableEntry(15, 'X'))); } public void testRowEntrySetRemove() { table = sortedTable = create("a", 2, 'X', "a", 2, 'X', "b", 3, 'X', "b", 2, 'X', "c", 10, 'X', "c", 10, 'X', "c", 20, 'X', "d", 15, 'X', "d", 20, 'X', "d", 1, 'X', "e", 5, 'X'); SortedMap<Integer, Character> row = sortedTable.row("c"); Set<Map.Entry<Integer, Character>> entrySet = row.tailMap(15).entrySet(); assertFalse(entrySet.remove(Maps.immutableEntry(10, 'X'))); assertTrue(entrySet.remove(Maps.immutableEntry(20, 'X'))); assertFalse(entrySet.remove(Maps.immutableEntry(15, 'X'))); entrySet = row.entrySet(); assertTrue(entrySet.remove(Maps.immutableEntry(10, 'X'))); assertFalse(entrySet.remove(Maps.immutableEntry(20, 'X'))); assertFalse(entrySet.remove(Maps.immutableEntry(15, 'X'))); } public void testRowSize() { table = sortedTable = create("a", 2, 'X', "a", 2, 'X', "b", 3, 'X', "b", 2, 'X', "c", 10, 'X', "c", 10, 'X', "c", 20, 'X', "d", 15, 'X', "d", 20, 'X', "d", 1, 'X', "e", 5, 'X'); SortedMap<Integer, Character> row = sortedTable.row("c"); assertEquals(row.size(), 2); assertEquals(row.tailMap(15).size(), 1); } public void testSubRowClearAndPut() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); SortedMap<Integer, Character> row = (SortedMap<Integer, Character>) table.row("foo"); SortedMap<Integer, Character> subRow = row.tailMap(2); assertEquals(ImmutableMap.of(1, 'a', 3, 'c'), row); assertEquals(ImmutableMap.of(3, 'c'), subRow); table.remove("foo", 3); assertEquals(ImmutableMap.of(1, 'a'), row); assertEquals(ImmutableMap.of(), subRow); table.remove("foo", 1); assertEquals(ImmutableMap.of(), row); assertEquals(ImmutableMap.of(), subRow); table.put("foo", 2, 'b'); assertEquals(ImmutableMap.of(2, 'b'), row); assertEquals(ImmutableMap.of(2, 'b'), subRow); row.clear(); assertEquals(ImmutableMap.of(), row); assertEquals(ImmutableMap.of(), subRow); table.put("foo", 5, 'x'); assertEquals(ImmutableMap.of(5, 'x'), row); assertEquals(ImmutableMap.of(5, 'x'), subRow); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/TreeBasedTableTest.java
Java
asf20
14,758
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static java.util.concurrent.TimeUnit.HOURS; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import junit.framework.TestCase; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * @author Charles Fry */ @GwtCompatible(emulated = true) public class MapMakerTest extends TestCase { // "Basher tests", where we throw a bunch of stuff at a Cache and check basic invariants. /* * TODO(cpovirk): eliminate duplication between these tests and those in LegacyMapMakerTests and * anywhere else */ /** Tests for the builder. */ public static class MakerTest extends TestCase { public void testInitialCapacity_negative() { MapMaker maker = new MapMaker(); try { maker.initialCapacity(-1); fail(); } catch (IllegalArgumentException expected) { } } // TODO(cpovirk): enable when ready public void xtestInitialCapacity_setTwice() { MapMaker maker = new MapMaker().initialCapacity(16); try { // even to the same value is not allowed maker.initialCapacity(16); fail(); } catch (IllegalArgumentException expected) { } } @SuppressWarnings("deprecation") // test of deprecated method public void testExpiration_setTwice() { MapMaker maker = new MapMaker().expireAfterWrite(1, HOURS); try { // even to the same value is not allowed maker.expireAfterWrite(1, HOURS); fail(); } catch (IllegalStateException expected) { } } public void testMaximumSize_setTwice() { MapMaker maker = new MapMaker().maximumSize(16); try { // even to the same value is not allowed maker.maximumSize(16); fail(); } catch (IllegalStateException expected) { } } public void testReturnsPlainConcurrentHashMapWhenPossible() { Map<?, ?> map = new MapMaker() .initialCapacity(5) .makeMap(); assertTrue(map instanceof ConcurrentHashMap); } } /** Tests of the built map with maximumSize. */ public static class MaximumSizeTest extends TestCase { public void testPut_sizeIsZero() { ConcurrentMap<Object, Object> map = new MapMaker().maximumSize(0).makeMap(); assertEquals(0, map.size()); map.put(new Object(), new Object()); assertEquals(0, map.size()); } public void testSizeBasedEviction() { int numKeys = 10; int mapSize = 5; ConcurrentMap<Object, Object> map = new MapMaker().maximumSize(mapSize).makeMap(); for (int i = 0; i < numKeys; i++) { map.put(i, i); } assertEquals(mapSize, map.size()); for (int i = numKeys - mapSize; i < mapSize; i++) { assertTrue(map.containsKey(i)); } } } /** Tests for recursive computation. */ public static class RecursiveComputationTest extends TestCase { Function<Integer, String> recursiveComputer = new Function<Integer, String>() { @Override public String apply(Integer key) { if (key > 0) { return key + ", " + recursiveMap.get(key - 1); } else { return "0"; } } }; ConcurrentMap<Integer, String> recursiveMap = new MapMaker() .makeComputingMap(recursiveComputer); public void testRecursiveComputation() { assertEquals("3, 2, 1, 0", recursiveMap.get(3)); } } /** * Tests for computing functionality. */ public static class ComputingTest extends TestCase { public void testComputerThatReturnsNull() { ConcurrentMap<Integer, String> map = new MapMaker() .makeComputingMap(new Function<Integer, String>() { @Override public String apply(Integer key) { return null; } }); try { map.get(1); fail(); } catch (NullPointerException e) { /* expected */ } } public void testRuntimeException() { final RuntimeException e = new RuntimeException(); ConcurrentMap<Object, Object> map = new MapMaker().makeComputingMap( new Function<Object, Object>() { @Override public Object apply(Object from) { throw e; } }); try { map.get(new Object()); fail(); } catch (ComputationException ce) { assertSame(e, ce.getCause()); } } } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/MapMakerTest.java
Java
asf20
5,133
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; /** * Unit tests for {@code TreeMultimap} with natural ordering. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class TreeMultimapNaturalTest extends TestCase { protected SetMultimap<String, Integer> create() { return TreeMultimap.create(); } /** * Create and populate a {@code TreeMultimap} with the natural ordering of * keys and values. */ private TreeMultimap<String, Integer> createPopulate() { TreeMultimap<String, Integer> multimap = TreeMultimap.create(); multimap.put("google", 2); multimap.put("google", 6); multimap.put("foo", 3); multimap.put("foo", 1); multimap.put("foo", 7); multimap.put("tree", 4); multimap.put("tree", 0); return multimap; } public void testToString() { SetMultimap<String, Integer> multimap = create(); multimap.putAll("bar", Arrays.asList(3, 1, 2)); multimap.putAll("foo", Arrays.asList(2, 3, 1, -1, 4)); assertEquals("{bar=[1, 2, 3], foo=[-1, 1, 2, 3, 4]}", multimap.toString()); } public void testOrderedGet() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.get("foo")).has().exactly(1, 3, 7).inOrder(); ASSERT.that(multimap.get("google")).has().exactly(2, 6).inOrder(); ASSERT.that(multimap.get("tree")).has().exactly(0, 4).inOrder(); } public void testOrderedKeySet() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.keySet()).has().exactly("foo", "google", "tree").inOrder(); } public void testOrderedAsMapEntries() { TreeMultimap<String, Integer> multimap = createPopulate(); Iterator<Map.Entry<String, Collection<Integer>>> iterator = multimap.asMap().entrySet().iterator(); Map.Entry<String, Collection<Integer>> entry = iterator.next(); assertEquals("foo", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(1, 3, 7); entry = iterator.next(); assertEquals("google", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(2, 6); entry = iterator.next(); assertEquals("tree", entry.getKey()); ASSERT.that(entry.getValue()).has().exactly(0, 4); } public void testOrderedEntries() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.entries()).has().exactly( Maps.immutableEntry("foo", 1), Maps.immutableEntry("foo", 3), Maps.immutableEntry("foo", 7), Maps.immutableEntry("google", 2), Maps.immutableEntry("google", 6), Maps.immutableEntry("tree", 0), Maps.immutableEntry("tree", 4)).inOrder(); } public void testOrderedValues() { TreeMultimap<String, Integer> multimap = createPopulate(); ASSERT.that(multimap.values()).has().exactly( 1, 3, 7, 2, 6, 0, 4).inOrder(); } public void testMultimapConstructor() { SetMultimap<String, Integer> multimap = create(); multimap.putAll("bar", Arrays.asList(3, 1, 2)); multimap.putAll("foo", Arrays.asList(2, 3, 1, -1, 4)); TreeMultimap<String, Integer> copy = TreeMultimap.create(multimap); assertEquals(multimap, copy); } private static final Comparator<Double> KEY_COMPARATOR = Ordering.natural(); private static final Comparator<Double> VALUE_COMPARATOR = Ordering.natural().reverse().nullsFirst(); /** * Test that creating one TreeMultimap from another does not copy the * comparators from the source TreeMultimap. */ public void testCreateFromTreeMultimap() { Multimap<Double, Double> tree = TreeMultimap.create(KEY_COMPARATOR, VALUE_COMPARATOR); tree.put(1.0, 2.0); tree.put(2.0, 3.0); tree.put(3.0, 4.0); tree.put(4.0, 5.0); TreeMultimap<Double, Double> copyFromTree = TreeMultimap.create(tree); assertEquals(tree, copyFromTree); assertSame(Ordering.natural(), copyFromTree.keyComparator()); assertSame(Ordering.natural(), copyFromTree.valueComparator()); assertSame(Ordering.natural(), copyFromTree.get(1.0).comparator()); } /** * Test that creating one TreeMultimap from a non-TreeMultimap * results in natural ordering. */ public void testCreateFromHashMultimap() { Multimap<Double, Double> hash = HashMultimap.create(); hash.put(1.0, 2.0); hash.put(2.0, 3.0); hash.put(3.0, 4.0); hash.put(4.0, 5.0); TreeMultimap<Double, Double> copyFromHash = TreeMultimap.create(hash); assertEquals(hash, copyFromHash); assertEquals(Ordering.natural(), copyFromHash.keyComparator()); assertEquals(Ordering.natural(), copyFromHash.valueComparator()); } /** * Test that creating one TreeMultimap from a SortedSetMultimap uses natural * ordering. */ public void testCreateFromSortedSetMultimap() { SortedSetMultimap<Double, Double> tree = TreeMultimap.create(KEY_COMPARATOR, VALUE_COMPARATOR); tree.put(1.0, 2.0); tree.put(2.0, 3.0); tree.put(3.0, 4.0); tree.put(4.0, 5.0); SortedSetMultimap<Double, Double> sorted = Multimaps.unmodifiableSortedSetMultimap(tree); TreeMultimap<Double, Double> copyFromSorted = TreeMultimap.create(sorted); assertEquals(tree, copyFromSorted); assertSame(Ordering.natural(), copyFromSorted.keyComparator()); assertSame(Ordering.natural(), copyFromSorted.valueComparator()); assertSame(Ordering.natural(), copyFromSorted.get(1.0).comparator()); } public void testComparators() { TreeMultimap<String, Integer> multimap = TreeMultimap.create(); assertEquals(Ordering.natural(), multimap.keyComparator()); assertEquals(Ordering.natural(), multimap.valueComparator()); } public void testTreeMultimapAsMapSorted() { TreeMultimap<String, Integer> multimap = createPopulate(); SortedMap<String, Collection<Integer>> asMap = multimap.asMap(); assertEquals(Ordering.natural(), asMap.comparator()); assertEquals("foo", asMap.firstKey()); assertEquals("tree", asMap.lastKey()); Set<Integer> fooValues = ImmutableSet.of(1, 3, 7); Set<Integer> googleValues = ImmutableSet.of(2, 6); Set<Integer> treeValues = ImmutableSet.of(4, 0); assertEquals(ImmutableMap.of("google", googleValues, "tree", treeValues), asMap.tailMap("g")); assertEquals(ImmutableMap.of("google", googleValues, "foo", fooValues), asMap.headMap("h")); assertEquals(ImmutableMap.of("google", googleValues), asMap.subMap("g", "h")); } public void testTailSetClear() { TreeMultimap<String, Integer> multimap = TreeMultimap.create(); multimap.put("a", 1); multimap.put("a", 11); multimap.put("b", 2); multimap.put("c", 3); multimap.put("d", 4); multimap.put("e", 5); multimap.put("e", 55); multimap.keySet().tailSet("d").clear(); assertEquals(ImmutableSet.of("a", "b", "c"), multimap.keySet()); assertEquals(4, multimap.size()); assertEquals(4, multimap.values().size()); assertEquals(4, multimap.keys().size()); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/TreeMultimapNaturalTest.java
Java
asf20
7,888
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.Maps.transformEntries; import static com.google.common.collect.Maps.transformValues; import static com.google.common.collect.testing.Helpers.mapEntry; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Converter; import com.google.common.base.Equivalence; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Maps.EntryTransformer; import com.google.common.collect.Maps.ValueDifferenceImpl; import com.google.common.collect.SetsTest.Derived; import com.google.common.testing.EqualsTester; import com.google.common.testing.SerializableTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.concurrent.ConcurrentMap; /** * Unit test for {@code Maps}. * * @author Kevin Bourrillion * @author Mike Bostock * @author Jared Levy */ @GwtCompatible(emulated = true) public class MapsTest extends TestCase { private static final Comparator<Integer> SOME_COMPARATOR = Collections.reverseOrder(); public void testHashMap() { HashMap<Integer, Integer> map = Maps.newHashMap(); assertEquals(Collections.emptyMap(), map); } public void testHashMapWithInitialMap() { Map<String, Integer> original = new TreeMap<String, Integer>(); original.put("a", 1); original.put("b", 2); original.put("c", 3); HashMap<String, Integer> map = Maps.newHashMap(original); assertEquals(original, map); } public void testHashMapGeneralizesTypes() { Map<String, Integer> original = new TreeMap<String, Integer>(); original.put("a", 1); original.put("b", 2); original.put("c", 3); HashMap<Object, Object> map = Maps.newHashMap((Map<? extends Object, ? extends Object>) original); assertEquals(original, map); } public void testCapacityForNegativeSizeFails() { try { Maps.capacity(-1); fail("Negative expected size must result in IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } public void testCapacityForLargeSizes() { int[] largeExpectedSizes = new int[] { Integer.MAX_VALUE / 2 - 1, Integer.MAX_VALUE / 2, Integer.MAX_VALUE / 2 + 1, Integer.MAX_VALUE - 1, Integer.MAX_VALUE}; for (int expectedSize : largeExpectedSizes) { int capacity = Maps.capacity(expectedSize); assertTrue( "capacity (" + capacity + ") must be >= expectedSize (" + expectedSize + ")", capacity >= expectedSize); } } public void testLinkedHashMap() { LinkedHashMap<Integer, Integer> map = Maps.newLinkedHashMap(); assertEquals(Collections.emptyMap(), map); } @SuppressWarnings("serial") public void testLinkedHashMapWithInitialMap() { Map<String, String> map = new LinkedHashMap<String, String>() {{ put("Hello", "World"); put("first", "second"); put("polygene", "lubricants"); put("alpha", "betical"); }}; LinkedHashMap<String, String> copy = Maps.newLinkedHashMap(map); Iterator<Entry<String, String>> iter = copy.entrySet().iterator(); assertTrue(iter.hasNext()); Entry<String, String> entry = iter.next(); assertEquals("Hello", entry.getKey()); assertEquals("World", entry.getValue()); assertTrue(iter.hasNext()); entry = iter.next(); assertEquals("first", entry.getKey()); assertEquals("second", entry.getValue()); assertTrue(iter.hasNext()); entry = iter.next(); assertEquals("polygene", entry.getKey()); assertEquals("lubricants", entry.getValue()); assertTrue(iter.hasNext()); entry = iter.next(); assertEquals("alpha", entry.getKey()); assertEquals("betical", entry.getValue()); assertFalse(iter.hasNext()); } public void testLinkedHashMapGeneralizesTypes() { Map<String, Integer> original = new LinkedHashMap<String, Integer>(); original.put("a", 1); original.put("b", 2); original.put("c", 3); HashMap<Object, Object> map = Maps.<Object, Object>newLinkedHashMap(original); assertEquals(original, map); } public void testIdentityHashMap() { IdentityHashMap<Integer, Integer> map = Maps.newIdentityHashMap(); assertEquals(Collections.emptyMap(), map); } public void testConcurrentMap() { ConcurrentMap<Integer, Integer> map = Maps.newConcurrentMap(); assertEquals(Collections.emptyMap(), map); } public void testTreeMap() { TreeMap<Integer, Integer> map = Maps.newTreeMap(); assertEquals(Collections.emptyMap(), map); assertNull(map.comparator()); } public void testTreeMapDerived() { TreeMap<Derived, Integer> map = Maps.newTreeMap(); assertEquals(Collections.emptyMap(), map); map.put(new Derived("foo"), 1); map.put(new Derived("bar"), 2); ASSERT.that(map.keySet()).has().exactly( new Derived("bar"), new Derived("foo")).inOrder(); ASSERT.that(map.values()).has().exactly(2, 1).inOrder(); assertNull(map.comparator()); } public void testTreeMapNonGeneric() { TreeMap<LegacyComparable, Integer> map = Maps.newTreeMap(); assertEquals(Collections.emptyMap(), map); map.put(new LegacyComparable("foo"), 1); map.put(new LegacyComparable("bar"), 2); ASSERT.that(map.keySet()).has().exactly( new LegacyComparable("bar"), new LegacyComparable("foo")).inOrder(); ASSERT.that(map.values()).has().exactly(2, 1).inOrder(); assertNull(map.comparator()); } public void testTreeMapWithComparator() { TreeMap<Integer, Integer> map = Maps.newTreeMap(SOME_COMPARATOR); assertEquals(Collections.emptyMap(), map); assertSame(SOME_COMPARATOR, map.comparator()); } public void testTreeMapWithInitialMap() { SortedMap<Integer, Integer> map = Maps.newTreeMap(); map.put(5, 10); map.put(3, 20); map.put(1, 30); TreeMap<Integer, Integer> copy = Maps.newTreeMap(map); assertEquals(copy, map); assertSame(copy.comparator(), map.comparator()); } public enum SomeEnum { SOME_INSTANCE } public void testEnumMap() { EnumMap<SomeEnum, Integer> map = Maps.newEnumMap(SomeEnum.class); assertEquals(Collections.emptyMap(), map); map.put(SomeEnum.SOME_INSTANCE, 0); assertEquals(Collections.singletonMap(SomeEnum.SOME_INSTANCE, 0), map); } public void testEnumMapNullClass() { try { Maps.<SomeEnum, Long>newEnumMap((Class<MapsTest.SomeEnum>) null); fail("no exception thrown"); } catch (NullPointerException expected) { } } public void testEnumMapWithInitialEnumMap() { EnumMap<SomeEnum, Integer> original = Maps.newEnumMap(SomeEnum.class); original.put(SomeEnum.SOME_INSTANCE, 0); EnumMap<SomeEnum, Integer> copy = Maps.newEnumMap(original); assertEquals(original, copy); } public void testEnumMapWithInitialEmptyEnumMap() { EnumMap<SomeEnum, Integer> original = Maps.newEnumMap(SomeEnum.class); EnumMap<SomeEnum, Integer> copy = Maps.newEnumMap(original); assertEquals(original, copy); assertNotSame(original, copy); } public void testEnumMapWithInitialMap() { HashMap<SomeEnum, Integer> original = Maps.newHashMap(); original.put(SomeEnum.SOME_INSTANCE, 0); EnumMap<SomeEnum, Integer> copy = Maps.newEnumMap(original); assertEquals(original, copy); } public void testEnumMapWithInitialEmptyMap() { Map<SomeEnum, Integer> original = Maps.newHashMap(); try { Maps.newEnumMap(original); fail("Empty map must result in an IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } public void testToStringImplWithNullKeys() throws Exception { Map<String, String> hashmap = Maps.newHashMap(); hashmap.put("foo", "bar"); hashmap.put(null, "baz"); assertEquals(hashmap.toString(), Maps.toStringImpl(hashmap)); } public void testToStringImplWithNullValues() throws Exception { Map<String, String> hashmap = Maps.newHashMap(); hashmap.put("foo", "bar"); hashmap.put("baz", null); assertEquals(hashmap.toString(), Maps.toStringImpl(hashmap)); } private static final Map<Integer, Integer> EMPTY = Collections.emptyMap(); private static final Map<Integer, Integer> SINGLETON = Collections.singletonMap(1, 2); public void testMapDifferenceEmptyEmpty() { MapDifference<Integer, Integer> diff = Maps.difference(EMPTY, EMPTY); assertTrue(diff.areEqual()); assertEquals(EMPTY, diff.entriesOnlyOnLeft()); assertEquals(EMPTY, diff.entriesOnlyOnRight()); assertEquals(EMPTY, diff.entriesInCommon()); assertEquals(EMPTY, diff.entriesDiffering()); assertEquals("equal", diff.toString()); } public void testMapDifferenceEmptySingleton() { MapDifference<Integer, Integer> diff = Maps.difference(EMPTY, SINGLETON); assertFalse(diff.areEqual()); assertEquals(EMPTY, diff.entriesOnlyOnLeft()); assertEquals(SINGLETON, diff.entriesOnlyOnRight()); assertEquals(EMPTY, diff.entriesInCommon()); assertEquals(EMPTY, diff.entriesDiffering()); assertEquals("not equal: only on right={1=2}", diff.toString()); } public void testMapDifferenceSingletonEmpty() { MapDifference<Integer, Integer> diff = Maps.difference(SINGLETON, EMPTY); assertFalse(diff.areEqual()); assertEquals(SINGLETON, diff.entriesOnlyOnLeft()); assertEquals(EMPTY, diff.entriesOnlyOnRight()); assertEquals(EMPTY, diff.entriesInCommon()); assertEquals(EMPTY, diff.entriesDiffering()); assertEquals("not equal: only on left={1=2}", diff.toString()); } public void testMapDifferenceTypical() { Map<Integer, String> left = ImmutableMap.of( 1, "a", 2, "b", 3, "c", 4, "d", 5, "e"); Map<Integer, String> right = ImmutableMap.of( 1, "a", 3, "f", 5, "g", 6, "z"); MapDifference<Integer, String> diff1 = Maps.difference(left, right); assertFalse(diff1.areEqual()); assertEquals(ImmutableMap.of(2, "b", 4, "d"), diff1.entriesOnlyOnLeft()); assertEquals(ImmutableMap.of(6, "z"), diff1.entriesOnlyOnRight()); assertEquals(ImmutableMap.of(1, "a"), diff1.entriesInCommon()); assertEquals(ImmutableMap.of(3, ValueDifferenceImpl.create("c", "f"), 5, ValueDifferenceImpl.create("e", "g")), diff1.entriesDiffering()); assertEquals("not equal: only on left={2=b, 4=d}: only on right={6=z}: " + "value differences={3=(c, f), 5=(e, g)}", diff1.toString()); MapDifference<Integer, String> diff2 = Maps.difference(right, left); assertFalse(diff2.areEqual()); assertEquals(ImmutableMap.of(6, "z"), diff2.entriesOnlyOnLeft()); assertEquals(ImmutableMap.of(2, "b", 4, "d"), diff2.entriesOnlyOnRight()); assertEquals(ImmutableMap.of(1, "a"), diff2.entriesInCommon()); assertEquals(ImmutableMap.of(3, ValueDifferenceImpl.create("f", "c"), 5, ValueDifferenceImpl.create("g", "e")), diff2.entriesDiffering()); assertEquals("not equal: only on left={6=z}: only on right={2=b, 4=d}: " + "value differences={3=(f, c), 5=(g, e)}", diff2.toString()); } public void testMapDifferenceEquals() { Map<Integer, String> left = ImmutableMap.of( 1, "a", 2, "b", 3, "c", 4, "d", 5, "e"); Map<Integer, String> right = ImmutableMap.of( 1, "a", 3, "f", 5, "g", 6, "z"); Map<Integer, String> right2 = ImmutableMap.of( 1, "a", 3, "h", 5, "g", 6, "z"); MapDifference<Integer, String> original = Maps.difference(left, right); MapDifference<Integer, String> same = Maps.difference(left, right); MapDifference<Integer, String> reverse = Maps.difference(right, left); MapDifference<Integer, String> diff2 = Maps.difference(left, right2); new EqualsTester() .addEqualityGroup(original, same) .addEqualityGroup(reverse) .addEqualityGroup(diff2) .testEquals(); } public void testMapDifferencePredicateTypical() { Map<Integer, String> left = ImmutableMap.of( 1, "a", 2, "b", 3, "c", 4, "d", 5, "e"); Map<Integer, String> right = ImmutableMap.of( 1, "A", 3, "F", 5, "G", 6, "Z"); // TODO(kevinb): replace with Ascii.caseInsensitiveEquivalence() when it // exists Equivalence<String> caseInsensitiveEquivalence = Equivalence.equals().onResultOf( new Function<String, String>() { @Override public String apply(String input) { return input.toLowerCase(); } }); MapDifference<Integer, String> diff1 = Maps.difference(left, right, caseInsensitiveEquivalence); assertFalse(diff1.areEqual()); assertEquals(ImmutableMap.of(2, "b", 4, "d"), diff1.entriesOnlyOnLeft()); assertEquals(ImmutableMap.of(6, "Z"), diff1.entriesOnlyOnRight()); assertEquals(ImmutableMap.of(1, "a"), diff1.entriesInCommon()); assertEquals(ImmutableMap.of(3, ValueDifferenceImpl.create("c", "F"), 5, ValueDifferenceImpl.create("e", "G")), diff1.entriesDiffering()); assertEquals("not equal: only on left={2=b, 4=d}: only on right={6=Z}: " + "value differences={3=(c, F), 5=(e, G)}", diff1.toString()); MapDifference<Integer, String> diff2 = Maps.difference(right, left, caseInsensitiveEquivalence); assertFalse(diff2.areEqual()); assertEquals(ImmutableMap.of(6, "Z"), diff2.entriesOnlyOnLeft()); assertEquals(ImmutableMap.of(2, "b", 4, "d"), diff2.entriesOnlyOnRight()); assertEquals(ImmutableMap.of(1, "A"), diff2.entriesInCommon()); assertEquals(ImmutableMap.of(3, ValueDifferenceImpl.create("F", "c"), 5, ValueDifferenceImpl.create("G", "e")), diff2.entriesDiffering()); assertEquals("not equal: only on left={6=Z}: only on right={2=b, 4=d}: " + "value differences={3=(F, c), 5=(G, e)}", diff2.toString()); } private static final SortedMap<Integer, Integer> SORTED_EMPTY = Maps.newTreeMap(); private static final SortedMap<Integer, Integer> SORTED_SINGLETON = ImmutableSortedMap.of(1, 2); public void testMapDifferenceOfSortedMapIsSorted() { Map<Integer, Integer> map = SORTED_SINGLETON; MapDifference<Integer, Integer> difference = Maps.difference(map, EMPTY); assertTrue(difference instanceof SortedMapDifference); } public void testSortedMapDifferenceEmptyEmpty() { SortedMapDifference<Integer, Integer> diff = Maps.difference(SORTED_EMPTY, SORTED_EMPTY); assertTrue(diff.areEqual()); assertEquals(SORTED_EMPTY, diff.entriesOnlyOnLeft()); assertEquals(SORTED_EMPTY, diff.entriesOnlyOnRight()); assertEquals(SORTED_EMPTY, diff.entriesInCommon()); assertEquals(SORTED_EMPTY, diff.entriesDiffering()); assertEquals("equal", diff.toString()); } public void testSortedMapDifferenceEmptySingleton() { SortedMapDifference<Integer, Integer> diff = Maps.difference(SORTED_EMPTY, SORTED_SINGLETON); assertFalse(diff.areEqual()); assertEquals(SORTED_EMPTY, diff.entriesOnlyOnLeft()); assertEquals(SORTED_SINGLETON, diff.entriesOnlyOnRight()); assertEquals(SORTED_EMPTY, diff.entriesInCommon()); assertEquals(SORTED_EMPTY, diff.entriesDiffering()); assertEquals("not equal: only on right={1=2}", diff.toString()); } public void testSortedMapDifferenceSingletonEmpty() { SortedMapDifference<Integer, Integer> diff = Maps.difference(SORTED_SINGLETON, SORTED_EMPTY); assertFalse(diff.areEqual()); assertEquals(SORTED_SINGLETON, diff.entriesOnlyOnLeft()); assertEquals(SORTED_EMPTY, diff.entriesOnlyOnRight()); assertEquals(SORTED_EMPTY, diff.entriesInCommon()); assertEquals(SORTED_EMPTY, diff.entriesDiffering()); assertEquals("not equal: only on left={1=2}", diff.toString()); } public void testSortedMapDifferenceTypical() { SortedMap<Integer, String> left = ImmutableSortedMap.<Integer, String>reverseOrder() .put(1, "a").put(2, "b").put(3, "c").put(4, "d").put(5, "e") .build(); SortedMap<Integer, String> right = ImmutableSortedMap.of(1, "a", 3, "f", 5, "g", 6, "z"); SortedMapDifference<Integer, String> diff1 = Maps.difference(left, right); assertFalse(diff1.areEqual()); ASSERT.that(diff1.entriesOnlyOnLeft().entrySet()).has().exactly( Maps.immutableEntry(4, "d"), Maps.immutableEntry(2, "b")).inOrder(); ASSERT.that(diff1.entriesOnlyOnRight().entrySet()).has().item( Maps.immutableEntry(6, "z")); ASSERT.that(diff1.entriesInCommon().entrySet()).has().item( Maps.immutableEntry(1, "a")); ASSERT.that(diff1.entriesDiffering().entrySet()).has().exactly( Maps.immutableEntry(5, ValueDifferenceImpl.create("e", "g")), Maps.immutableEntry(3, ValueDifferenceImpl.create("c", "f"))).inOrder(); assertEquals("not equal: only on left={4=d, 2=b}: only on right={6=z}: " + "value differences={5=(e, g), 3=(c, f)}", diff1.toString()); SortedMapDifference<Integer, String> diff2 = Maps.difference(right, left); assertFalse(diff2.areEqual()); ASSERT.that(diff2.entriesOnlyOnLeft().entrySet()).has().item( Maps.immutableEntry(6, "z")); ASSERT.that(diff2.entriesOnlyOnRight().entrySet()).has().exactly( Maps.immutableEntry(2, "b"), Maps.immutableEntry(4, "d")).inOrder(); ASSERT.that(diff1.entriesInCommon().entrySet()).has().item( Maps.immutableEntry(1, "a")); assertEquals(ImmutableMap.of( 3, ValueDifferenceImpl.create("f", "c"), 5, ValueDifferenceImpl.create("g", "e")), diff2.entriesDiffering()); assertEquals("not equal: only on left={6=z}: only on right={2=b, 4=d}: " + "value differences={3=(f, c), 5=(g, e)}", diff2.toString()); } public void testSortedMapDifferenceImmutable() { SortedMap<Integer, String> left = Maps.newTreeMap( ImmutableSortedMap.of(1, "a", 2, "b", 3, "c", 4, "d", 5, "e")); SortedMap<Integer, String> right = Maps.newTreeMap(ImmutableSortedMap.of(1, "a", 3, "f", 5, "g", 6, "z")); SortedMapDifference<Integer, String> diff1 = Maps.difference(left, right); left.put(6, "z"); assertFalse(diff1.areEqual()); ASSERT.that(diff1.entriesOnlyOnLeft().entrySet()).has().exactly( Maps.immutableEntry(2, "b"), Maps.immutableEntry(4, "d")).inOrder(); ASSERT.that(diff1.entriesOnlyOnRight().entrySet()).has().item( Maps.immutableEntry(6, "z")); ASSERT.that(diff1.entriesInCommon().entrySet()).has().item( Maps.immutableEntry(1, "a")); ASSERT.that(diff1.entriesDiffering().entrySet()).has().exactly( Maps.immutableEntry(3, ValueDifferenceImpl.create("c", "f")), Maps.immutableEntry(5, ValueDifferenceImpl.create("e", "g"))).inOrder(); try { diff1.entriesInCommon().put(7, "x"); fail(); } catch (UnsupportedOperationException expected) { } try { diff1.entriesOnlyOnLeft().put(7, "x"); fail(); } catch (UnsupportedOperationException expected) { } try { diff1.entriesOnlyOnRight().put(7, "x"); fail(); } catch (UnsupportedOperationException expected) { } } public void testSortedMapDifferenceEquals() { SortedMap<Integer, String> left = ImmutableSortedMap.of(1, "a", 2, "b", 3, "c", 4, "d", 5, "e"); SortedMap<Integer, String> right = ImmutableSortedMap.of(1, "a", 3, "f", 5, "g", 6, "z"); SortedMap<Integer, String> right2 = ImmutableSortedMap.of(1, "a", 3, "h", 5, "g", 6, "z"); SortedMapDifference<Integer, String> original = Maps.difference(left, right); SortedMapDifference<Integer, String> same = Maps.difference(left, right); SortedMapDifference<Integer, String> reverse = Maps.difference(right, left); SortedMapDifference<Integer, String> diff2 = Maps.difference(left, right2); new EqualsTester() .addEqualityGroup(original, same) .addEqualityGroup(reverse) .addEqualityGroup(diff2) .testEquals(); } private static final Function<String, Integer> LENGTH_FUNCTION = new Function<String, Integer>() { @Override public Integer apply(String input) { return input.length(); } }; public void testAsMap() { Set<String> strings = ImmutableSet.of("one", "two", "three"); Map<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertEquals(Integer.valueOf(5), map.get("three")); assertNull(map.get("five")); ASSERT.that(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("two", 3), mapEntry("three", 5)).inOrder(); } public void testAsMapReadsThrough() { Set<String> strings = Sets.newLinkedHashSet(); Collections.addAll(strings, "one", "two", "three"); Map<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertNull(map.get("four")); strings.add("four"); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5, "four", 4), map); assertEquals(Integer.valueOf(4), map.get("four")); } public void testAsMapWritesThrough() { Set<String> strings = Sets.newLinkedHashSet(); Collections.addAll(strings, "one", "two", "three"); Map<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertEquals(Integer.valueOf(3), map.remove("two")); ASSERT.that(strings).has().exactly("one", "three").inOrder(); } public void testAsMapEmpty() { Set<String> strings = ImmutableSet.of(); Map<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); ASSERT.that(map.entrySet()).isEmpty(); assertTrue(map.isEmpty()); assertNull(map.get("five")); } private static class NonNavigableSortedSet extends ForwardingSortedSet<String> { private final SortedSet<String> delegate = Sets.newTreeSet(); @Override protected SortedSet<String> delegate() { return delegate; } } public void testAsMapReturnsSortedMapForSortedSetInput() { Set<String> set = new NonNavigableSortedSet(); assertTrue(Maps.asMap(set, Functions.identity()) instanceof SortedMap); } public void testAsMapSorted() { SortedSet<String> strings = new NonNavigableSortedSet(); Collections.addAll(strings, "one", "two", "three"); SortedMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertEquals(Integer.valueOf(5), map.get("three")); assertNull(map.get("five")); ASSERT.that(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("three", 5), mapEntry("two", 3)).inOrder(); ASSERT.that(map.tailMap("onea").entrySet()).has().exactly( mapEntry("three", 5), mapEntry("two", 3)).inOrder(); ASSERT.that(map.subMap("one", "two").entrySet()).has().exactly( mapEntry("one", 3), mapEntry("three", 5)).inOrder(); } public void testAsMapSortedReadsThrough() { SortedSet<String> strings = new NonNavigableSortedSet(); Collections.addAll(strings, "one", "two", "three"); SortedMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertNull(map.comparator()); assertEquals(ImmutableSortedMap.of("one", 3, "two", 3, "three", 5), map); assertNull(map.get("four")); strings.add("four"); assertEquals( ImmutableSortedMap.of("one", 3, "two", 3, "three", 5, "four", 4), map); assertEquals(Integer.valueOf(4), map.get("four")); SortedMap<String, Integer> headMap = map.headMap("two"); assertEquals( ImmutableSortedMap.of("four", 4, "one", 3, "three", 5), headMap); strings.add("five"); strings.remove("one"); assertEquals( ImmutableSortedMap.of("five", 4, "four", 4, "three", 5), headMap); ASSERT.that(map.entrySet()).has().exactly( mapEntry("five", 4), mapEntry("four", 4), mapEntry("three", 5), mapEntry("two", 3)).inOrder(); } public void testAsMapSortedWritesThrough() { SortedSet<String> strings = new NonNavigableSortedSet(); Collections.addAll(strings, "one", "two", "three"); SortedMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertEquals(Integer.valueOf(3), map.remove("two")); ASSERT.that(strings).has().exactly("one", "three").inOrder(); } public void testAsMapSortedSubViewKeySetsDoNotSupportAdd() { SortedMap<String, Integer> map = Maps.asMap( new NonNavigableSortedSet(), LENGTH_FUNCTION); try { map.subMap("a", "z").keySet().add("a"); fail(); } catch (UnsupportedOperationException expected) { } try { map.tailMap("a").keySet().add("a"); fail(); } catch (UnsupportedOperationException expected) { } try { map.headMap("r").keySet().add("a"); fail(); } catch (UnsupportedOperationException expected) { } try { map.headMap("r").tailMap("m").keySet().add("a"); fail(); } catch (UnsupportedOperationException expected) { } } public void testAsMapSortedEmpty() { SortedSet<String> strings = new NonNavigableSortedSet(); SortedMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); ASSERT.that(map.entrySet()).isEmpty(); assertTrue(map.isEmpty()); assertNull(map.get("five")); } public void testToMap() { Iterable<String> strings = ImmutableList.of("one", "two", "three"); ImmutableMap<String, Integer> map = Maps.toMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); ASSERT.that(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("two", 3), mapEntry("three", 5)).inOrder(); } public void testToMapIterator() { Iterator<String> strings = ImmutableList.of("one", "two", "three").iterator(); ImmutableMap<String, Integer> map = Maps.toMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); ASSERT.that(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("two", 3), mapEntry("three", 5)).inOrder(); } public void testToMapWithDuplicateKeys() { Iterable<String> strings = ImmutableList.of("one", "two", "three", "two", "one"); ImmutableMap<String, Integer> map = Maps.toMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); ASSERT.that(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("two", 3), mapEntry("three", 5)).inOrder(); } public void testToMapWithNullKeys() { Iterable<String> strings = Arrays.asList("one", null, "three"); try { Maps.toMap(strings, Functions.constant("foo")); fail(); } catch (NullPointerException expected) { } } public void testToMapWithNullValues() { Iterable<String> strings = ImmutableList.of("one", "two", "three"); try { Maps.toMap(strings, Functions.constant(null)); fail(); } catch (NullPointerException expected) { } } private static final BiMap<Integer, String> INT_TO_STRING_MAP = new ImmutableBiMap.Builder<Integer, String>() .put(1, "one") .put(2, "two") .put(3, "three") .build(); public void testUniqueIndexCollection() { ImmutableMap<Integer, String> outputMap = Maps.uniqueIndex(INT_TO_STRING_MAP.values(), Functions.forMap(INT_TO_STRING_MAP.inverse())); assertEquals(INT_TO_STRING_MAP, outputMap); } public void testUniqueIndexIterable() { ImmutableMap<Integer, String> outputMap = Maps.uniqueIndex(new Iterable<String>() { @Override public Iterator<String> iterator() { return INT_TO_STRING_MAP.values().iterator(); } }, Functions.forMap(INT_TO_STRING_MAP.inverse())); assertEquals(INT_TO_STRING_MAP, outputMap); } public void testUniqueIndexIterator() { ImmutableMap<Integer, String> outputMap = Maps.uniqueIndex(INT_TO_STRING_MAP.values().iterator(), Functions.forMap(INT_TO_STRING_MAP.inverse())); assertEquals(INT_TO_STRING_MAP, outputMap); } /** Can't create the map if more than one value maps to the same key. */ public void testUniqueIndexDuplicates() { try { Maps.uniqueIndex(ImmutableSet.of("one", "uno"), Functions.constant(1)); fail(); } catch (IllegalArgumentException expected) { } } /** Null values are not allowed. */ public void testUniqueIndexNullValue() { List<String> listWithNull = Lists.newArrayList((String) null); try { Maps.uniqueIndex(listWithNull, Functions.constant(1)); fail(); } catch (NullPointerException expected) { } } /** Null keys aren't allowed either. */ public void testUniqueIndexNullKey() { List<String> oneStringList = Lists.newArrayList("foo"); try { Maps.uniqueIndex(oneStringList, Functions.constant(null)); fail(); } catch (NullPointerException expected) { } } /** * Constructs a "nefarious" map entry with the specified key and value, * meaning an entry that is suitable for testing that map entries cannot be * modified via a nefarious implementation of equals. This is used for testing * unmodifiable collections of map entries; for example, it should not be * possible to access the raw (modifiable) map entry via a nefarious equals * method. */ public static <K, V> Map.Entry<K, V> nefariousEntry( final K key, final V value) { return new AbstractMapEntry<K, V>() { @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(V value) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (o instanceof Map.Entry) { Map.Entry<K, V> e = (Map.Entry<K, V>) o; e.setValue(value); // muhahaha! } return super.equals(o); } }; } public void testAsConverter_nominal() throws Exception { ImmutableBiMap<String, Integer> biMap = ImmutableBiMap.of( "one", 1, "two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); for (Entry<String, Integer> entry : biMap.entrySet()) { assertSame(entry.getValue(), converter.convert(entry.getKey())); } } public void testAsConverter_inverse() throws Exception { ImmutableBiMap<String, Integer> biMap = ImmutableBiMap.of( "one", 1, "two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); for (Entry<String, Integer> entry : biMap.entrySet()) { assertSame(entry.getKey(), converter.reverse().convert(entry.getValue())); } } public void testAsConverter_noMapping() throws Exception { ImmutableBiMap<String, Integer> biMap = ImmutableBiMap.of( "one", 1, "two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); try { converter.convert("three"); fail(); } catch (IllegalArgumentException expected) { } } public void testAsConverter_nullConversions() throws Exception { ImmutableBiMap<String, Integer> biMap = ImmutableBiMap.of( "one", 1, "two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); assertNull(converter.convert(null)); assertNull(converter.reverse().convert(null)); } public void testAsConverter_isAView() throws Exception { BiMap<String, Integer> biMap = HashBiMap.create(); biMap.put("one", 1); biMap.put("two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); assertSame(1, converter.convert("one")); assertSame(2, converter.convert("two")); try { converter.convert("three"); fail(); } catch (IllegalArgumentException expected) { } biMap.put("three", 3); assertSame(1, converter.convert("one")); assertSame(2, converter.convert("two")); assertSame(3, converter.convert("three")); } public void testAsConverter_withNullMapping() throws Exception { BiMap<String, Integer> biMap = HashBiMap.create(); biMap.put("one", 1); biMap.put("two", 2); biMap.put("three", null); try { Maps.asConverter(biMap).convert("three"); fail(); } catch (IllegalArgumentException expected) { } } public void testAsConverter_toString() { ImmutableBiMap<String, Integer> biMap = ImmutableBiMap.of( "one", 1, "two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); assertEquals("Maps.asConverter({one=1, two=2})", converter.toString()); } public void testAsConverter_serialization() { ImmutableBiMap<String, Integer> biMap = ImmutableBiMap.of( "one", 1, "two", 2); Converter<String, Integer> converter = Maps.asConverter(biMap); SerializableTester.reserializeAndAssert(converter); } public void testUnmodifiableBiMap() { BiMap<Integer, String> mod = HashBiMap.create(); mod.put(1, "one"); mod.put(2, "two"); mod.put(3, "three"); BiMap<Number, String> unmod = Maps.<Number, String>unmodifiableBiMap(mod); /* No aliasing on inverse operations. */ assertSame(unmod.inverse(), unmod.inverse()); assertSame(unmod, unmod.inverse().inverse()); /* Unmodifiable is a view. */ mod.put(4, "four"); assertEquals(true, unmod.get(4).equals("four")); assertEquals(true, unmod.inverse().get("four").equals(4)); /* UnsupportedOperationException on direct modifications. */ try { unmod.put(4, "four"); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { unmod.forcePut(4, "four"); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { unmod.putAll(Collections.singletonMap(4, "four")); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} /* UnsupportedOperationException on indirect modifications. */ BiMap<String, Number> inverse = unmod.inverse(); try { inverse.put("four", 4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { inverse.forcePut("four", 4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { inverse.putAll(Collections.singletonMap("four", 4)); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} Set<String> values = unmod.values(); try { values.remove("four"); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} Set<Map.Entry<Number, String>> entries = unmod.entrySet(); Map.Entry<Number, String> entry = entries.iterator().next(); try { entry.setValue("four"); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} @SuppressWarnings("unchecked") Map.Entry<Integer, String> entry2 = (Map.Entry<Integer, String>) entries.toArray()[0]; try { entry2.setValue("four"); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} } public void testImmutableEntry() { Map.Entry<String, Integer> e = Maps.immutableEntry("foo", 1); assertEquals("foo", e.getKey()); assertEquals(1, (int) e.getValue()); try { e.setValue(2); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} assertEquals("foo=1", e.toString()); assertEquals(101575, e.hashCode()); } public void testImmutableEntryNull() { Map.Entry<String, Integer> e = Maps.immutableEntry((String) null, (Integer) null); assertNull(e.getKey()); assertNull(e.getValue()); try { e.setValue(null); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} assertEquals("null=null", e.toString()); assertEquals(0, e.hashCode()); } /** See {@link SynchronizedBiMapTest} for more tests. */ public void testSynchronizedBiMap() { BiMap<String, Integer> bimap = HashBiMap.create(); bimap.put("one", 1); BiMap<String, Integer> sync = Maps.synchronizedBiMap(bimap); bimap.put("two", 2); sync.put("three", 3); assertEquals(ImmutableSet.of(1, 2, 3), bimap.inverse().keySet()); assertEquals(ImmutableSet.of(1, 2, 3), sync.inverse().keySet()); } private static final Predicate<String> NOT_LENGTH_3 = new Predicate<String>() { @Override public boolean apply(String input) { return input == null || input.length() != 3; } }; private static final Predicate<Integer> EVEN = new Predicate<Integer>() { @Override public boolean apply(Integer input) { return input == null || input % 2 == 0; } }; private static final Predicate<Entry<String, Integer>> CORRECT_LENGTH = new Predicate<Entry<String, Integer>>() { @Override public boolean apply(Entry<String, Integer> input) { return input.getKey().length() == input.getValue(); } }; private static final Function<Integer, Double> SQRT_FUNCTION = new Function<Integer, Double>() { @Override public Double apply(Integer in) { return Math.sqrt(in); } }; public static class FilteredMapTest extends TestCase { Map<String, Integer> createUnfiltered() { return Maps.newHashMap(); } public void testFilteredKeysIllegalPut() { Map<String, Integer> unfiltered = createUnfiltered(); Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3); filtered.put("a", 1); filtered.put("b", 2); assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered); try { filtered.put("yyy", 3); fail(); } catch (IllegalArgumentException expected) {} } public void testFilteredKeysIllegalPutAll() { Map<String, Integer> unfiltered = createUnfiltered(); Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3); filtered.put("a", 1); filtered.put("b", 2); assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered); try { filtered.putAll(ImmutableMap.of("c", 3, "zzz", 4, "b", 5)); fail(); } catch (IllegalArgumentException expected) {} assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered); } public void testFilteredKeysFilteredReflectsBackingChanges() { Map<String, Integer> unfiltered = createUnfiltered(); Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3); unfiltered.put("two", 2); unfiltered.put("three", 3); unfiltered.put("four", 4); assertEquals(ImmutableMap.of("two", 2, "three", 3, "four", 4), unfiltered); assertEquals(ImmutableMap.of("three", 3, "four", 4), filtered); unfiltered.remove("three"); assertEquals(ImmutableMap.of("two", 2, "four", 4), unfiltered); assertEquals(ImmutableMap.of("four", 4), filtered); unfiltered.clear(); assertEquals(ImmutableMap.of(), unfiltered); assertEquals(ImmutableMap.of(), filtered); } public void testFilteredValuesIllegalPut() { Map<String, Integer> unfiltered = createUnfiltered(); Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN); filtered.put("a", 2); unfiltered.put("b", 4); unfiltered.put("c", 5); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); try { filtered.put("yyy", 3); fail(); } catch (IllegalArgumentException expected) {} assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); } public void testFilteredValuesIllegalPutAll() { Map<String, Integer> unfiltered = createUnfiltered(); Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN); filtered.put("a", 2); unfiltered.put("b", 4); unfiltered.put("c", 5); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); try { filtered.putAll(ImmutableMap.of("c", 4, "zzz", 5, "b", 6)); fail(); } catch (IllegalArgumentException expected) {} assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); } public void testFilteredValuesIllegalSetValue() { Map<String, Integer> unfiltered = createUnfiltered(); Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN); filtered.put("a", 2); filtered.put("b", 4); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); Entry<String, Integer> entry = filtered.entrySet().iterator().next(); try { entry.setValue(5); fail(); } catch (IllegalArgumentException expected) {} assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); } public void testFilteredValuesClear() { Map<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("one", 1); unfiltered.put("two", 2); unfiltered.put("three", 3); unfiltered.put("four", 4); Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN); assertEquals(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4), unfiltered); assertEquals(ImmutableMap.of("two", 2, "four", 4), filtered); filtered.clear(); assertEquals(ImmutableMap.of("one", 1, "three", 3), unfiltered); assertTrue(filtered.isEmpty()); } public void testFilteredEntriesIllegalPut() { Map<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("cat", 3); unfiltered.put("dog", 2); unfiltered.put("horse", 5); Map<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH); assertEquals(ImmutableMap.of("cat", 3, "horse", 5), filtered); filtered.put("chicken", 7); assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); try { filtered.put("cow", 7); fail(); } catch (IllegalArgumentException expected) {} assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); } public void testFilteredEntriesIllegalPutAll() { Map<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("cat", 3); unfiltered.put("dog", 2); unfiltered.put("horse", 5); Map<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH); assertEquals(ImmutableMap.of("cat", 3, "horse", 5), filtered); filtered.put("chicken", 7); assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); try { filtered.putAll(ImmutableMap.of("sheep", 5, "cow", 7)); fail(); } catch (IllegalArgumentException expected) {} assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); } public void testFilteredEntriesObjectPredicate() { Map<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("cat", 3); unfiltered.put("dog", 2); unfiltered.put("horse", 5); Predicate<Object> predicate = Predicates.alwaysFalse(); Map<String, Integer> filtered = Maps.filterEntries(unfiltered, predicate); assertTrue(filtered.isEmpty()); } public void testFilteredEntriesWildCardEntryPredicate() { Map<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("cat", 3); unfiltered.put("dog", 2); unfiltered.put("horse", 5); Predicate<Entry<?, ?>> predicate = new Predicate<Entry<?, ?>>() { @Override public boolean apply(Entry<?, ?> input) { return "cat".equals(input.getKey()) || Integer.valueOf(2) == input.getValue(); } }; Map<String, Integer> filtered = Maps.filterEntries(unfiltered, predicate); assertEquals(ImmutableMap.of("cat", 3, "dog", 2), filtered); } } public static class FilteredSortedMapTest extends FilteredMapTest { @Override SortedMap<String, Integer> createUnfiltered() { return Maps.newTreeMap(); } public void testFilterKeysIdentifiesSortedMap() { SortedMap<String, Integer> map = createUnfiltered(); assertTrue(Maps.filterKeys((Map<String, Integer>) map, NOT_LENGTH_3) instanceof SortedMap); } public void testFilterValuesIdentifiesSortedMap() { SortedMap<String, Integer> map = createUnfiltered(); assertTrue(Maps.filterValues((Map<String, Integer>) map, EVEN) instanceof SortedMap); } public void testFilterEntriesIdentifiesSortedMap() { SortedMap<String, Integer> map = createUnfiltered(); assertTrue(Maps.filterEntries((Map<String, Integer>) map, CORRECT_LENGTH) instanceof SortedMap); } public void testFirstAndLastKeyFilteredMap() { SortedMap<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("apple", 2); unfiltered.put("banana", 6); unfiltered.put("cat", 3); unfiltered.put("dog", 5); SortedMap<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH); assertEquals("banana", filtered.firstKey()); assertEquals("cat", filtered.lastKey()); } public void testHeadSubTailMap_FilteredMap() { SortedMap<String, Integer> unfiltered = createUnfiltered(); unfiltered.put("apple", 2); unfiltered.put("banana", 6); unfiltered.put("cat", 4); unfiltered.put("dog", 3); SortedMap<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH); assertEquals(ImmutableMap.of("banana", 6), filtered.headMap("dog")); assertEquals(ImmutableMap.of(), filtered.headMap("banana")); assertEquals(ImmutableMap.of("banana", 6, "dog", 3), filtered.headMap("emu")); assertEquals(ImmutableMap.of("banana", 6), filtered.subMap("banana", "dog")); assertEquals(ImmutableMap.of("dog", 3), filtered.subMap("cat", "emu")); assertEquals(ImmutableMap.of("dog", 3), filtered.tailMap("cat")); assertEquals(ImmutableMap.of("banana", 6, "dog", 3), filtered.tailMap("banana")); } } public static class FilteredBiMapTest extends FilteredMapTest { @Override BiMap<String, Integer> createUnfiltered() { return HashBiMap.create(); } public void testFilterKeysIdentifiesBiMap() { BiMap<String, Integer> map = createUnfiltered(); assertTrue(Maps.filterKeys((Map<String, Integer>) map, NOT_LENGTH_3) instanceof BiMap); } public void testFilterValuesIdentifiesBiMap() { BiMap<String, Integer> map = createUnfiltered(); assertTrue(Maps.filterValues((Map<String, Integer>) map, EVEN) instanceof BiMap); } public void testFilterEntriesIdentifiesBiMap() { BiMap<String, Integer> map = createUnfiltered(); assertTrue(Maps.filterEntries((Map<String, Integer>) map, CORRECT_LENGTH) instanceof BiMap); } } public void testTransformValues() { Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9); Map<String, Double> transformed = transformValues(map, SQRT_FUNCTION); assertEquals(ImmutableMap.of("a", 2.0, "b", 3.0), transformed); } public void testTransformValuesSecretlySorted() { Map<String, Integer> map = sortedNotNavigable(ImmutableSortedMap.of("a", 4, "b", 9)); Map<String, Double> transformed = transformValues(map, SQRT_FUNCTION); assertEquals(ImmutableMap.of("a", 2.0, "b", 3.0), transformed); assertTrue(transformed instanceof SortedMap); } public void testTransformEntries() { Map<String, String> map = ImmutableMap.of("a", "4", "b", "9"); EntryTransformer<String, String, String> concat = new EntryTransformer<String, String, String>() { @Override public String transformEntry(String key, String value) { return key + value; } }; Map<String, String> transformed = transformEntries(map, concat); assertEquals(ImmutableMap.of("a", "a4", "b", "b9"), transformed); } public void testTransformEntriesSecretlySorted() { Map<String, String> map = ImmutableSortedMap.of("a", "4", "b", "9"); EntryTransformer<String, String, String> concat = new EntryTransformer<String, String, String>() { @Override public String transformEntry(String key, String value) { return key + value; } }; Map<String, String> transformed = transformEntries(map, concat); assertEquals(ImmutableMap.of("a", "a4", "b", "b9"), transformed); assertTrue(transformed instanceof SortedMap); } @SuppressWarnings("unused") public void testTransformEntriesGenerics() { Map<Object, Object> map1 = ImmutableMap.<Object, Object>of(1, 2); Map<Object, Number> map2 = ImmutableMap.<Object, Number>of(1, 2); Map<Object, Integer> map3 = ImmutableMap.<Object, Integer>of(1, 2); Map<Number, Object> map4 = ImmutableMap.<Number, Object>of(1, 2); Map<Number, Number> map5 = ImmutableMap.<Number, Number>of(1, 2); Map<Number, Integer> map6 = ImmutableMap.<Number, Integer>of(1, 2); Map<Integer, Object> map7 = ImmutableMap.<Integer, Object>of(1, 2); Map<Integer, Number> map8 = ImmutableMap.<Integer, Number>of(1, 2); Map<Integer, Integer> map9 = ImmutableMap.<Integer, Integer>of(1, 2); Map<? extends Number, ? extends Number> map0 = ImmutableMap.of(1, 2); EntryTransformer<Number, Number, Double> transformer = new EntryTransformer<Number, Number, Double>() { @Override public Double transformEntry(Number key, Number value) { return key.doubleValue() + value.doubleValue(); } }; Map<Object, Double> objectKeyed; Map<Number, Double> numberKeyed; Map<Integer, Double> integerKeyed; numberKeyed = transformEntries(map5, transformer); numberKeyed = transformEntries(map6, transformer); integerKeyed = transformEntries(map8, transformer); integerKeyed = transformEntries(map9, transformer); Map<? extends Number, Double> wildcarded = transformEntries(map0, transformer); // Can't loosen the key type: // objectKeyed = transformEntries(map5, transformer); // objectKeyed = transformEntries(map6, transformer); // objectKeyed = transformEntries(map8, transformer); // objectKeyed = transformEntries(map9, transformer); // numberKeyed = transformEntries(map8, transformer); // numberKeyed = transformEntries(map9, transformer); // Can't loosen the value type: // Map<Number, Number> looseValued1 = transformEntries(map5, transformer); // Map<Number, Number> looseValued2 = transformEntries(map6, transformer); // Map<Integer, Number> looseValued3 = transformEntries(map8, transformer); // Map<Integer, Number> looseValued4 = transformEntries(map9, transformer); // Can't call with too loose a key: // transformEntries(map1, transformer); // transformEntries(map2, transformer); // transformEntries(map3, transformer); // Can't call with too loose a value: // transformEntries(map1, transformer); // transformEntries(map4, transformer); // transformEntries(map7, transformer); } public void testTransformEntriesExample() { Map<String, Boolean> options = ImmutableMap.of("verbose", true, "sort", false); EntryTransformer<String, Boolean, String> flagPrefixer = new EntryTransformer<String, Boolean, String>() { @Override public String transformEntry(String key, Boolean value) { return value ? key : "no" + key; } }; Map<String, String> transformed = transformEntries(options, flagPrefixer); assertEquals("{verbose=verbose, sort=nosort}", transformed.toString()); } // Logically this would accept a NavigableMap, but that won't work under GWT. private static <K, V> SortedMap<K, V> sortedNotNavigable( final SortedMap<K, V> map) { return new ForwardingSortedMap<K, V>() { @Override protected SortedMap<K, V> delegate() { return map; } }; } public void testSortedMapTransformValues() { SortedMap<String, Integer> map = sortedNotNavigable(ImmutableSortedMap.of("a", 4, "b", 9)); SortedMap<String, Double> transformed = transformValues(map, SQRT_FUNCTION); /* * We'd like to sanity check that we didn't get a NavigableMap out, but we * can't easily do so while maintaining GWT compatibility. */ assertEquals(ImmutableSortedMap.of("a", 2.0, "b", 3.0), transformed); } public void testSortedMapTransformEntries() { SortedMap<String, String> map = sortedNotNavigable(ImmutableSortedMap.of("a", "4", "b", "9")); EntryTransformer<String, String, String> concat = new EntryTransformer<String, String, String>() { @Override public String transformEntry(String key, String value) { return key + value; } }; SortedMap<String, String> transformed = transformEntries(map, concat); /* * We'd like to sanity check that we didn't get a NavigableMap out, but we * can't easily do so while maintaining GWT compatibility. */ assertEquals(ImmutableSortedMap.of("a", "a4", "b", "b9"), transformed); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/MapsTest.java
Java
asf20
55,154
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.collect.Table.Cell; import com.google.common.collect.testing.MapInterfaceTest; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.TestSetGenerator; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.Feature; import junit.framework.TestCase; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; /** * Collection tests for {@link Table} implementations. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class TableCollectionTest extends TestCase { private static final Feature<?>[] COLLECTION_FEATURES = { CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_QUERIES }; private static final Feature<?>[] COLLECTION_FEATURES_ORDER = { CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, CollectionFeature.ALLOWS_NULL_QUERIES }; private static final Feature<?>[] COLLECTION_FEATURES_REMOVE = { CollectionSize.ANY, CollectionFeature.SUPPORTS_REMOVE, CollectionFeature.ALLOWS_NULL_QUERIES }; private static final Feature<?>[] COLLECTION_FEATURES_REMOVE_ORDER = { CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, CollectionFeature.SUPPORTS_REMOVE, CollectionFeature.ALLOWS_NULL_QUERIES }; private static void populateForRowKeySet( Table<String, Integer, Character> table, String[] elements) { for (String row : elements) { table.put(row, 1, 'a'); table.put(row, 2, 'b'); } } private static void populateForColumnKeySet( Table<Integer, String, Character> table, String[] elements) { for (String column : elements) { table.put(1, column, 'a'); table.put(2, column, 'b'); } } private static void populateForValues( Table<Integer, Character, String> table, String[] elements) { for (int i = 0; i < elements.length; i++) { table.put(i, 'a', elements[i]); } } private static abstract class TestCellSetGenerator implements TestSetGenerator<Cell<String, Integer, Character>> { @Override public SampleElements<Cell<String, Integer, Character>> samples() { return new SampleElements<Cell<String, Integer, Character>>( Tables.immutableCell("bar", 1, 'a'), Tables.immutableCell("bar", 2, 'b'), Tables.immutableCell("foo", 3, 'c'), Tables.immutableCell("bar", 1, 'b'), Tables.immutableCell("cat", 2, 'b')); } @Override public Set<Cell<String, Integer, Character>> create( Object... elements) { Table<String, Integer, Character> table = createTable(); for (Object element : elements) { @SuppressWarnings("unchecked") Cell<String, Integer, Character> cell = (Cell<String, Integer, Character>) element; table.put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); } return table.cellSet(); } abstract Table<String, Integer, Character> createTable(); @Override @SuppressWarnings("unchecked") public Cell<String, Integer, Character>[] createArray(int length) { return (Cell<String, Integer, Character>[]) new Cell<?, ?, ?>[length]; } @Override public List<Cell<String, Integer, Character>> order( List<Cell<String, Integer, Character>> insertionOrder) { return insertionOrder; } } private static abstract class MapTests extends MapInterfaceTest<String, Integer> { MapTests(boolean allowsNullValues, boolean supportsPut, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { super(false, allowsNullValues, supportsPut, supportsRemove, supportsClear, supportsIteratorRemove); } @Override protected String getKeyNotInPopulatedMap() { return "four"; } @Override protected Integer getValueNotInPopulatedMap() { return 4; } } private static abstract class RowTests extends MapTests { RowTests(boolean allowsNullValues, boolean supportsPut, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { super(allowsNullValues, supportsPut, supportsRemove, supportsClear, supportsIteratorRemove); } abstract Table<Character, String, Integer> makeTable(); @Override protected Map<String, Integer> makeEmptyMap() { return makeTable().row('a'); } @Override protected Map<String, Integer> makePopulatedMap() { Table<Character, String, Integer> table = makeTable(); table.put('a', "one", 1); table.put('a', "two", 2); table.put('a', "three", 3); table.put('b', "four", 4); return table.row('a'); } } public static class HashRowTests extends RowTests { public HashRowTests() { super(false, true, true, true, true); } @Override Table<Character, String, Integer> makeTable() { return HashBasedTable.create(); } } public static class TreeRowTests extends RowTests { public TreeRowTests() { super(false, true, true, true, true); } @Override Table<Character, String, Integer> makeTable() { return TreeBasedTable.create(); } } public static class TransposeRowTests extends RowTests { public TransposeRowTests() { super(false, true, true, true, false); } @Override Table<Character, String, Integer> makeTable() { Table<String, Character, Integer> original = TreeBasedTable.create(); return Tables.transpose(original); } } private static final Function<Integer, Integer> DIVIDE_BY_2 = new Function<Integer, Integer>() { @Override public Integer apply(Integer input) { return (input == null) ? null : input / 2; } }; public static class TransformValueRowTests extends RowTests { public TransformValueRowTests() { super(false, false, true, true, true); } @Override Table<Character, String, Integer> makeTable() { Table<Character, String, Integer> table = HashBasedTable.create(); return Tables.transformValues(table, DIVIDE_BY_2); } @Override protected Map<String, Integer> makePopulatedMap() { Table<Character, String, Integer> table = HashBasedTable.create(); table.put('a', "one", 2); table.put('a', "two", 4); table.put('a', "three", 6); table.put('b', "four", 8); return Tables.transformValues(table, DIVIDE_BY_2).row('a'); } } public static class UnmodifiableHashRowTests extends RowTests { public UnmodifiableHashRowTests() { super(false, false, false, false, false); } @Override Table<Character, String, Integer> makeTable() { Table<Character, String, Integer> table = HashBasedTable.create(); return Tables.unmodifiableTable(table); } @Override protected Map<String, Integer> makePopulatedMap() { Table<Character, String, Integer> table = HashBasedTable.create(); table.put('a', "one", 1); table.put('a', "two", 2); table.put('a', "three", 3); table.put('b', "four", 4); return Tables.unmodifiableTable(table).row('a'); } } public static class UnmodifiableTreeRowTests extends RowTests { public UnmodifiableTreeRowTests() { super(false, false, false, false, false); } @Override Table<Character, String, Integer> makeTable() { RowSortedTable<Character, String, Integer> table = TreeBasedTable.create(); return Tables.unmodifiableRowSortedTable(table); } @Override protected Map<String, Integer> makePopulatedMap() { RowSortedTable<Character, String, Integer> table = TreeBasedTable.create(); table.put('a', "one", 1); table.put('a', "two", 2); table.put('a', "three", 3); table.put('b', "four", 4); return Tables.unmodifiableRowSortedTable(table).row('a'); } } private static abstract class ColumnTests extends MapTests { ColumnTests(boolean allowsNullValues, boolean supportsPut, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { super(allowsNullValues, supportsPut, supportsRemove, supportsClear, supportsIteratorRemove); } abstract Table<String, Character, Integer> makeTable(); @Override protected Map<String, Integer> makeEmptyMap() { return makeTable().column('a'); } @Override protected Map<String, Integer> makePopulatedMap() { Table<String, Character, Integer> table = makeTable(); table.put("one", 'a', 1); table.put("two", 'a', 2); table.put("three", 'a', 3); table.put("four", 'b', 4); return table.column('a'); } } public static class HashColumnTests extends ColumnTests { public HashColumnTests() { super(false, true, true, true, false); } @Override Table<String, Character, Integer> makeTable() { return HashBasedTable.create(); } } public static class TreeColumnTests extends ColumnTests { public TreeColumnTests() { super(false, true, true, true, false); } @Override Table<String, Character, Integer> makeTable() { return TreeBasedTable.create(); } } public static class TransposeColumnTests extends ColumnTests { public TransposeColumnTests() { super(false, true, true, true, true); } @Override Table<String, Character, Integer> makeTable() { Table<Character, String, Integer> original = TreeBasedTable.create(); return Tables.transpose(original); } } public static class TransformValueColumnTests extends ColumnTests { public TransformValueColumnTests() { super(false, false, true, true, false); } @Override Table<String, Character, Integer> makeTable() { Table<String, Character, Integer> table = HashBasedTable.create(); return Tables.transformValues(table, DIVIDE_BY_2); } @Override protected Map<String, Integer> makePopulatedMap() { Table<String, Character, Integer> table = HashBasedTable.create(); table.put("one", 'a', 1); table.put("two", 'a', 2); table.put("three", 'a', 3); table.put("four", 'b', 4); return Tables.transformValues(table, DIVIDE_BY_2).column('a'); } } public static class UnmodifiableHashColumnTests extends ColumnTests { public UnmodifiableHashColumnTests() { super(false, false, false, false, false); } @Override Table<String, Character, Integer> makeTable() { Table<String, Character, Integer> table = HashBasedTable.create(); return Tables.unmodifiableTable(table); } @Override protected Map<String, Integer> makePopulatedMap() { Table<String, Character, Integer> table = HashBasedTable.create(); table.put("one", 'a', 1); table.put("two", 'a', 2); table.put("three", 'a', 3); table.put("four", 'b', 4); return Tables.unmodifiableTable(table).column('a'); } } public static class UnmodifiableTreeColumnTests extends ColumnTests { public UnmodifiableTreeColumnTests() { super(false, false, false, false, false); } @Override Table<String, Character, Integer> makeTable() { RowSortedTable<String, Character, Integer> table = TreeBasedTable.create(); return Tables.unmodifiableRowSortedTable(table); } @Override protected Map<String, Integer> makePopulatedMap() { RowSortedTable<String, Character, Integer> table = TreeBasedTable.create(); table.put("one", 'a', 1); table.put("two", 'a', 2); table.put("three", 'a', 3); table.put("four", 'b', 4); return Tables.unmodifiableRowSortedTable(table).column('a'); } } private static abstract class MapMapTests extends MapInterfaceTest<String, Map<Integer, Character>> { MapMapTests(boolean allowsNullValues, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { super(false, allowsNullValues, false, supportsRemove, supportsClear, supportsIteratorRemove); } @Override protected String getKeyNotInPopulatedMap() { return "cat"; } @Override protected Map<Integer, Character> getValueNotInPopulatedMap() { return ImmutableMap.of(); } /** * The version of this test supplied by {@link MapInterfaceTest} fails for * this particular map implementation, because {@code map.get()} returns a * view collection that changes in the course of a call to {@code remove()}. * Thus, the expectation doesn't hold that {@code map.remove(x)} returns the * same value which {@code map.get(x)} did immediately beforehand. */ @Override public void testRemove() { final Map<String, Map<Integer, Character>> map; final String keyToRemove; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } keyToRemove = map.keySet().iterator().next(); if (supportsRemove) { int initialSize = map.size(); map.get(keyToRemove); map.remove(keyToRemove); // This line doesn't hold - see the Javadoc comments above. // assertEquals(expectedValue, oldValue); assertFalse(map.containsKey(keyToRemove)); assertEquals(initialSize - 1, map.size()); } else { try { map.remove(keyToRemove); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // Expected. } } assertInvariants(map); } } private static abstract class RowMapTests extends MapMapTests { RowMapTests(boolean allowsNullValues, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { super(allowsNullValues, supportsRemove, supportsClear, supportsIteratorRemove); } abstract Table<String, Integer, Character> makeTable(); @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { Table<String, Integer, Character> table = makeTable(); populateTable(table); return table.rowMap(); } void populateTable(Table<String, Integer, Character> table) { table.put("foo", 1, 'a'); table.put("bar", 1, 'b'); table.put("foo", 3, 'c'); } @Override protected Map<String, Map<Integer, Character>> makeEmptyMap() { return makeTable().rowMap(); } } public static class HashRowMapTests extends RowMapTests { public HashRowMapTests() { super(false, true, true, true); } @Override Table<String, Integer, Character> makeTable() { return HashBasedTable.create(); } } public static class TreeRowMapTests extends RowMapTests { public TreeRowMapTests() { super(false, true, true, true); } @Override Table<String, Integer, Character> makeTable() { return TreeBasedTable.create(); } } public static class TreeRowMapHeadMapTests extends RowMapTests { public TreeRowMapHeadMapTests() { super(false, true, true, true); } @Override TreeBasedTable<String, Integer, Character> makeTable() { TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create(); table.put("z", 1, 'a'); return table; } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { TreeBasedTable<String, Integer, Character> table = makeTable(); populateTable(table); return table.rowMap().headMap("x"); } @Override protected Map<String, Map<Integer, Character>> makeEmptyMap() { return makeTable().rowMap().headMap("x"); } @Override protected String getKeyNotInPopulatedMap() { return "z"; } } public static class TreeRowMapTailMapTests extends RowMapTests { public TreeRowMapTailMapTests() { super(false, true, true, true); } @Override TreeBasedTable<String, Integer, Character> makeTable() { TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create(); table.put("a", 1, 'a'); return table; } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { TreeBasedTable<String, Integer, Character> table = makeTable(); populateTable(table); return table.rowMap().tailMap("b"); } @Override protected Map<String, Map<Integer, Character>> makeEmptyMap() { return makeTable().rowMap().tailMap("b"); } @Override protected String getKeyNotInPopulatedMap() { return "a"; } } public static class TreeRowMapSubMapTests extends RowMapTests { public TreeRowMapSubMapTests() { super(false, true, true, true); } @Override TreeBasedTable<String, Integer, Character> makeTable() { TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create(); table.put("a", 1, 'a'); table.put("z", 1, 'a'); return table; } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { TreeBasedTable<String, Integer, Character> table = makeTable(); populateTable(table); return table.rowMap().subMap("b", "x"); } @Override protected Map<String, Map<Integer, Character>> makeEmptyMap() { return makeTable().rowMap().subMap("b", "x"); } @Override protected String getKeyNotInPopulatedMap() { return "z"; } } private static final Function<String, Character> FIRST_CHARACTER = new Function<String, Character>() { @Override public Character apply(String input) { return input == null ? null : input.charAt(0); } }; public static class TransformValueRowMapTests extends RowMapTests { public TransformValueRowMapTests() { super(false, true, true, true); } @Override Table<String, Integer, Character> makeTable() { Table<String, Integer, String> original = HashBasedTable.create(); return Tables.transformValues(original, FIRST_CHARACTER); } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { Table<String, Integer, String> table = HashBasedTable.create(); table.put("foo", 1, "apple"); table.put("bar", 1, "banana"); table.put("foo", 3, "cat"); return Tables.transformValues(table, FIRST_CHARACTER).rowMap(); } } public static class UnmodifiableHashRowMapTests extends RowMapTests { public UnmodifiableHashRowMapTests() { super(false, false, false, false); } @Override Table<String, Integer, Character> makeTable() { Table<String, Integer, Character> original = HashBasedTable.create(); return Tables.unmodifiableTable(original); } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { Table<String, Integer, Character> table = HashBasedTable.create(); table.put("foo", 1, 'a'); table.put("bar", 1, 'b'); table.put("foo", 3, 'c'); return Tables.unmodifiableTable(table).rowMap(); } } public static class UnmodifiableTreeRowMapTests extends RowMapTests { public UnmodifiableTreeRowMapTests() { super(false, false, false, false); } @Override RowSortedTable<String, Integer, Character> makeTable() { RowSortedTable<String, Integer, Character> original = TreeBasedTable.create(); return Tables.unmodifiableRowSortedTable(original); } @Override protected SortedMap<String, Map<Integer, Character>> makePopulatedMap() { RowSortedTable<String, Integer, Character> table = TreeBasedTable.create(); table.put("foo", 1, 'a'); table.put("bar", 1, 'b'); table.put("foo", 3, 'c'); return Tables.unmodifiableRowSortedTable(table).rowMap(); } } private static abstract class ColumnMapTests extends MapMapTests { ColumnMapTests(boolean allowsNullValues, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { super(allowsNullValues, supportsRemove, supportsClear, supportsIteratorRemove); } abstract Table<Integer, String, Character> makeTable(); @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { Table<Integer, String, Character> table = makeTable(); table.put(1, "foo", 'a'); table.put(1, "bar", 'b'); table.put(3, "foo", 'c'); return table.columnMap(); } @Override protected Map<String, Map<Integer, Character>> makeEmptyMap() { return makeTable().columnMap(); } } public static class HashColumnMapTests extends ColumnMapTests { public HashColumnMapTests() { super(false, true, true, false); } @Override Table<Integer, String, Character> makeTable() { return HashBasedTable.create(); } } public static class TreeColumnMapTests extends ColumnMapTests { public TreeColumnMapTests() { super(false, true, true, false); } @Override Table<Integer, String, Character> makeTable() { return TreeBasedTable.create(); } } public static class TransformValueColumnMapTests extends ColumnMapTests { public TransformValueColumnMapTests() { super(false, true, true, false); } @Override Table<Integer, String, Character> makeTable() { Table<Integer, String, String> original = HashBasedTable.create(); return Tables.transformValues(original, FIRST_CHARACTER); } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { Table<Integer, String, String> table = HashBasedTable.create(); table.put(1, "foo", "apple"); table.put(1, "bar", "banana"); table.put(3, "foo", "cat"); return Tables.transformValues(table, FIRST_CHARACTER).columnMap(); } } public static class UnmodifiableHashColumnMapTests extends ColumnMapTests { public UnmodifiableHashColumnMapTests() { super(false, false, false, false); } @Override Table<Integer, String, Character> makeTable() { Table<Integer, String, Character> original = HashBasedTable.create(); return Tables.unmodifiableTable(original); } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { Table<Integer, String, Character> table = HashBasedTable.create(); table.put(1, "foo", 'a'); table.put(1, "bar", 'b'); table.put(3, "foo", 'c'); return Tables.unmodifiableTable(table).columnMap(); } } public static class UnmodifiableTreeColumnMapTests extends ColumnMapTests { public UnmodifiableTreeColumnMapTests() { super(false, false, false, false); } @Override Table<Integer, String, Character> makeTable() { RowSortedTable<Integer, String, Character> original = TreeBasedTable.create(); return Tables.unmodifiableRowSortedTable(original); } @Override protected Map<String, Map<Integer, Character>> makePopulatedMap() { RowSortedTable<Integer, String, Character> table = TreeBasedTable.create(); table.put(1, "foo", 'a'); table.put(1, "bar", 'b'); table.put(3, "foo", 'c'); return Tables.unmodifiableRowSortedTable(table).columnMap(); } } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/TableCollectionTest.java
Java
asf20
24,091
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.MapConstraintsTest.TestKeyException; import com.google.common.collect.MapConstraintsTest.TestValueException; import com.google.common.collect.testing.google.TestStringBiMapGenerator; import junit.framework.TestCase; import java.util.Map.Entry; /** * Tests for {@link MapConstraints#constrainedBiMap}. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class ConstrainedBiMapTest extends TestCase { private static final String TEST_KEY = "42"; private static final String TEST_VALUE = "test"; private static final MapConstraint<String, String> TEST_CONSTRAINT = new TestConstraint(); public void testPutWithForbiddenKeyForbiddenValue() { BiMap<String, String> map = MapConstraints.constrainedBiMap( HashBiMap.<String, String> create(), TEST_CONSTRAINT); try { map.put(TEST_KEY, TEST_VALUE); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // success } } public void testPutWithForbiddenKeyAllowedValue() { BiMap<String, String> map = MapConstraints.constrainedBiMap( HashBiMap.<String, String> create(), TEST_CONSTRAINT); try { map.put(TEST_KEY, "allowed"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // success } } public void testPutWithAllowedKeyForbiddenValue() { BiMap<String, String> map = MapConstraints.constrainedBiMap( HashBiMap.<String, String> create(), TEST_CONSTRAINT); try { map.put("allowed", TEST_VALUE); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // success } } public static final class ConstrainedBiMapGenerator extends TestStringBiMapGenerator { @Override protected BiMap<String, String> create(Entry<String, String>[] entries) { BiMap<String, String> bimap = MapConstraints.constrainedBiMap( HashBiMap.<String, String> create(), TEST_CONSTRAINT); for (Entry<String, String> entry : entries) { checkArgument(!bimap.containsKey(entry.getKey())); bimap.put(entry.getKey(), entry.getValue()); } return bimap; } } private static final class TestConstraint implements MapConstraint<String, String> { @Override public void checkKeyValue(String key, String value) { if (TEST_KEY.equals(key)) { throw new TestKeyException(); } if (TEST_VALUE.equals(value)) { throw new TestValueException(); } } private static final long serialVersionUID = 0; } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ConstrainedBiMapTest.java
Java
asf20
3,442
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; /** * Unit tests for {@link HashMultimap}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class HashMultimapTest extends TestCase { /* * The behavior of toString() is tested by TreeMultimap, which shares a * lot of code with HashMultimap and has deterministic iteration order. */ public void testCreate() { HashMultimap<String, Integer> multimap = HashMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("foo", 3); assertEquals(ImmutableSet.of(1, 3), multimap.get("foo")); assertEquals(2, multimap.expectedValuesPerKey); } public void testCreateFromMultimap() { HashMultimap<String, Integer> multimap = HashMultimap.create(); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("foo", 3); HashMultimap<String, Integer> copy = HashMultimap.create(multimap); assertEquals(multimap, copy); assertEquals(2, copy.expectedValuesPerKey); } public void testCreateFromSizes() { HashMultimap<String, Integer> multimap = HashMultimap.create(20, 15); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("foo", 3); assertEquals(ImmutableSet.of(1, 3), multimap.get("foo")); assertEquals(15, multimap.expectedValuesPerKey); } public void testCreateFromIllegalSizes() { try { HashMultimap.create(-20, 15); fail(); } catch (IllegalArgumentException expected) {} try { HashMultimap.create(20, -15); fail(); } catch (IllegalArgumentException expected) {} } public void testEmptyMultimapsEqual() { Multimap<String, Integer> setMultimap = HashMultimap.create(); Multimap<String, Integer> listMultimap = ArrayListMultimap.create(); assertTrue(setMultimap.equals(listMultimap)); assertTrue(listMultimap.equals(setMultimap)); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/HashMultimapTest.java
Java
asf20
2,569
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.testing.Helpers.nefariousMapEntry; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Supplier; import junit.framework.TestCase; import java.io.Serializable; import java.util.AbstractMap; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import java.util.SortedSet; /** * Tests for {@code MapConstraints}. * * @author Mike Bostock * @author Jared Levy */ @GwtCompatible(emulated = true) public class MapConstraintsTest extends TestCase { private static final String TEST_KEY = "test"; private static final Integer TEST_VALUE = 42; static final class TestKeyException extends IllegalArgumentException { private static final long serialVersionUID = 0; } static final class TestValueException extends IllegalArgumentException { private static final long serialVersionUID = 0; } static final MapConstraint<String, Integer> TEST_CONSTRAINT = new TestConstraint(); private static final class TestConstraint implements MapConstraint<String, Integer>, Serializable { @Override public void checkKeyValue(String key, Integer value) { if (TEST_KEY.equals(key)) { throw new TestKeyException(); } if (TEST_VALUE.equals(value)) { throw new TestValueException(); } } private static final long serialVersionUID = 0; } public void testNotNull() { MapConstraint<Object, Object> constraint = MapConstraints.notNull(); constraint.checkKeyValue("foo", 1); assertEquals("Not null", constraint.toString()); try { constraint.checkKeyValue(null, 1); fail("NullPointerException expected"); } catch (NullPointerException expected) {} try { constraint.checkKeyValue("foo", null); fail("NullPointerException expected"); } catch (NullPointerException expected) {} try { constraint.checkKeyValue(null, null); fail("NullPointerException expected"); } catch (NullPointerException expected) {} } public void testConstrainedMapLegal() { Map<String, Integer> map = Maps.newLinkedHashMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap( map, TEST_CONSTRAINT); map.put(TEST_KEY, TEST_VALUE); constrained.put("foo", 1); map.putAll(ImmutableMap.of("bar", 2)); constrained.putAll(ImmutableMap.of("baz", 3)); assertTrue(map.equals(constrained)); assertTrue(constrained.equals(map)); assertEquals(map.entrySet(), constrained.entrySet()); assertEquals(map.keySet(), constrained.keySet()); assertEquals(HashMultiset.create(map.values()), HashMultiset.create(constrained.values())); assertFalse(map.values() instanceof Serializable); assertEquals(map.toString(), constrained.toString()); assertEquals(map.hashCode(), constrained.hashCode()); ASSERT.that(map.entrySet()).has().exactly( Maps.immutableEntry(TEST_KEY, TEST_VALUE), Maps.immutableEntry("foo", 1), Maps.immutableEntry("bar", 2), Maps.immutableEntry("baz", 3)).inOrder(); } public void testConstrainedMapIllegal() { Map<String, Integer> map = Maps.newLinkedHashMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap( map, TEST_CONSTRAINT); try { constrained.put(TEST_KEY, TEST_VALUE); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.put("baz", TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.put(TEST_KEY, 3); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.putAll(ImmutableMap.of("baz", 3, TEST_KEY, 4)); fail("TestKeyException expected"); } catch (TestKeyException expected) {} assertEquals(Collections.emptySet(), map.entrySet()); assertEquals(Collections.emptySet(), constrained.entrySet()); } public void testConstrainedBiMapLegal() { BiMap<String, Integer> map = new AbstractBiMap<String, Integer>( Maps.<String, Integer>newLinkedHashMap(), Maps.<Integer, String>newLinkedHashMap()) {}; BiMap<String, Integer> constrained = MapConstraints.constrainedBiMap( map, TEST_CONSTRAINT); map.put(TEST_KEY, TEST_VALUE); constrained.put("foo", 1); map.putAll(ImmutableMap.of("bar", 2)); constrained.putAll(ImmutableMap.of("baz", 3)); assertTrue(map.equals(constrained)); assertTrue(constrained.equals(map)); assertEquals(map.entrySet(), constrained.entrySet()); assertEquals(map.keySet(), constrained.keySet()); assertEquals(map.values(), constrained.values()); assertEquals(map.toString(), constrained.toString()); assertEquals(map.hashCode(), constrained.hashCode()); ASSERT.that(map.entrySet()).has().exactly( Maps.immutableEntry(TEST_KEY, TEST_VALUE), Maps.immutableEntry("foo", 1), Maps.immutableEntry("bar", 2), Maps.immutableEntry("baz", 3)).inOrder(); } public void testConstrainedBiMapIllegal() { BiMap<String, Integer> map = new AbstractBiMap<String, Integer>( Maps.<String, Integer>newLinkedHashMap(), Maps.<Integer, String>newLinkedHashMap()) {}; BiMap<String, Integer> constrained = MapConstraints.constrainedBiMap( map, TEST_CONSTRAINT); try { constrained.put(TEST_KEY, TEST_VALUE); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.put("baz", TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.put(TEST_KEY, 3); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.putAll(ImmutableMap.of("baz", 3, TEST_KEY, 4)); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.forcePut(TEST_KEY, 3); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.inverse().forcePut(TEST_VALUE, "baz"); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.inverse().forcePut(3, TEST_KEY); fail("TestKeyException expected"); } catch (TestKeyException expected) {} assertEquals(Collections.emptySet(), map.entrySet()); assertEquals(Collections.emptySet(), constrained.entrySet()); } public void testConstrainedMultimapLegal() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap( multimap, TEST_CONSTRAINT); multimap.put(TEST_KEY, TEST_VALUE); constrained.put("foo", 1); multimap.get("bar").add(2); constrained.get("baz").add(3); multimap.get("qux").addAll(Arrays.asList(4)); constrained.get("zig").addAll(Arrays.asList(5)); multimap.putAll("zag", Arrays.asList(6)); constrained.putAll("bee", Arrays.asList(7)); multimap.putAll(new ImmutableMultimap.Builder<String, Integer>() .put("bim", 8).build()); constrained.putAll(new ImmutableMultimap.Builder<String, Integer>() .put("bop", 9).build()); multimap.putAll(new ImmutableMultimap.Builder<String, Integer>() .put("dig", 10).build()); constrained.putAll(new ImmutableMultimap.Builder<String, Integer>() .put("dag", 11).build()); assertTrue(multimap.equals(constrained)); assertTrue(constrained.equals(multimap)); ASSERT.that(ImmutableList.copyOf(multimap.entries())) .is(ImmutableList.copyOf(constrained.entries())); ASSERT.that(constrained.asMap().get("foo")).has().item(1); assertNull(constrained.asMap().get("missing")); assertEquals(multimap.asMap(), constrained.asMap()); assertEquals(multimap.values(), constrained.values()); assertEquals(multimap.keys(), constrained.keys()); assertEquals(multimap.keySet(), constrained.keySet()); assertEquals(multimap.toString(), constrained.toString()); assertEquals(multimap.hashCode(), constrained.hashCode()); ASSERT.that(multimap.entries()).has().exactly( Maps.immutableEntry(TEST_KEY, TEST_VALUE), Maps.immutableEntry("foo", 1), Maps.immutableEntry("bar", 2), Maps.immutableEntry("baz", 3), Maps.immutableEntry("qux", 4), Maps.immutableEntry("zig", 5), Maps.immutableEntry("zag", 6), Maps.immutableEntry("bee", 7), Maps.immutableEntry("bim", 8), Maps.immutableEntry("bop", 9), Maps.immutableEntry("dig", 10), Maps.immutableEntry("dag", 11)).inOrder(); assertFalse(constrained.asMap().values() instanceof Serializable); Iterator<Collection<Integer>> iterator = constrained.asMap().values().iterator(); iterator.next(); iterator.next().add(12); assertTrue(multimap.containsEntry("foo", 12)); } public void testConstrainedTypePreservingList() { ListMultimap<String, Integer> multimap = MapConstraints.constrainedListMultimap( LinkedListMultimap.<String, Integer>create(), TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, Collection<Integer>> entry = multimap.asMap().entrySet().iterator().next(); assertTrue(entry.getValue() instanceof List); assertFalse(multimap.entries() instanceof Set); assertFalse(multimap.get("foo") instanceof RandomAccess); } public void testConstrainedTypePreservingRandomAccessList() { ListMultimap<String, Integer> multimap = MapConstraints.constrainedListMultimap( ArrayListMultimap.<String, Integer>create(), TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, Collection<Integer>> entry = multimap.asMap().entrySet().iterator().next(); assertTrue(entry.getValue() instanceof List); assertFalse(multimap.entries() instanceof Set); assertTrue(multimap.get("foo") instanceof RandomAccess); } public void testConstrainedTypePreservingSet() { SetMultimap<String, Integer> multimap = MapConstraints.constrainedSetMultimap( LinkedHashMultimap.<String, Integer>create(), TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, Collection<Integer>> entry = multimap.asMap().entrySet().iterator().next(); assertTrue(entry.getValue() instanceof Set); } public void testConstrainedTypePreservingSortedSet() { Comparator<Integer> comparator = Collections.reverseOrder(); SortedSetMultimap<String, Integer> delegate = TreeMultimap.create(Ordering.<String>natural(), comparator); SortedSetMultimap<String, Integer> multimap = MapConstraints.constrainedSortedSetMultimap(delegate, TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, Collection<Integer>> entry = multimap.asMap().entrySet().iterator().next(); assertTrue(entry.getValue() instanceof SortedSet); assertSame(comparator, multimap.valueComparator()); assertSame(comparator, multimap.get("foo").comparator()); } @SuppressWarnings("unchecked") public void testConstrainedMultimapIllegal() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap( multimap, TEST_CONSTRAINT); try { constrained.put(TEST_KEY, 1); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.put("foo", TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.put(TEST_KEY, TEST_VALUE); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.get(TEST_KEY).add(1); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.get("foo").add(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.get(TEST_KEY).add(TEST_VALUE); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.get(TEST_KEY).addAll(Arrays.asList(1)); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.get("foo").addAll(Arrays.asList(1, TEST_VALUE)); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.get(TEST_KEY).addAll(Arrays.asList(1, TEST_VALUE)); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.putAll(TEST_KEY, Arrays.asList(1)); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.putAll("foo", Arrays.asList(1, TEST_VALUE)); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.putAll(TEST_KEY, Arrays.asList(1, TEST_VALUE)); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.putAll(new ImmutableMultimap.Builder<String, Integer>() .put(TEST_KEY, 2).put("foo", 1).build()); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.putAll(new ImmutableMultimap.Builder<String, Integer>() .put("bar", TEST_VALUE).put("foo", 1).build()); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.putAll(new ImmutableMultimap.Builder<String, Integer>() .put(TEST_KEY, TEST_VALUE).put("foo", 1).build()); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.entries().add(Maps.immutableEntry(TEST_KEY, 1)); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { constrained.entries().addAll(Arrays.asList( Maps.immutableEntry("foo", 1), Maps.immutableEntry(TEST_KEY, 2))); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} assertTrue(multimap.isEmpty()); assertTrue(constrained.isEmpty()); constrained.put("foo", 1); try { constrained.asMap().get("foo").add(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.asMap().values().iterator().next().add(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { ((Collection<Integer>) constrained.asMap().values().toArray()[0]) .add(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} ASSERT.that(ImmutableList.copyOf(multimap.entries())) .is(ImmutableList.copyOf(constrained.entries())); assertEquals(multimap.asMap(), constrained.asMap()); assertEquals(multimap.values(), constrained.values()); assertEquals(multimap.keys(), constrained.keys()); assertEquals(multimap.keySet(), constrained.keySet()); assertEquals(multimap.toString(), constrained.toString()); assertEquals(multimap.hashCode(), constrained.hashCode()); } private static class QueueSupplier implements Supplier<Queue<Integer>> { @Override public Queue<Integer> get() { return new LinkedList<Integer>(); } } public void testConstrainedMultimapQueue() { Multimap<String, Integer> multimap = Multimaps.newMultimap( new HashMap<String, Collection<Integer>>(), new QueueSupplier()); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap( multimap, TEST_CONSTRAINT); constrained.put("foo", 1); assertTrue(constrained.get("foo").contains(1)); assertTrue(multimap.get("foo").contains(1)); try { constrained.put(TEST_KEY, 1); fail("TestKeyException expected"); } catch (TestKeyException expected) {} try { constrained.put("foo", TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} try { constrained.get("foo").add(TEST_VALUE); fail("TestKeyException expected"); } catch (TestValueException expected) {} try { constrained.get(TEST_KEY).add(1); fail("TestValueException expected"); } catch (TestKeyException expected) {} assertEquals(1, constrained.size()); assertEquals(1, multimap.size()); } public void testMapEntrySetToArray() { Map<String, Integer> map = Maps.newLinkedHashMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap(map, TEST_CONSTRAINT); map.put("foo", 1); @SuppressWarnings("unchecked") Map.Entry<String, Integer> entry = (Map.Entry) constrained.entrySet().toArray()[0]; try { entry.setValue(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} assertFalse(map.containsValue(TEST_VALUE)); } public void testMapEntrySetContainsNefariousEntry() { Map<String, Integer> map = Maps.newTreeMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap(map, TEST_CONSTRAINT); map.put("foo", 1); Map.Entry<String, Integer> nefariousEntry = nefariousMapEntry(TEST_KEY, TEST_VALUE); Set<Map.Entry<String, Integer>> entries = constrained.entrySet(); assertFalse(entries.contains(nefariousEntry)); assertFalse(map.containsValue(TEST_VALUE)); assertFalse(entries.containsAll(Collections.singleton(nefariousEntry))); assertFalse(map.containsValue(TEST_VALUE)); } public void testMultimapAsMapEntriesToArray() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap(multimap, TEST_CONSTRAINT); multimap.put("foo", 1); @SuppressWarnings("unchecked") Map.Entry<String, Collection<Integer>> entry = (Map.Entry<String, Collection<Integer>>) constrained.asMap().entrySet().toArray()[0]; try { entry.setValue(Collections.<Integer>emptySet()); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) {} try { entry.getValue().add(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} assertFalse(multimap.containsValue(TEST_VALUE)); } public void testMultimapAsMapValuesToArray() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap(multimap, TEST_CONSTRAINT); multimap.put("foo", 1); @SuppressWarnings("unchecked") Collection<Integer> collection = (Collection<Integer>) constrained.asMap().values().toArray()[0]; try { collection.add(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} assertFalse(multimap.containsValue(TEST_VALUE)); } public void testMultimapEntriesContainsNefariousEntry() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap(multimap, TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, Integer> nefariousEntry = nefariousMapEntry(TEST_KEY, TEST_VALUE); Collection<Map.Entry<String, Integer>> entries = constrained.entries(); assertFalse(entries.contains(nefariousEntry)); assertFalse(multimap.containsValue(TEST_VALUE)); assertFalse(entries.containsAll(Collections.singleton(nefariousEntry))); assertFalse(multimap.containsValue(TEST_VALUE)); } public void testMultimapEntriesRemoveNefariousEntry() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap(multimap, TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, Integer> nefariousEntry = nefariousMapEntry(TEST_KEY, TEST_VALUE); Collection<Map.Entry<String, Integer>> entries = constrained.entries(); assertFalse(entries.remove(nefariousEntry)); assertFalse(multimap.containsValue(TEST_VALUE)); assertFalse(entries.removeAll(Collections.singleton(nefariousEntry))); assertFalse(multimap.containsValue(TEST_VALUE)); } public void testMultimapAsMapEntriesContainsNefariousEntry() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap(multimap, TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, ? extends Collection<Integer>> nefariousEntry = nefariousMapEntry(TEST_KEY, Collections.singleton(TEST_VALUE)); Set<Map.Entry<String, Collection<Integer>>> entries = constrained.asMap().entrySet(); assertFalse(entries.contains(nefariousEntry)); assertFalse(multimap.containsValue(TEST_VALUE)); assertFalse(entries.containsAll(Collections.singleton(nefariousEntry))); assertFalse(multimap.containsValue(TEST_VALUE)); } public void testMultimapAsMapEntriesRemoveNefariousEntry() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap(multimap, TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, ? extends Collection<Integer>> nefariousEntry = nefariousMapEntry(TEST_KEY, Collections.singleton(TEST_VALUE)); Set<Map.Entry<String, Collection<Integer>>> entries = constrained.asMap().entrySet(); assertFalse(entries.remove(nefariousEntry)); assertFalse(multimap.containsValue(TEST_VALUE)); assertFalse(entries.removeAll(Collections.singleton(nefariousEntry))); assertFalse(multimap.containsValue(TEST_VALUE)); } public void testNefariousMapPutAll() { Map<String, Integer> map = Maps.newLinkedHashMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap( map, TEST_CONSTRAINT); Map<String, Integer> onceIterable = onceIterableMap("foo", 1); constrained.putAll(onceIterable); assertEquals((Integer) 1, constrained.get("foo")); } public void testNefariousMultimapPutAllIterable() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap( multimap, TEST_CONSTRAINT); Collection<Integer> onceIterable = ConstraintsTest.onceIterableCollection(1); constrained.putAll("foo", onceIterable); assertEquals(ImmutableList.of(1), constrained.get("foo")); } public void testNefariousMultimapPutAllMultimap() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap( multimap, TEST_CONSTRAINT); Multimap<String, Integer> onceIterable = Multimaps.forMap(onceIterableMap("foo", 1)); constrained.putAll(onceIterable); assertEquals(ImmutableList.of(1), constrained.get("foo")); } public void testNefariousMultimapGetAddAll() { Multimap<String, Integer> multimap = LinkedListMultimap.create(); Multimap<String, Integer> constrained = MapConstraints.constrainedMultimap( multimap, TEST_CONSTRAINT); Collection<Integer> onceIterable = ConstraintsTest.onceIterableCollection(1); constrained.get("foo").addAll(onceIterable); assertEquals(ImmutableList.of(1), constrained.get("foo")); } /** * Returns a "nefarious" map, which permits only one call to its views' * iterator() methods. This verifies that the constrained map uses a * defensive copy instead of potentially checking the elements in one snapshot * and adding the elements from another. * * @param key the key to be contained in the map * @param value the value to be contained in the map */ static <K, V> Map<K, V> onceIterableMap(K key, V value) { final Map.Entry<K, V> entry = Maps.immutableEntry(key, value); return new AbstractMap<K, V>() { boolean iteratorCalled; @Override public int size() { /* * We could make the map empty, but that seems more likely to trigger * special cases (so maybe we should test both empty and nonempty...). */ return 1; } @Override public Set<Entry<K, V>> entrySet() { return new ForwardingSet<Entry<K, V>>() { @Override protected Set<Entry<K, V>> delegate() { return Collections.singleton(entry); } @Override public Iterator<Entry<K, V>> iterator() { assertFalse("Expected only one call to iterator()", iteratorCalled); iteratorCalled = true; return super.iterator(); } }; } @Override public Set<K> keySet() { throw new UnsupportedOperationException(); } @Override public Collection<V> values() { throw new UnsupportedOperationException(); } }; } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/MapConstraintsTest.java
Java
asf20
26,308
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.collect.Table.Cell; import com.google.common.testing.EqualsTester; import com.google.common.testing.SerializableTester; import java.util.Arrays; import java.util.Map; /** * Test cases for {@link ArrayTable}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class ArrayTableTest extends AbstractTableTest { @Override protected ArrayTable<String, Integer, Character> create( Object... data) { // TODO: Specify different numbers of rows and columns, to detect problems // that arise when the wrong size is used. ArrayTable<String, Integer, Character> table = ArrayTable.create(asList("foo", "bar", "cat"), asList(1, 2, 3)); populate(table, data); return table; } @Override protected void assertSize(int expectedSize) { assertEquals(9, table.size()); } @Override protected boolean supportsRemove() { return false; } @Override protected boolean supportsNullValues() { return true; } // Overriding tests of behavior that differs for ArrayTable. @Override public void testContains() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.contains("foo", 1)); assertTrue(table.contains("bar", 1)); assertTrue(table.contains("foo", 3)); assertTrue(table.contains("foo", 2)); assertTrue(table.contains("bar", 3)); assertTrue(table.contains("cat", 1)); assertFalse(table.contains("foo", -1)); assertFalse(table.contains("bad", 1)); assertFalse(table.contains("bad", -1)); assertFalse(table.contains("foo", null)); assertFalse(table.contains(null, 1)); assertFalse(table.contains(null, null)); } @Override public void testContainsRow() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.containsRow("foo")); assertTrue(table.containsRow("bar")); assertTrue(table.containsRow("cat")); assertFalse(table.containsRow("bad")); assertFalse(table.containsRow(null)); } @Override public void testContainsColumn() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.containsColumn(1)); assertTrue(table.containsColumn(3)); assertTrue(table.containsColumn(2)); assertFalse(table.containsColumn(-1)); assertFalse(table.containsColumn(null)); } @Override public void testContainsValue() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertTrue(table.containsValue('a')); assertTrue(table.containsValue('b')); assertTrue(table.containsValue('c')); assertFalse(table.containsValue('x')); assertTrue(table.containsValue(null)); } @Override public void testIsEmpty() { assertFalse(table.isEmpty()); table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertFalse(table.isEmpty()); } @Override public void testEquals() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Table<String, Integer, Character> hashCopy = HashBasedTable.create(); hashCopy.put("foo", 1, 'a'); hashCopy.put("bar", 1, 'b'); hashCopy.put("foo", 3, 'c'); Table<String, Integer, Character> reordered = create("foo", 3, 'c', "foo", 1, 'a', "bar", 1, 'b'); Table<String, Integer, Character> smaller = create("foo", 1, 'a', "bar", 1, 'b'); Table<String, Integer, Character> swapOuter = create("bar", 1, 'a', "foo", 1, 'b', "bar", 3, 'c'); Table<String, Integer, Character> swapValues = create("foo", 1, 'c', "bar", 1, 'b', "foo", 3, 'a'); new EqualsTester() .addEqualityGroup(table, reordered) .addEqualityGroup(hashCopy) .addEqualityGroup(smaller) .addEqualityGroup(swapOuter) .addEqualityGroup(swapValues) .testEquals(); } @Override public void testHashCode() { table = ArrayTable.create(asList("foo", "bar"), asList(1, 3)); table.put("foo", 1, 'a'); table.put("bar", 1, 'b'); table.put("foo", 3, 'c'); int expected = Objects.hashCode("foo", 1, 'a') + Objects.hashCode("bar", 1, 'b') + Objects.hashCode("foo", 3, 'c') + Objects.hashCode("bar", 3, 0); assertEquals(expected, table.hashCode()); } @Override public void testRow() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<Integer, Character> expected = Maps.newHashMap(); expected.put(1, 'a'); expected.put(3, 'c'); expected.put(2, null); assertEquals(expected, table.row("foo")); } @Override public void testColumn() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<String, Character> expected = Maps.newHashMap(); expected.put("foo", 'a'); expected.put("bar", 'b'); expected.put("cat", null); assertEquals(expected, table.column(1)); } @Override public void testToStringSize1() { table = ArrayTable.create(ImmutableList.of("foo"), ImmutableList.of(1)); table.put("foo", 1, 'a'); assertEquals("{foo={1=a}}", table.toString()); } public void testCreateDuplicateRows() { try { ArrayTable.create(asList("foo", "bar", "foo"), asList(1, 2, 3)); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateDuplicateColumns() { try { ArrayTable.create(asList("foo", "bar"), asList(1, 2, 3, 2)); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateEmptyRows() { try { ArrayTable.create(Arrays.<String>asList(), asList(1, 2, 3)); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateEmptyColumns() { try { ArrayTable.create(asList("foo", "bar"), Arrays.<Integer>asList()); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateCopyArrayTable() { Table<String, Integer, Character> original = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Table<String, Integer, Character> copy = ArrayTable.create(original); assertEquals(original, copy); original.put("foo", 1, 'd'); assertEquals((Character) 'd', original.get("foo", 1)); assertEquals((Character) 'a', copy.get("foo", 1)); assertEquals(copy.rowKeySet(), original.rowKeySet()); assertEquals(copy.columnKeySet(), original.columnKeySet()); } public void testCreateCopyHashBasedTable() { Table<String, Integer, Character> original = HashBasedTable.create(); original.put("foo", 1, 'a'); original.put("bar", 1, 'b'); original.put("foo", 3, 'c'); Table<String, Integer, Character> copy = ArrayTable.create(original); assertEquals(4, copy.size()); assertEquals((Character) 'a', copy.get("foo", 1)); assertEquals((Character) 'b', copy.get("bar", 1)); assertEquals((Character) 'c', copy.get("foo", 3)); assertNull(copy.get("bar", 3)); original.put("foo", 1, 'd'); assertEquals((Character) 'd', original.get("foo", 1)); assertEquals((Character) 'a', copy.get("foo", 1)); assertEquals(copy.rowKeySet(), ImmutableSet.of("foo", "bar")); assertEquals(copy.columnKeySet(), ImmutableSet.of(1, 3)); } public void testCreateCopyEmptyTable() { Table<String, Integer, Character> original = HashBasedTable.create(); try { ArrayTable.create(original); fail(); } catch (IllegalArgumentException expected) {} } public void testSerialization() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); SerializableTester.reserializeAndAssert(table); } public void testToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("{foo={1=a, 2=null, 3=c}, " + "bar={1=b, 2=null, 3=null}, " + "cat={1=null, 2=null, 3=null}}", table.toString()); assertEquals("{foo={1=a, 2=null, 3=c}, " + "bar={1=b, 2=null, 3=null}, " + "cat={1=null, 2=null, 3=null}}", table.rowMap().toString()); } public void testCellSetToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[(foo,1)=a, (foo,2)=null, (foo,3)=c, " + "(bar,1)=b, (bar,2)=null, (bar,3)=null, " + "(cat,1)=null, (cat,2)=null, (cat,3)=null]", table.cellSet().toString()); } public void testRowKeySetToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[foo, bar, cat]", table.rowKeySet().toString()); } public void testColumnKeySetToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[1, 2, 3]", table.columnKeySet().toString()); } public void testValuesToString_ordered() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals("[a, null, c, b, null, null, null, null, null]", table.values().toString()); } public void testRowKeyList() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); ASSERT.that(table.rowKeyList()).has().exactly("foo", "bar", "cat").inOrder(); } public void testColumnKeyList() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); ASSERT.that(table.columnKeyList()).has().exactly(1, 2, 3).inOrder(); } public void testGetMissingKeys() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertNull(table.get("dog", 1)); assertNull(table.get("foo", 4)); } public void testAt() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals((Character) 'b', table.at(1, 0)); assertEquals((Character) 'c', table.at(0, 2)); assertNull(table.at(1, 2)); try { table.at(1, 3); fail(); } catch (IndexOutOfBoundsException expected) {} try { table.at(1, -1); fail(); } catch (IndexOutOfBoundsException expected) {} try { table.at(3, 2); fail(); } catch (IndexOutOfBoundsException expected) {} try { table.at(-1, 2); fail(); } catch (IndexOutOfBoundsException expected) {} } public void testSet() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals((Character) 'b', table.set(1, 0, 'd')); assertEquals((Character) 'd', table.get("bar", 1)); assertNull(table.set(2, 0, 'e')); assertEquals((Character) 'e', table.get("cat", 1)); assertEquals((Character) 'a', table.set(0, 0, null)); assertNull(table.get("foo", 1)); try { table.set(1, 3, 'z'); fail(); } catch (IndexOutOfBoundsException expected) {} try { table.set(1, -1, 'z'); fail(); } catch (IndexOutOfBoundsException expected) {} try { table.set(3, 2, 'z'); fail(); } catch (IndexOutOfBoundsException expected) {} try { table.set(-1, 2, 'z'); fail(); } catch (IndexOutOfBoundsException expected) {} assertFalse(table.containsValue('z')); } public void testEraseAll() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); table.eraseAll(); assertEquals(9, table.size()); assertNull(table.get("bar", 1)); assertTrue(table.containsRow("foo")); assertFalse(table.containsValue('a')); } public void testPutIllegal() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); try { table.put("dog", 1, 'd'); fail(); } catch (IllegalArgumentException expected) { assertEquals("Row dog not in [foo, bar, cat]", expected.getMessage()); } try { table.put("foo", 4, 'd'); fail(); } catch (IllegalArgumentException expected) { assertEquals("Column 4 not in [1, 2, 3]", expected.getMessage()); } assertFalse(table.containsValue('d')); } public void testErase() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertEquals((Character) 'b', table.erase("bar", 1)); assertNull(table.get("bar", 1)); assertEquals(9, table.size()); assertNull(table.erase("bar", 1)); assertNull(table.erase("foo", 2)); assertNull(table.erase("dog", 1)); assertNull(table.erase("bar", 5)); assertNull(table.erase(null, 1)); assertNull(table.erase("bar", null)); } public void testCellReflectsChanges() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Cell<String, Integer, Character> cell = table.cellSet().iterator().next(); assertEquals(Tables.immutableCell("foo", 1, 'a'), cell); assertEquals((Character) 'a', table.put("foo", 1, 'd')); assertEquals(Tables.immutableCell("foo", 1, 'd'), cell); } public void testRowMissing() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<Integer, Character> row = table.row("dog"); assertTrue(row.isEmpty()); try { row.put(1, 'd'); fail(); } catch (UnsupportedOperationException expected) {} } public void testColumnMissing() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<String, Character> column = table.column(4); assertTrue(column.isEmpty()); try { column.put("foo", 'd'); fail(); } catch (UnsupportedOperationException expected) {} } public void testRowPutIllegal() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<Integer, Character> map = table.row("foo"); try { map.put(4, 'd'); fail(); } catch (IllegalArgumentException expected) { assertEquals("Column 4 not in [1, 2, 3]", expected.getMessage()); } } public void testColumnPutIllegal() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<String, Character> map = table.column(3); try { map.put("dog", 'd'); fail(); } catch (IllegalArgumentException expected) { assertEquals("Row dog not in [foo, bar, cat]", expected.getMessage()); } } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ArrayTableTest.java
Java
asf20
14,869
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.google.UnmodifiableCollectionTests; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * Tests for {@link ImmutableMultiset}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class ImmutableMultisetTest extends TestCase { public void testCreation_noArgs() { Multiset<String> multiset = ImmutableMultiset.of(); assertTrue(multiset.isEmpty()); } public void testCreation_oneElement() { Multiset<String> multiset = ImmutableMultiset.of("a"); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCreation_twoElements() { Multiset<String> multiset = ImmutableMultiset.of("a", "b"); assertEquals(HashMultiset.create(asList("a", "b")), multiset); } public void testCreation_threeElements() { Multiset<String> multiset = ImmutableMultiset.of("a", "b", "c"); assertEquals(HashMultiset.create(asList("a", "b", "c")), multiset); } public void testCreation_fourElements() { Multiset<String> multiset = ImmutableMultiset.of("a", "b", "c", "d"); assertEquals(HashMultiset.create(asList("a", "b", "c", "d")), multiset); } public void testCreation_fiveElements() { Multiset<String> multiset = ImmutableMultiset.of("a", "b", "c", "d", "e"); assertEquals(HashMultiset.create(asList("a", "b", "c", "d", "e")), multiset); } public void testCreation_sixElements() { Multiset<String> multiset = ImmutableMultiset.of( "a", "b", "c", "d", "e", "f"); assertEquals(HashMultiset.create(asList("a", "b", "c", "d", "e", "f")), multiset); } public void testCreation_sevenElements() { Multiset<String> multiset = ImmutableMultiset.of( "a", "b", "c", "d", "e", "f", "g"); assertEquals( HashMultiset.create(asList("a", "b", "c", "d", "e", "f", "g")), multiset); } public void testCreation_emptyArray() { String[] array = new String[0]; Multiset<String> multiset = ImmutableMultiset.copyOf(array); assertTrue(multiset.isEmpty()); } public void testCreation_arrayOfOneElement() { String[] array = new String[] { "a" }; Multiset<String> multiset = ImmutableMultiset.copyOf(array); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCreation_arrayOfArray() { String[] array = new String[] { "a" }; Multiset<String[]> multiset = ImmutableMultiset.<String[]>of(array); Multiset<String[]> expected = HashMultiset.create(); expected.add(array); assertEquals(expected, multiset); } public void testCreation_arrayContainingOnlyNull() { String[] array = new String[] { null }; try { ImmutableMultiset.copyOf(array); fail(); } catch (NullPointerException expected) {} } public void testCopyOf_collection_empty() { // "<String>" is required to work around a javac 1.5 bug. Collection<String> c = MinimalCollection.<String>of(); Multiset<String> multiset = ImmutableMultiset.copyOf(c); assertTrue(multiset.isEmpty()); } public void testCopyOf_collection_oneElement() { Collection<String> c = MinimalCollection.of("a"); Multiset<String> multiset = ImmutableMultiset.copyOf(c); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCopyOf_collection_general() { Collection<String> c = MinimalCollection.of("a", "b", "a"); Multiset<String> multiset = ImmutableMultiset.copyOf(c); assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset); } public void testCopyOf_collectionContainingNull() { Collection<String> c = MinimalCollection.of("a", null, "b"); try { ImmutableMultiset.copyOf(c); fail(); } catch (NullPointerException expected) {} } public void testCopyOf_multiset_empty() { Multiset<String> c = HashMultiset.create(); Multiset<String> multiset = ImmutableMultiset.copyOf(c); assertTrue(multiset.isEmpty()); } public void testCopyOf_multiset_oneElement() { Multiset<String> c = HashMultiset.create(asList("a")); Multiset<String> multiset = ImmutableMultiset.copyOf(c); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCopyOf_multiset_general() { Multiset<String> c = HashMultiset.create(asList("a", "b", "a")); Multiset<String> multiset = ImmutableMultiset.copyOf(c); assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset); } public void testCopyOf_multisetContainingNull() { Multiset<String> c = HashMultiset.create(asList("a", null, "b")); try { ImmutableMultiset.copyOf(c); fail(); } catch (NullPointerException expected) {} } public void testCopyOf_iterator_empty() { Iterator<String> iterator = Iterators.emptyIterator(); Multiset<String> multiset = ImmutableMultiset.copyOf(iterator); assertTrue(multiset.isEmpty()); } public void testCopyOf_iterator_oneElement() { Iterator<String> iterator = Iterators.singletonIterator("a"); Multiset<String> multiset = ImmutableMultiset.copyOf(iterator); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCopyOf_iterator_general() { Iterator<String> iterator = asList("a", "b", "a").iterator(); Multiset<String> multiset = ImmutableMultiset.copyOf(iterator); assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset); } public void testCopyOf_iteratorContainingNull() { Iterator<String> iterator = asList("a", null, "b").iterator(); try { ImmutableMultiset.copyOf(iterator); fail(); } catch (NullPointerException expected) {} } private static class CountingIterable implements Iterable<String> { int count = 0; @Override public Iterator<String> iterator() { count++; return asList("a", "b", "a").iterator(); } } public void testCopyOf_plainIterable() { CountingIterable iterable = new CountingIterable(); Multiset<String> multiset = ImmutableMultiset.copyOf(iterable); assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset); assertEquals(1, iterable.count); } public void testCopyOf_shortcut_empty() { Collection<String> c = ImmutableMultiset.of(); assertSame(c, ImmutableMultiset.copyOf(c)); } public void testCopyOf_shortcut_singleton() { Collection<String> c = ImmutableMultiset.of("a"); assertSame(c, ImmutableMultiset.copyOf(c)); } public void testCopyOf_shortcut_immutableMultiset() { Collection<String> c = ImmutableMultiset.of("a", "b", "c"); assertSame(c, ImmutableMultiset.copyOf(c)); } public void testBuilderAdd() { ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>() .add("a") .add("b") .add("a") .add("c") .build(); assertEquals(HashMultiset.create(asList("a", "b", "a", "c")), multiset); } public void testBuilderAddAll() { List<String> a = asList("a", "b"); List<String> b = asList("c", "d"); ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>() .addAll(a) .addAll(b) .build(); assertEquals(HashMultiset.create(asList("a", "b", "c", "d")), multiset); } public void testBuilderAddAllMultiset() { Multiset<String> a = HashMultiset.create(asList("a", "b", "b")); Multiset<String> b = HashMultiset.create(asList("c", "b")); ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>() .addAll(a) .addAll(b) .build(); assertEquals( HashMultiset.create(asList("a", "b", "b", "b", "c")), multiset); } public void testBuilderAddAllIterator() { Iterator<String> iterator = asList("a", "b", "a", "c").iterator(); ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>() .addAll(iterator) .build(); assertEquals(HashMultiset.create(asList("a", "b", "a", "c")), multiset); } public void testBuilderAddCopies() { ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>() .addCopies("a", 2) .addCopies("b", 3) .addCopies("c", 0) .build(); assertEquals( HashMultiset.create(asList("a", "a", "b", "b", "b")), multiset); } public void testBuilderSetCount() { ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>() .add("a") .setCount("a", 2) .setCount("b", 3) .build(); assertEquals( HashMultiset.create(asList("a", "a", "b", "b", "b")), multiset); } public void testBuilderAddHandlesNullsCorrectly() { ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder(); try { builder.add((String) null); fail("expected NullPointerException"); } catch (NullPointerException expected) {} } public void testBuilderAddAllHandlesNullsCorrectly() { ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder(); try { builder.addAll((Collection<String>) null); fail("expected NullPointerException"); } catch (NullPointerException expected) {} builder = ImmutableMultiset.builder(); List<String> listWithNulls = asList("a", null, "b"); try { builder.addAll(listWithNulls); fail("expected NullPointerException"); } catch (NullPointerException expected) {} builder = ImmutableMultiset.builder(); Multiset<String> multisetWithNull = LinkedHashMultiset.create(asList("a", null, "b")); try { builder.addAll(multisetWithNull); fail("expected NullPointerException"); } catch (NullPointerException expected) {} } public void testBuilderAddCopiesHandlesNullsCorrectly() { ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder(); try { builder.addCopies(null, 2); fail("expected NullPointerException"); } catch (NullPointerException expected) {} } public void testBuilderAddCopiesIllegal() { ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder(); try { builder.addCopies("a", -2); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } public void testBuilderSetCountHandlesNullsCorrectly() { ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder(); try { builder.setCount(null, 2); fail("expected NullPointerException"); } catch (NullPointerException expected) {} } public void testBuilderSetCountIllegal() { ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder(); try { builder.setCount("a", -2); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } public void testEquals_immutableMultiset() { Collection<String> c = ImmutableMultiset.of("a", "b", "a"); assertEquals(c, ImmutableMultiset.of("a", "b", "a")); assertEquals(c, ImmutableMultiset.of("a", "a", "b")); ASSERT.that(c).isNotEqualTo(ImmutableMultiset.of("a", "b")); ASSERT.that(c).isNotEqualTo(ImmutableMultiset.of("a", "b", "c", "d")); } public void testIterationOrder() { Collection<String> c = ImmutableMultiset.of("a", "b", "a"); ASSERT.that(c).has().exactly("a", "a", "b").inOrder(); } public void testMultisetWrites() { Multiset<String> multiset = ImmutableMultiset.of("a", "b", "a"); UnmodifiableCollectionTests.assertMultisetIsUnmodifiable(multiset, "test"); } public void testAsList() { ImmutableMultiset<String> multiset = ImmutableMultiset.of("a", "a", "b", "b", "b"); ImmutableList<String> list = multiset.asList(); assertEquals(ImmutableList.of("a", "a", "b", "b", "b"), list); assertEquals(2, list.indexOf("b")); assertEquals(4, list.lastIndexOf("b")); } public void testEquals() { new EqualsTester() .addEqualityGroup(ImmutableMultiset.of(), ImmutableMultiset.of()) .addEqualityGroup(ImmutableMultiset.of(1), ImmutableMultiset.of(1)) .addEqualityGroup(ImmutableMultiset.of(1, 1), ImmutableMultiset.of(1, 1)) .addEqualityGroup(ImmutableMultiset.of(1, 2, 1), ImmutableMultiset.of(2, 1, 1)) .testEquals(); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ImmutableMultisetTest.java
Java
asf20
13,161
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.Iterator; import java.util.NoSuchElementException; /** * Unit test for {@code AbstractIterator}. * * @author Kevin Bourrillion */ @SuppressWarnings("serial") // No serialization is used in this test @GwtCompatible(emulated = true) // TODO(cpovirk): why is this slow (>1m/test) under GWT when fully optimized? public class AbstractIteratorTest extends TestCase { public void testDefaultBehaviorOfNextAndHasNext() { // This sample AbstractIterator returns 0 on the first call, 1 on the // second, then signals that it's reached the end of the data Iterator<Integer> iter = new AbstractIterator<Integer>() { private int rep; @Override public Integer computeNext() { switch (rep++) { case 0: return 0; case 1: return 1; case 2: return endOfData(); default: fail("Should not have been invoked again"); return null; } } }; assertTrue(iter.hasNext()); assertEquals(0, (int) iter.next()); // verify idempotence of hasNext() assertTrue(iter.hasNext()); assertTrue(iter.hasNext()); assertTrue(iter.hasNext()); assertEquals(1, (int) iter.next()); assertFalse(iter.hasNext()); // Make sure computeNext() doesn't get invoked again assertFalse(iter.hasNext()); try { iter.next(); fail("no exception thrown"); } catch (NoSuchElementException expected) { } } public void testDefaultBehaviorOfPeek() { /* * This sample AbstractIterator returns 0 on the first call, 1 on the * second, then signals that it's reached the end of the data */ AbstractIterator<Integer> iter = new AbstractIterator<Integer>() { private int rep; @Override public Integer computeNext() { switch (rep++) { case 0: return 0; case 1: return 1; case 2: return endOfData(); default: fail("Should not have been invoked again"); return null; } } }; assertEquals(0, (int) iter.peek()); assertEquals(0, (int) iter.peek()); assertTrue(iter.hasNext()); assertEquals(0, (int) iter.peek()); assertEquals(0, (int) iter.next()); assertEquals(1, (int) iter.peek()); assertEquals(1, (int) iter.next()); try { iter.peek(); fail("peek() should throw NoSuchElementException at end"); } catch (NoSuchElementException expected) { } try { iter.peek(); fail("peek() should continue to throw NoSuchElementException at end"); } catch (NoSuchElementException expected) { } try { iter.next(); fail("next() should throw NoSuchElementException as usual"); } catch (NoSuchElementException expected) { } try { iter.peek(); fail("peek() should still throw NoSuchElementException after next()"); } catch (NoSuchElementException expected) { } } public void testDefaultBehaviorOfPeekForEmptyIteration() { AbstractIterator<Integer> empty = new AbstractIterator<Integer>() { private boolean alreadyCalledEndOfData; @Override public Integer computeNext() { if (alreadyCalledEndOfData) { fail("Should not have been invoked again"); } alreadyCalledEndOfData = true; return endOfData(); } }; try { empty.peek(); fail("peek() should throw NoSuchElementException at end"); } catch (NoSuchElementException expected) { } try { empty.peek(); fail("peek() should continue to throw NoSuchElementException at end"); } catch (NoSuchElementException expected) { } } public void testSneakyThrow() throws Exception { Iterator<Integer> iter = new AbstractIterator<Integer>() { boolean haveBeenCalled; @Override public Integer computeNext() { if (haveBeenCalled) { fail("Should not have been called again"); } else { haveBeenCalled = true; sneakyThrow(new SomeCheckedException()); } return null; // never reached } }; // The first time, the sneakily-thrown exception comes out try { iter.hasNext(); fail("No exception thrown"); } catch (Exception e) { if (!(e instanceof SomeCheckedException)) { throw e; } } // But the second time, AbstractIterator itself throws an ISE try { iter.hasNext(); fail("No exception thrown"); } catch (IllegalStateException expected) { } } public void testException() { final SomeUncheckedException exception = new SomeUncheckedException(); Iterator<Integer> iter = new AbstractIterator<Integer>() { @Override public Integer computeNext() { throw exception; } }; // It should pass through untouched try { iter.hasNext(); fail("No exception thrown"); } catch (SomeUncheckedException e) { assertSame(exception, e); } } public void testExceptionAfterEndOfData() { Iterator<Integer> iter = new AbstractIterator<Integer>() { @Override public Integer computeNext() { endOfData(); throw new SomeUncheckedException(); } }; try { iter.hasNext(); fail("No exception thrown"); } catch (SomeUncheckedException expected) { } } public void testCantRemove() { Iterator<Integer> iter = new AbstractIterator<Integer>() { boolean haveBeenCalled; @Override public Integer computeNext() { if (haveBeenCalled) { endOfData(); } haveBeenCalled = true; return 0; } }; assertEquals(0, (int) iter.next()); try { iter.remove(); fail("No exception thrown"); } catch (UnsupportedOperationException expected) { } } public void testReentrantHasNext() { Iterator<Integer> iter = new AbstractIterator<Integer>() { @Override protected Integer computeNext() { hasNext(); return null; } }; try { iter.hasNext(); fail(); } catch (IllegalStateException expected) { } } // Technically we should test other reentrant scenarios (9 combinations of // hasNext/next/peek), but we'll cop out for now, knowing that peek() and // next() both start by invoking hasNext() anyway. /** * Throws a undeclared checked exception. */ private static void sneakyThrow(Throwable t) { class SneakyThrower<T extends Throwable> { @SuppressWarnings("unchecked") // not really safe, but that's the point void throwIt(Throwable t) throws T { throw (T) t; } } new SneakyThrower<Error>().throwIt(t); } private static class SomeCheckedException extends Exception { } private static class SomeUncheckedException extends RuntimeException { } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/AbstractIteratorTest.java
Java
asf20
7,643
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * Unit tests for {@link ImmutableSortedSet}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class ImmutableSortedSetTest extends AbstractImmutableSetTest { // enum singleton pattern private enum StringLengthComparator implements Comparator<String> { INSTANCE; @Override public int compare(String a, String b) { return a.length() - b.length(); } } private static final Comparator<String> STRING_LENGTH = StringLengthComparator.INSTANCE; @Override protected SortedSet<String> of() { return ImmutableSortedSet.of(); } @Override protected SortedSet<String> of(String e) { return ImmutableSortedSet.of(e); } @Override protected SortedSet<String> of(String e1, String e2) { return ImmutableSortedSet.of(e1, e2); } @Override protected SortedSet<String> of(String e1, String e2, String e3) { return ImmutableSortedSet.of(e1, e2, e3); } @Override protected SortedSet<String> of( String e1, String e2, String e3, String e4) { return ImmutableSortedSet.of(e1, e2, e3, e4); } @Override protected SortedSet<String> of( String e1, String e2, String e3, String e4, String e5) { return ImmutableSortedSet.of(e1, e2, e3, e4, e5); } @Override protected SortedSet<String> of(String e1, String e2, String e3, String e4, String e5, String e6, String... rest) { return ImmutableSortedSet.of(e1, e2, e3, e4, e5, e6, rest); } @Override protected SortedSet<String> copyOf(String[] elements) { return ImmutableSortedSet.copyOf(elements); } @Override protected SortedSet<String> copyOf(Collection<String> elements) { return ImmutableSortedSet.copyOf(elements); } @Override protected SortedSet<String> copyOf(Iterable<String> elements) { return ImmutableSortedSet.copyOf(elements); } @Override protected SortedSet<String> copyOf(Iterator<String> elements) { return ImmutableSortedSet.copyOf(elements); } public void testEmpty_comparator() { SortedSet<String> set = of(); assertSame(Ordering.natural(), set.comparator()); } public void testEmpty_headSet() { SortedSet<String> set = of(); assertSame(set, set.headSet("c")); } public void testEmpty_tailSet() { SortedSet<String> set = of(); assertSame(set, set.tailSet("f")); } public void testEmpty_subSet() { SortedSet<String> set = of(); assertSame(set, set.subSet("c", "f")); } public void testEmpty_first() { SortedSet<String> set = of(); try { set.first(); fail(); } catch (NoSuchElementException expected) { } } public void testEmpty_last() { SortedSet<String> set = of(); try { set.last(); fail(); } catch (NoSuchElementException expected) { } } public void testSingle_comparator() { SortedSet<String> set = of("e"); assertSame(Ordering.natural(), set.comparator()); } public void testSingle_headSet() { SortedSet<String> set = of("e"); assertTrue(set.headSet("g") instanceof ImmutableSortedSet); ASSERT.that(set.headSet("g")).has().item("e"); assertSame(of(), set.headSet("c")); assertSame(of(), set.headSet("e")); } public void testSingle_tailSet() { SortedSet<String> set = of("e"); assertTrue(set.tailSet("c") instanceof ImmutableSortedSet); ASSERT.that(set.tailSet("c")).has().item("e"); ASSERT.that(set.tailSet("e")).has().item("e"); assertSame(of(), set.tailSet("g")); } public void testSingle_subSet() { SortedSet<String> set = of("e"); assertTrue(set.subSet("c", "g") instanceof ImmutableSortedSet); ASSERT.that(set.subSet("c", "g")).has().item("e"); ASSERT.that(set.subSet("e", "g")).has().item("e"); assertSame(of(), set.subSet("f", "g")); assertSame(of(), set.subSet("c", "e")); assertSame(of(), set.subSet("c", "d")); } public void testSingle_first() { SortedSet<String> set = of("e"); assertEquals("e", set.first()); } public void testSingle_last() { SortedSet<String> set = of("e"); assertEquals("e", set.last()); } public void testOf_ordering() { SortedSet<String> set = of("e", "a", "f", "b", "d", "c"); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } /* * Tests that we workaround GWT bug #3621 (or that it is already fixed). * * A call to of() with a parameter that is not a plain Object[] (here, * Interface[]) creates a RegularImmutableSortedSet backed by an array of that * type. Later, RegularImmutableSortedSet.toArray() calls System.arraycopy() * to copy from that array to the destination array. This would be fine, but * GWT has a bug: It refuses to copy from an E[] to an Object[] when E is an * interface type. */ // TODO: test other collections for this problem public void testOf_gwtArraycopyBug() { /* * The test requires: * * 1) An interface I extending Comparable<I> so that the created array is of * an interface type. 2) An instance of a class implementing that interface * so that we can pass non-null instances of the interface. * * (Currently it's safe to pass instances for which compareTo() always * returns 0, but if we had a SingletonImmutableSortedSet, this might no * longer be the case.) * * javax.naming.Name and java.util.concurrent.Delayed might work, but * they're fairly obscure, we've invented our own interface and class. */ Interface a = new Impl(); Interface b = new Impl(); ImmutableSortedSet<Interface> set = ImmutableSortedSet.of(a, b); set.toArray(); set.toArray(new Object[2]); } interface Interface extends Comparable<Interface> { } static class Impl implements Interface { static int nextId; Integer id = nextId++; @Override public int compareTo(Interface other) { return id.compareTo(((Impl) other).id); } } public void testOf_ordering_dupes() { SortedSet<String> set = of("e", "a", "e", "f", "b", "b", "d", "a", "c"); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testOf_comparator() { SortedSet<String> set = of("e", "a", "f", "b", "d", "c"); assertSame(Ordering.natural(), set.comparator()); } public void testOf_headSet() { SortedSet<String> set = of("e", "f", "b", "d", "c"); assertTrue(set.headSet("e") instanceof ImmutableSortedSet); ASSERT.that(set.headSet("e")).has().exactly("b", "c", "d").inOrder(); ASSERT.that(set.headSet("g")).has().exactly("b", "c", "d", "e", "f").inOrder(); assertSame(of(), set.headSet("a")); assertSame(of(), set.headSet("b")); } public void testOf_tailSet() { SortedSet<String> set = of("e", "f", "b", "d", "c"); assertTrue(set.tailSet("e") instanceof ImmutableSortedSet); ASSERT.that(set.tailSet("e")).has().exactly("e", "f").inOrder(); ASSERT.that(set.tailSet("a")).has().exactly("b", "c", "d", "e", "f").inOrder(); assertSame(of(), set.tailSet("g")); } public void testOf_subSet() { SortedSet<String> set = of("e", "f", "b", "d", "c"); assertTrue(set.subSet("c", "e") instanceof ImmutableSortedSet); ASSERT.that(set.subSet("c", "e")).has().exactly("c", "d").inOrder(); ASSERT.that(set.subSet("a", "g")).has().exactly("b", "c", "d", "e", "f").inOrder(); assertSame(of(), set.subSet("a", "b")); assertSame(of(), set.subSet("g", "h")); assertSame(of(), set.subSet("c", "c")); try { set.subSet("e", "c"); fail(); } catch (IllegalArgumentException expected) { } } public void testOf_first() { SortedSet<String> set = of("e", "f", "b", "d", "c"); assertEquals("b", set.first()); } public void testOf_last() { SortedSet<String> set = of("e", "f", "b", "d", "c"); assertEquals("f", set.last()); } /* "Explicit" indicates an explicit comparator. */ public void testExplicit_ordering() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testExplicit_ordering_dupes() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "brown", "fox", "jumped", "over", "a", "lazy", "dog").build(); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testExplicit_contains() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertTrue(set.contains("quick")); assertTrue(set.contains("google")); assertFalse(set.contains("")); assertFalse(set.contains("california")); assertFalse(set.contains(null)); } public void testExplicit_containsMismatchedTypes() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertFalse(set.contains(3.7)); } public void testExplicit_comparator() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertSame(STRING_LENGTH, set.comparator()); } public void testExplicit_headSet() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertTrue(set.headSet("a") instanceof ImmutableSortedSet); assertTrue(set.headSet("fish") instanceof ImmutableSortedSet); ASSERT.that(set.headSet("fish")).has().exactly("a", "in", "the").inOrder(); ASSERT.that(set.headSet("california")).has() .exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); assertTrue(set.headSet("a").isEmpty()); assertTrue(set.headSet("").isEmpty()); } public void testExplicit_tailSet() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertTrue(set.tailSet("california") instanceof ImmutableSortedSet); assertTrue(set.tailSet("fish") instanceof ImmutableSortedSet); ASSERT.that(set.tailSet("fish")).has().exactly("over", "quick", "jumped").inOrder(); ASSERT.that( set.tailSet("a")).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); assertTrue(set.tailSet("california").isEmpty()); } public void testExplicit_subSet() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertTrue(set.subSet("the", "quick") instanceof ImmutableSortedSet); assertTrue(set.subSet("", "b") instanceof ImmutableSortedSet); ASSERT.that(set.subSet("the", "quick")).has().exactly("the", "over").inOrder(); ASSERT.that(set.subSet("a", "california")) .has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); assertTrue(set.subSet("", "b").isEmpty()); assertTrue(set.subSet("vermont", "california").isEmpty()); assertTrue(set.subSet("aaa", "zzz").isEmpty()); try { set.subSet("quick", "the"); fail(); } catch (IllegalArgumentException expected) { } } public void testExplicit_first() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertEquals("a", set.first()); } public void testExplicit_last() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); assertEquals("jumped", set.last()); } public void testCopyOf_ordering() { SortedSet<String> set = copyOf(asList("e", "a", "f", "b", "d", "c")); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_ordering_dupes() { SortedSet<String> set = copyOf(asList("e", "a", "e", "f", "b", "b", "d", "a", "c")); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_subSet() { SortedSet<String> set = of("e", "a", "f", "b", "d", "c"); SortedSet<String> subset = set.subSet("c", "e"); SortedSet<String> copy = copyOf(subset); assertEquals(subset, copy); } public void testCopyOf_headSet() { SortedSet<String> set = of("e", "a", "f", "b", "d", "c"); SortedSet<String> headset = set.headSet("d"); SortedSet<String> copy = copyOf(headset); assertEquals(headset, copy); } public void testCopyOf_tailSet() { SortedSet<String> set = of("e", "a", "f", "b", "d", "c"); SortedSet<String> tailset = set.tailSet("d"); SortedSet<String> copy = copyOf(tailset); assertEquals(tailset, copy); } public void testCopyOf_comparator() { SortedSet<String> set = copyOf(asList("e", "a", "f", "b", "d", "c")); assertSame(Ordering.natural(), set.comparator()); } public void testCopyOf_iterator_ordering() { SortedSet<String> set = copyOf(asIterator("e", "a", "f", "b", "d", "c")); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_iterator_ordering_dupes() { SortedSet<String> set = copyOf(asIterator("e", "a", "e", "f", "b", "b", "d", "a", "c")); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_iterator_comparator() { SortedSet<String> set = copyOf(asIterator("e", "a", "f", "b", "d", "c")); assertSame(Ordering.natural(), set.comparator()); } public void testCopyOf_sortedSet_ordering() { SortedSet<String> set = copyOf(Sets.newTreeSet(asList("e", "a", "f", "b", "d", "c"))); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_sortedSet_comparator() { SortedSet<String> set = copyOf(Sets.<String>newTreeSet()); assertSame(Ordering.natural(), set.comparator()); } public void testCopyOfExplicit_ordering() { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asList( "in", "the", "quick", "jumped", "over", "a")); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testCopyOfExplicit_ordering_dupes() { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asList( "in", "the", "quick", "brown", "fox", "jumped", "over", "a", "lazy", "dog")); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testCopyOfExplicit_comparator() { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asList( "in", "the", "quick", "jumped", "over", "a")); assertSame(STRING_LENGTH, set.comparator()); } public void testCopyOfExplicit_iterator_ordering() { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asIterator( "in", "the", "quick", "jumped", "over", "a")); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testCopyOfExplicit_iterator_ordering_dupes() { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asIterator( "in", "the", "quick", "brown", "fox", "jumped", "over", "a", "lazy", "dog")); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testCopyOfExplicit_iterator_comparator() { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asIterator( "in", "the", "quick", "jumped", "over", "a")); assertSame(STRING_LENGTH, set.comparator()); } public void testCopyOf_sortedSetIterable() { SortedSet<String> input = Sets.newTreeSet(STRING_LENGTH); Collections.addAll(input, "in", "the", "quick", "jumped", "over", "a"); SortedSet<String> set = copyOf(input); ASSERT.that(set).has().exactly("a", "in", "jumped", "over", "quick", "the").inOrder(); } public void testCopyOfSorted_natural_ordering() { SortedSet<String> input = Sets.newTreeSet( asList("in", "the", "quick", "jumped", "over", "a")); SortedSet<String> set = ImmutableSortedSet.copyOfSorted(input); ASSERT.that(set).has().exactly("a", "in", "jumped", "over", "quick", "the").inOrder(); } public void testCopyOfSorted_natural_comparator() { SortedSet<String> input = Sets.newTreeSet(asList("in", "the", "quick", "jumped", "over", "a")); SortedSet<String> set = ImmutableSortedSet.copyOfSorted(input); assertSame(Ordering.natural(), set.comparator()); } public void testCopyOfSorted_explicit_ordering() { SortedSet<String> input = Sets.newTreeSet(STRING_LENGTH); Collections.addAll(input, "in", "the", "quick", "jumped", "over", "a"); SortedSet<String> set = ImmutableSortedSet.copyOfSorted(input); ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); assertSame(STRING_LENGTH, set.comparator()); } public void testEquals_bothDefaultOrdering() { SortedSet<String> set = of("a", "b", "c"); assertEquals(set, Sets.newTreeSet(asList("a", "b", "c"))); assertEquals(Sets.newTreeSet(asList("a", "b", "c")), set); assertFalse(set.equals(Sets.newTreeSet(asList("a", "b", "d")))); assertFalse(Sets.newTreeSet(asList("a", "b", "d")).equals(set)); assertFalse(set.equals(Sets.newHashSet(4, 5, 6))); assertFalse(Sets.newHashSet(4, 5, 6).equals(set)); } public void testEquals_bothExplicitOrdering() { SortedSet<String> set = of("in", "the", "a"); assertEquals(Sets.newTreeSet(asList("in", "the", "a")), set); assertFalse(set.equals(Sets.newTreeSet(asList("in", "the", "house")))); assertFalse(Sets.newTreeSet(asList("in", "the", "house")).equals(set)); assertFalse(set.equals(Sets.newHashSet(4, 5, 6))); assertFalse(Sets.newHashSet(4, 5, 6).equals(set)); Set<String> complex = Sets.newTreeSet(STRING_LENGTH); Collections.addAll(complex, "in", "the", "a"); assertEquals(set, complex); } public void testEquals_bothDefaultOrdering_StringVsInt() { SortedSet<String> set = of("a", "b", "c"); assertFalse(set.equals(Sets.newTreeSet(asList(4, 5, 6)))); assertNotEqualLenient(Sets.newTreeSet(asList(4, 5, 6)), set); } public void testEquals_bothExplicitOrdering_StringVsInt() { SortedSet<String> set = of("in", "the", "a"); assertFalse(set.equals(Sets.newTreeSet(asList(4, 5, 6)))); assertNotEqualLenient(Sets.newTreeSet(asList(4, 5, 6)), set); } public void testContainsAll_notSortedSet() { SortedSet<String> set = of("a", "b", "f"); assertTrue(set.containsAll(Collections.emptyList())); assertTrue(set.containsAll(asList("b"))); assertTrue(set.containsAll(asList("b", "b"))); assertTrue(set.containsAll(asList("b", "f"))); assertTrue(set.containsAll(asList("b", "f", "a"))); assertFalse(set.containsAll(asList("d"))); assertFalse(set.containsAll(asList("z"))); assertFalse(set.containsAll(asList("b", "d"))); assertFalse(set.containsAll(asList("f", "d", "a"))); } public void testContainsAll_sameComparator() { SortedSet<String> set = of("a", "b", "f"); assertTrue(set.containsAll(Sets.newTreeSet())); assertTrue(set.containsAll(Sets.newTreeSet(asList("b")))); assertTrue(set.containsAll(Sets.newTreeSet(asList("a", "f")))); assertTrue(set.containsAll(Sets.newTreeSet(asList("a", "b", "f")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("d")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("z")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("b", "d")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("f", "d", "a")))); } public void testContainsAll_sameComparator_StringVsInt() { SortedSet<String> set = of("a", "b", "f"); SortedSet<Integer> unexpected = Sets.newTreeSet(Ordering.natural()); unexpected.addAll(asList(1, 2, 3)); assertFalse(set.containsAll(unexpected)); } public void testContainsAll_differentComparator() { Comparator<Comparable<?>> comparator = Collections.reverseOrder(); SortedSet<String> set = new ImmutableSortedSet.Builder<String>(comparator) .add("a", "b", "f").build(); assertTrue(set.containsAll(Sets.newTreeSet())); assertTrue(set.containsAll(Sets.newTreeSet(asList("b")))); assertTrue(set.containsAll(Sets.newTreeSet(asList("a", "f")))); assertTrue(set.containsAll(Sets.newTreeSet(asList("a", "b", "f")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("d")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("z")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("b", "d")))); assertFalse(set.containsAll(Sets.newTreeSet(asList("f", "d", "a")))); } public void testReverseOrder() { SortedSet<String> set = ImmutableSortedSet.<String>reverseOrder() .add("a", "b", "c").build(); ASSERT.that(set).has().exactly("c", "b", "a").inOrder(); assertEquals(Ordering.natural().reverse(), set.comparator()); } private static final Comparator<Object> TO_STRING = new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } }; public void testSupertypeComparator() { SortedSet<Integer> set = new ImmutableSortedSet.Builder<Integer>(TO_STRING) .add(3, 12, 101, 44).build(); ASSERT.that(set).has().exactly(101, 12, 3, 44).inOrder(); } public void testSupertypeComparatorSubtypeElements() { SortedSet<Number> set = new ImmutableSortedSet.Builder<Number>(TO_STRING) .add(3, 12, 101, 44).build(); ASSERT.that(set).has().exactly(101, 12, 3, 44).inOrder(); } @Override <E extends Comparable<E>> ImmutableSortedSet.Builder<E> builder() { return ImmutableSortedSet.naturalOrder(); } @Override int getComplexBuilderSetLastElement() { return 0x00FFFFFF; } public void testLegacyComparable_of() { ImmutableSortedSet<LegacyComparable> set0 = ImmutableSortedSet.of(); @SuppressWarnings("unchecked") // using a legacy comparable ImmutableSortedSet<LegacyComparable> set1 = ImmutableSortedSet.of( LegacyComparable.Z); @SuppressWarnings("unchecked") // using a legacy comparable ImmutableSortedSet<LegacyComparable> set2 = ImmutableSortedSet.of( LegacyComparable.Z, LegacyComparable.Y); } public void testLegacyComparable_copyOf_collection() { ImmutableSortedSet<LegacyComparable> set = ImmutableSortedSet.copyOf(LegacyComparable.VALUES_BACKWARD); assertTrue(Iterables.elementsEqual(LegacyComparable.VALUES_FORWARD, set)); } public void testLegacyComparable_copyOf_iterator() { ImmutableSortedSet<LegacyComparable> set = ImmutableSortedSet.copyOf( LegacyComparable.VALUES_BACKWARD.iterator()); assertTrue(Iterables.elementsEqual(LegacyComparable.VALUES_FORWARD, set)); } public void testLegacyComparable_builder_natural() { @SuppressWarnings("unchecked") // Note: IntelliJ wrongly reports an error for this statement ImmutableSortedSet.Builder<LegacyComparable> builder = ImmutableSortedSet.<LegacyComparable>naturalOrder(); builder.addAll(LegacyComparable.VALUES_BACKWARD); builder.add(LegacyComparable.X); builder.add(LegacyComparable.Y, LegacyComparable.Z); ImmutableSortedSet<LegacyComparable> set = builder.build(); assertTrue(Iterables.elementsEqual(LegacyComparable.VALUES_FORWARD, set)); } public void testLegacyComparable_builder_reverse() { @SuppressWarnings("unchecked") // Note: IntelliJ wrongly reports an error for this statement ImmutableSortedSet.Builder<LegacyComparable> builder = ImmutableSortedSet.<LegacyComparable>reverseOrder(); builder.addAll(LegacyComparable.VALUES_FORWARD); builder.add(LegacyComparable.X); builder.add(LegacyComparable.Y, LegacyComparable.Z); ImmutableSortedSet<LegacyComparable> set = builder.build(); assertTrue(Iterables.elementsEqual(LegacyComparable.VALUES_BACKWARD, set)); } @SuppressWarnings({"deprecation", "static-access"}) public void testBuilderMethod() { try { ImmutableSortedSet.builder(); fail(); } catch (UnsupportedOperationException expected) { } } public void testAsList() { ImmutableSet<String> set = ImmutableSortedSet.of("a", "e", "i", "o", "u"); ImmutableList<String> list = set.asList(); assertEquals(ImmutableList.of("a", "e", "i", "o", "u"), list); assertSame(list, ImmutableList.copyOf(set)); } public void testSubsetAsList() { ImmutableSet<String> set = ImmutableSortedSet.of("a", "e", "i", "o", "u").subSet("c", "r"); ImmutableList<String> list = set.asList(); assertEquals(ImmutableList.of("e", "i", "o"), list); assertEquals(list, ImmutableList.copyOf(set)); } public void testAsListInconsistentComprator() { ImmutableSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); ImmutableList<String> list = set.asList(); assertTrue(list.contains("the")); assertEquals(2, list.indexOf("the")); assertEquals(2, list.lastIndexOf("the")); assertFalse(list.contains("dog")); assertEquals(-1, list.indexOf("dog")); assertEquals(-1, list.lastIndexOf("dog")); assertFalse(list.contains("chicken")); assertEquals(-1, list.indexOf("chicken")); assertEquals(-1, list.lastIndexOf("chicken")); } private static <E> Iterator<E> asIterator(E... elements) { return asList(elements).iterator(); } // In GWT, java.util.TreeSet throws ClassCastException when the comparator // throws it, unlike JDK6. Therefore, we accept ClassCastException as a // valid result thrown by java.util.TreeSet#equals. private static void assertNotEqualLenient( TreeSet<?> unexpected, SortedSet<?> actual) { try { ASSERT.that(actual).isNotEqualTo(unexpected); } catch (ClassCastException accepted) { } } public void testHeadSetInclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { ASSERT.that(set.headSet(strings[i], true)) .has().exactlyAs(sortedNumberNames(0, i + 1)).inOrder(); } } public void testHeadSetExclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { ASSERT.that(set.headSet(strings[i], false)).has().exactlyAs( sortedNumberNames(0, i)).inOrder(); } } public void testTailSetInclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { ASSERT.that(set.tailSet(strings[i], true)).has().exactlyAs( sortedNumberNames(i, strings.length)).inOrder(); } } public void testTailSetExclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { ASSERT.that(set.tailSet(strings[i], false)).has().exactlyAs( sortedNumberNames(i + 1, strings.length)).inOrder(); } } public void testSubSetExclusiveExclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { for (int j = i; j < strings.length; j++) { ASSERT.that(set.subSet(strings[i], false, strings[j], false)) .has().exactlyAs(sortedNumberNames(Math.min(i + 1, j), j)).inOrder(); } } } public void testSubSetInclusiveExclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { for (int j = i; j < strings.length; j++) { ASSERT.that(set.subSet(strings[i], true, strings[j], false)) .has().exactlyAs(sortedNumberNames(i, j)).inOrder(); } } } public void testSubSetExclusiveInclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { for (int j = i; j < strings.length; j++) { ASSERT.that(set.subSet(strings[i], false, strings[j], true)) .has().exactlyAs(sortedNumberNames(i + 1, j + 1)).inOrder(); } } } public void testSubSetInclusiveInclusive() { String[] strings = NUMBER_NAMES.toArray(new String[0]); ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { for (int j = i; j < strings.length; j++) { ASSERT.that(set.subSet(strings[i], true, strings[j], true)) .has().exactlyAs(sortedNumberNames(i, j + 1)).inOrder(); } } } private static ImmutableList<String> sortedNumberNames(int i, int j) { return ImmutableList.copyOf(SORTED_NUMBER_NAMES.subList(i, j)); } private static final ImmutableList<String> NUMBER_NAMES = ImmutableList.of("one", "two", "three", "four", "five", "six", "seven"); private static final ImmutableList<String> SORTED_NUMBER_NAMES = Ordering.natural().immutableSortedCopy(NUMBER_NAMES); private static class SelfComparableExample implements Comparable<SelfComparableExample> { @Override public int compareTo(SelfComparableExample o) { return 0; } } public void testBuilderGenerics_SelfComparable() { ImmutableSortedSet.Builder<SelfComparableExample> natural = ImmutableSortedSet.naturalOrder(); ImmutableSortedSet.Builder<SelfComparableExample> reverse = ImmutableSortedSet.reverseOrder(); } private static class SuperComparableExample extends SelfComparableExample {} public void testBuilderGenerics_SuperComparable() { ImmutableSortedSet.Builder<SuperComparableExample> natural = ImmutableSortedSet.naturalOrder(); ImmutableSortedSet.Builder<SuperComparableExample> reverse = ImmutableSortedSet.reverseOrder(); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ImmutableSortedSetTest.java
Java
asf20
31,853
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.testing.SerializableTester.reserialize; import static com.google.common.testing.SerializableTester.reserializeAndAssert; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.collect.Ordering.ArbitraryOrdering; import com.google.common.collect.Ordering.IncomparableValueException; import com.google.common.collect.testing.Helpers; import com.google.common.primitives.Ints; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.RandomAccess; import javax.annotation.Nullable; /** * Unit tests for {@code Ordering}. * * @author Jesse Wilson */ @GwtCompatible(emulated = true) public class OrderingTest extends TestCase { // TODO(cpovirk): some of these are inexplicably slow (20-30s) under GWT private final Ordering<Number> numberOrdering = new NumberOrdering(); public void testAllEqual() { Ordering<Object> comparator = Ordering.allEqual(); assertSame(comparator, comparator.reverse()); assertEquals(comparator.compare(null, null), 0); assertEquals(comparator.compare(new Object(), new Object()), 0); assertEquals(comparator.compare("apples", "oranges"), 0); assertSame(comparator, reserialize(comparator)); assertEquals("Ordering.allEqual()", comparator.toString()); List<String> strings = ImmutableList.of("b", "a", "d", "c"); assertEquals(strings, comparator.sortedCopy(strings)); assertEquals(strings, comparator.immutableSortedCopy(strings)); } public void testNatural() { Ordering<Integer> comparator = Ordering.natural(); Helpers.testComparator(comparator, Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE); try { comparator.compare(1, null); fail(); } catch (NullPointerException expected) {} try { comparator.compare(null, 2); fail(); } catch (NullPointerException expected) {} try { comparator.compare(null, null); fail(); } catch (NullPointerException expected) {} assertSame(comparator, reserialize(comparator)); assertEquals("Ordering.natural()", comparator.toString()); } public void testFrom() { Ordering<String> caseInsensitiveOrdering = Ordering.from(String.CASE_INSENSITIVE_ORDER); assertEquals(0, caseInsensitiveOrdering.compare("A", "a")); assertTrue(caseInsensitiveOrdering.compare("a", "B") < 0); assertTrue(caseInsensitiveOrdering.compare("B", "a") > 0); @SuppressWarnings("deprecation") // test of deprecated method Ordering<String> orderingFromOrdering = Ordering.from(Ordering.<String>natural()); new EqualsTester() .addEqualityGroup(caseInsensitiveOrdering, Ordering.from(String.CASE_INSENSITIVE_ORDER)) .addEqualityGroup(orderingFromOrdering, Ordering.natural()) .testEquals(); } public void testExplicit_none() { Comparator<Integer> c = Ordering.explicit(Collections.<Integer>emptyList()); try { c.compare(0, 0); fail(); } catch (IncomparableValueException expected) { assertEquals(0, expected.value); } reserializeAndAssert(c); } public void testExplicit_one() { Comparator<Integer> c = Ordering.explicit(0); assertEquals(0, c.compare(0, 0)); try { c.compare(0, 1); fail(); } catch (IncomparableValueException expected) { assertEquals(1, expected.value); } reserializeAndAssert(c); assertEquals("Ordering.explicit([0])", c.toString()); } public void testExplicit_two() { Comparator<Integer> c = Ordering.explicit(42, 5); assertEquals(0, c.compare(5, 5)); assertTrue(c.compare(5, 42) > 0); assertTrue(c.compare(42, 5) < 0); try { c.compare(5, 666); fail(); } catch (IncomparableValueException expected) { assertEquals(666, expected.value); } new EqualsTester() .addEqualityGroup(c, Ordering.explicit(42, 5)) .addEqualityGroup(Ordering.explicit(5, 42)) .addEqualityGroup(Ordering.explicit(42)) .testEquals(); reserializeAndAssert(c); } public void testExplicit_sortingExample() { Comparator<Integer> c = Ordering.explicit(2, 8, 6, 1, 7, 5, 3, 4, 0, 9); List<Integer> list = Arrays.asList(0, 3, 5, 6, 7, 8, 9); Collections.sort(list, c); ASSERT.that(list).has().exactly(8, 6, 7, 5, 3, 0, 9).inOrder(); reserializeAndAssert(c); } public void testExplicit_withDuplicates() { try { Ordering.explicit(1, 2, 3, 4, 2); fail(); } catch (IllegalArgumentException expected) { } } // A more limited test than the one that follows, but this one uses the // actual public API. public void testArbitrary_withoutCollisions() { List<Object> list = Lists.newArrayList(); for (int i = 0; i < 50; i++) { list.add(new Object()); } Ordering<Object> arbitrary = Ordering.arbitrary(); Collections.sort(list, arbitrary); // Now we don't care what order it's put the list in, only that // comparing any pair of elements gives the answer we expect. Helpers.testComparator(arbitrary, list); assertEquals("Ordering.arbitrary()", arbitrary.toString()); } public void testArbitrary_withCollisions() { List<Integer> list = Lists.newArrayList(); for (int i = 0; i < 50; i++) { list.add(i); } Ordering<Object> arbitrary = new ArbitraryOrdering() { @Override int identityHashCode(Object object) { return ((Integer) object) % 5; // fake tons of collisions! } }; // Don't let the elements be in such a predictable order list = shuffledCopy(list, new Random(1)); Collections.sort(list, arbitrary); // Now we don't care what order it's put the list in, only that // comparing any pair of elements gives the answer we expect. Helpers.testComparator(arbitrary, list); } public void testUsingToString() { Ordering<Object> ordering = Ordering.usingToString(); Helpers.testComparator(ordering, 1, 12, 124, 2); assertEquals("Ordering.usingToString()", ordering.toString()); assertSame(ordering, reserialize(ordering)); } // use an enum to get easy serializability private enum CharAtFunction implements Function<String, Character> { AT0(0), AT1(1), AT2(2), AT3(3), AT4(4), AT5(5), ; final int index; CharAtFunction(int index) { this.index = index; } @Override public Character apply(String string) { return string.charAt(index); } } private static Ordering<String> byCharAt(int index) { return Ordering.natural().onResultOf(CharAtFunction.values()[index]); } public void testCompound_static() { Comparator<String> comparator = Ordering.compound(ImmutableList.of( byCharAt(0), byCharAt(1), byCharAt(2), byCharAt(3), byCharAt(4), byCharAt(5))); Helpers.testComparator(comparator, ImmutableList.of( "applesauce", "apricot", "artichoke", "banality", "banana", "banquet", "tangelo", "tangerine")); reserializeAndAssert(comparator); } public void testCompound_instance() { Comparator<String> comparator = byCharAt(1).compound(byCharAt(0)); Helpers.testComparator(comparator, ImmutableList.of( "red", "yellow", "violet", "blue", "indigo", "green", "orange")); } public void testCompound_instance_generics() { Ordering<Object> objects = Ordering.explicit((Object) 1); Ordering<Number> numbers = Ordering.explicit((Number) 1); Ordering<Integer> integers = Ordering.explicit(1); // Like by like equals like Ordering<Number> a = numbers.compound(numbers); // The compound takes the more specific type of the two, regardless of order Ordering<Number> b = numbers.compound(objects); Ordering<Number> c = objects.compound(numbers); Ordering<Integer> d = numbers.compound(integers); Ordering<Integer> e = integers.compound(numbers); // This works with three levels too (IDEA falsely reports errors as noted // below. Both javac and eclipse handle these cases correctly.) Ordering<Number> f = numbers.compound(objects).compound(objects); //bad IDEA Ordering<Number> g = objects.compound(numbers).compound(objects); Ordering<Number> h = objects.compound(objects).compound(numbers); Ordering<Number> i = numbers.compound(objects.compound(objects)); Ordering<Number> j = objects.compound(numbers.compound(objects)); //bad IDEA Ordering<Number> k = objects.compound(objects.compound(numbers)); // You can also arbitrarily assign a more restricted type - not an intended // feature, exactly, but unavoidable (I think) and harmless Ordering<Integer> l = objects.compound(numbers); // This correctly doesn't work: // Ordering<Object> m = numbers.compound(objects); // Sadly, the following works in javac 1.6, but at least it fails for // eclipse, and is *correctly* highlighted red in IDEA. // Ordering<Object> n = objects.compound(numbers); } public void testReverse() { Ordering<Number> reverseOrder = numberOrdering.reverse(); Helpers.testComparator(reverseOrder, Integer.MAX_VALUE, 1, 0, -1, Integer.MIN_VALUE); new EqualsTester() .addEqualityGroup(reverseOrder, numberOrdering.reverse()) .addEqualityGroup(Ordering.natural().reverse()) .addEqualityGroup(Collections.reverseOrder()) .testEquals(); } public void testReverseOfReverseSameAsForward() { // Not guaranteed by spec, but it works, and saves us from testing // exhaustively assertSame(numberOrdering, numberOrdering.reverse().reverse()); } private enum StringLengthFunction implements Function<String, Integer> { StringLength; @Override public Integer apply(String string) { return string.length(); } } private static final Ordering<Integer> DECREASING_INTEGER = Ordering.natural().reverse(); public void testOnResultOf_natural() { Comparator<String> comparator = Ordering.natural().onResultOf(StringLengthFunction.StringLength); assertTrue(comparator.compare("to", "be") == 0); assertTrue(comparator.compare("or", "not") < 0); assertTrue(comparator.compare("that", "to") > 0); new EqualsTester() .addEqualityGroup( comparator, Ordering.natural().onResultOf(StringLengthFunction.StringLength)) .addEqualityGroup(DECREASING_INTEGER) .testEquals(); reserializeAndAssert(comparator); assertEquals("Ordering.natural().onResultOf(StringLength)", comparator.toString()); } public void testOnResultOf_chained() { Comparator<String> comparator = DECREASING_INTEGER.onResultOf( StringLengthFunction.StringLength); assertTrue(comparator.compare("to", "be") == 0); assertTrue(comparator.compare("not", "or") < 0); assertTrue(comparator.compare("to", "that") > 0); new EqualsTester() .addEqualityGroup( comparator, DECREASING_INTEGER.onResultOf(StringLengthFunction.StringLength)) .addEqualityGroup( DECREASING_INTEGER.onResultOf(Functions.constant(1))) .addEqualityGroup(Ordering.natural()) .testEquals(); reserializeAndAssert(comparator); assertEquals("Ordering.natural().reverse().onResultOf(StringLength)", comparator.toString()); } @SuppressWarnings("unchecked") // dang varargs public void testLexicographical() { Ordering<String> ordering = Ordering.natural(); Ordering<Iterable<String>> lexy = ordering.lexicographical(); ImmutableList<String> empty = ImmutableList.of(); ImmutableList<String> a = ImmutableList.of("a"); ImmutableList<String> aa = ImmutableList.of("a", "a"); ImmutableList<String> ab = ImmutableList.of("a", "b"); ImmutableList<String> b = ImmutableList.of("b"); Helpers.testComparator(lexy, empty, a, aa, ab, b); new EqualsTester() .addEqualityGroup(lexy, ordering.lexicographical()) .addEqualityGroup(numberOrdering.lexicographical()) .addEqualityGroup(Ordering.natural()) .testEquals(); } public void testNullsFirst() { Ordering<Integer> ordering = Ordering.natural().nullsFirst(); Helpers.testComparator(ordering, null, Integer.MIN_VALUE, 0, 1); new EqualsTester() .addEqualityGroup(ordering, Ordering.natural().nullsFirst()) .addEqualityGroup(numberOrdering.nullsFirst()) .addEqualityGroup(Ordering.natural()) .testEquals(); } public void testNullsLast() { Ordering<Integer> ordering = Ordering.natural().nullsLast(); Helpers.testComparator(ordering, 0, 1, Integer.MAX_VALUE, null); new EqualsTester() .addEqualityGroup(ordering, Ordering.natural().nullsLast()) .addEqualityGroup(numberOrdering.nullsLast()) .addEqualityGroup(Ordering.natural()) .testEquals(); } public void testBinarySearch() { List<Integer> ints = Lists.newArrayList(0, 2, 3, 5, 7, 9); assertEquals(4, numberOrdering.binarySearch(ints, 7)); } public void testSortedCopy() { List<Integer> unsortedInts = Collections.unmodifiableList( Arrays.asList(5, 0, 3, null, 0, 9)); List<Integer> sortedInts = numberOrdering.nullsLast().sortedCopy(unsortedInts); assertEquals(Arrays.asList(0, 0, 3, 5, 9, null), sortedInts); assertEquals(Collections.emptyList(), numberOrdering.sortedCopy(Collections.<Integer>emptyList())); } public void testImmutableSortedCopy() { ImmutableList<Integer> unsortedInts = ImmutableList.of(5, 3, 0, 9, 3); ImmutableList<Integer> sortedInts = numberOrdering.immutableSortedCopy(unsortedInts); assertEquals(Arrays.asList(0, 3, 3, 5, 9), sortedInts); assertEquals(Collections.<Integer>emptyList(), numberOrdering.immutableSortedCopy(Collections.<Integer>emptyList())); List<Integer> listWithNull = Arrays.asList(5, 3, null, 9); try { Ordering.natural().nullsFirst().immutableSortedCopy(listWithNull); fail(); } catch (NullPointerException expected) { } } public void testIsOrdered() { assertFalse(numberOrdering.isOrdered(asList(5, 3, 0, 9))); assertFalse(numberOrdering.isOrdered(asList(0, 5, 3, 9))); assertTrue(numberOrdering.isOrdered(asList(0, 3, 5, 9))); assertTrue(numberOrdering.isOrdered(asList(0, 0, 3, 3))); assertTrue(numberOrdering.isOrdered(asList(0, 3))); assertTrue(numberOrdering.isOrdered(Collections.singleton(1))); assertTrue(numberOrdering.isOrdered(Collections.<Integer>emptyList())); } public void testIsStrictlyOrdered() { assertFalse(numberOrdering.isStrictlyOrdered(asList(5, 3, 0, 9))); assertFalse(numberOrdering.isStrictlyOrdered(asList(0, 5, 3, 9))); assertTrue(numberOrdering.isStrictlyOrdered(asList(0, 3, 5, 9))); assertFalse(numberOrdering.isStrictlyOrdered(asList(0, 0, 3, 3))); assertTrue(numberOrdering.isStrictlyOrdered(asList(0, 3))); assertTrue(numberOrdering.isStrictlyOrdered(Collections.singleton(1))); assertTrue(numberOrdering.isStrictlyOrdered( Collections.<Integer>emptyList())); } public void testLeastOfIterable_empty_0() { List<Integer> result = numberOrdering.leastOf(Arrays.<Integer>asList(), 0); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterator_empty_0() { List<Integer> result = numberOrdering.leastOf( Iterators.<Integer>emptyIterator(), 0); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterable_empty_1() { List<Integer> result = numberOrdering.leastOf(Arrays.<Integer>asList(), 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterator_empty_1() { List<Integer> result = numberOrdering.leastOf( Iterators.<Integer>emptyIterator(), 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterable_simple_negativeOne() { try { numberOrdering.leastOf(Arrays.asList(3, 4, 5, -1), -1); fail(); } catch (IllegalArgumentException expected) { } } public void testLeastOfIterator_simple_negativeOne() { try { numberOrdering.leastOf(Iterators.forArray(3, 4, 5, -1), -1); fail(); } catch (IllegalArgumentException expected) { } } public void testLeastOfIterable_singleton_0() { List<Integer> result = numberOrdering.leastOf(Arrays.asList(3), 0); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterator_singleton_0() { List<Integer> result = numberOrdering.leastOf( Iterators.singletonIterator(3), 0); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterable_simple_0() { List<Integer> result = numberOrdering.leastOf(Arrays.asList(3, 4, 5, -1), 0); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterator_simple_0() { List<Integer> result = numberOrdering.leastOf( Iterators.forArray(3, 4, 5, -1), 0); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.<Integer>of(), result); } public void testLeastOfIterable_simple_1() { List<Integer> result = numberOrdering.leastOf(Arrays.asList(3, 4, 5, -1), 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1), result); } public void testLeastOfIterator_simple_1() { List<Integer> result = numberOrdering.leastOf( Iterators.forArray(3, 4, 5, -1), 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1), result); } public void testLeastOfIterable_simple_nMinusOne_withNullElement() { List<Integer> list = Arrays.asList(3, null, 5, -1); List<Integer> result = Ordering.natural().nullsLast().leastOf(list, list.size() - 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 5), result); } public void testLeastOfIterator_simple_nMinusOne_withNullElement() { Iterator<Integer> itr = Iterators.forArray(3, null, 5, -1); List<Integer> result = Ordering.natural().nullsLast().leastOf(itr, 3); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 5), result); } public void testLeastOfIterable_simple_nMinusOne() { List<Integer> list = Arrays.asList(3, 4, 5, -1); List<Integer> result = numberOrdering.leastOf(list, list.size() - 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 4), result); } public void testLeastOfIterator_simple_nMinusOne() { List<Integer> list = Arrays.asList(3, 4, 5, -1); List<Integer> result = numberOrdering.leastOf(list.iterator(), list.size() - 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 4), result); } public void testLeastOfIterable_simple_n() { List<Integer> list = Arrays.asList(3, 4, 5, -1); List<Integer> result = numberOrdering.leastOf(list, list.size()); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 4, 5), result); } public void testLeastOfIterator_simple_n() { List<Integer> list = Arrays.asList(3, 4, 5, -1); List<Integer> result = numberOrdering.leastOf(list.iterator(), list.size()); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 4, 5), result); } public void testLeastOfIterable_simple_n_withNullElement() { List<Integer> list = Arrays.asList(3, 4, 5, null, -1); List<Integer> result = Ordering.natural().nullsLast().leastOf(list, list.size()); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(Arrays.asList(-1, 3, 4, 5, null), result); } public void testLeastOfIterator_simple_n_withNullElement() { List<Integer> list = Arrays.asList(3, 4, 5, null, -1); List<Integer> result = Ordering.natural().nullsLast().leastOf( list.iterator(), list.size()); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(Arrays.asList(-1, 3, 4, 5, null), result); } public void testLeastOfIterable_simple_nPlusOne() { List<Integer> list = Arrays.asList(3, 4, 5, -1); List<Integer> result = numberOrdering.leastOf(list, list.size() + 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 4, 5), result); } public void testLeastOfIterator_simple_nPlusOne() { List<Integer> list = Arrays.asList(3, 4, 5, -1); List<Integer> result = numberOrdering.leastOf(list.iterator(), list.size() + 1); assertTrue(result instanceof RandomAccess); assertListImmutable(result); assertEquals(ImmutableList.of(-1, 3, 4, 5), result); } public void testLeastOfIterable_ties() { Integer foo = new Integer(Integer.MAX_VALUE - 10); Integer bar = new Integer(Integer.MAX_VALUE - 10); assertNotSame(foo, bar); assertEquals(foo, bar); List<Integer> list = Arrays.asList(3, foo, bar, -1); List<Integer> result = numberOrdering.leastOf(list, list.size()); assertEquals(ImmutableList.of(-1, 3, foo, bar), result); } public void testLeastOfIterator_ties() { Integer foo = new Integer(Integer.MAX_VALUE - 10); Integer bar = new Integer(Integer.MAX_VALUE - 10); assertNotSame(foo, bar); assertEquals(foo, bar); List<Integer> list = Arrays.asList(3, foo, bar, -1); List<Integer> result = numberOrdering.leastOf(list.iterator(), list.size()); assertEquals(ImmutableList.of(-1, 3, foo, bar), result); } public void testLeastOf_reconcileAgainstSortAndSublistSmall() { runLeastOfComparison(10, 30, 2); } private static void runLeastOfComparison( int iterations, int elements, int seeds) { Random random = new Random(42); Ordering<Integer> ordering = Ordering.natural(); for (int i = 0; i < iterations; i++) { List<Integer> list = Lists.newArrayList(); for (int j = 0; j < elements; j++) { list.add(random.nextInt(10 * i + j + 1)); } for (int seed = 1; seed < seeds; seed++) { int k = random.nextInt(10 * seed); assertEquals(ordering.sortedCopy(list).subList(0, k), ordering.leastOf(list, k)); } } } public void testLeastOfIterableLargeK() { List<Integer> list = Arrays.asList(4, 2, 3, 5, 1); assertEquals(Arrays.asList(1, 2, 3, 4, 5), Ordering.natural() .leastOf(list, Integer.MAX_VALUE)); } public void testLeastOfIteratorLargeK() { List<Integer> list = Arrays.asList(4, 2, 3, 5, 1); assertEquals(Arrays.asList(1, 2, 3, 4, 5), Ordering.natural() .leastOf(list.iterator(), Integer.MAX_VALUE)); } public void testGreatestOfIterable_simple() { /* * If greatestOf() promised to be implemented as reverse().leastOf(), this * test would be enough. It doesn't... but we'll cheat and act like it does * anyway. There's a comment there to remind us to fix this if we change it. */ List<Integer> list = Arrays.asList(3, 1, 3, 2, 4, 2, 4, 3); assertEquals(Arrays.asList(4, 4, 3, 3), numberOrdering.greatestOf(list, 4)); } public void testGreatestOfIterator_simple() { /* * If greatestOf() promised to be implemented as reverse().leastOf(), this * test would be enough. It doesn't... but we'll cheat and act like it does * anyway. There's a comment there to remind us to fix this if we change it. */ List<Integer> list = Arrays.asList(3, 1, 3, 2, 4, 2, 4, 3); assertEquals(Arrays.asList(4, 4, 3, 3), numberOrdering.greatestOf(list.iterator(), 4)); } private static void assertListImmutable(List<Integer> result) { try { result.set(0, 1); fail(); } catch (UnsupportedOperationException expected) { // pass } } public void testIteratorMinAndMax() { List<Integer> ints = Lists.newArrayList(5, 3, 0, 9); assertEquals(9, (int) numberOrdering.max(ints.iterator())); assertEquals(0, (int) numberOrdering.min(ints.iterator())); // when the values are the same, the first argument should be returned Integer a = new Integer(4); Integer b = new Integer(4); ints = Lists.newArrayList(a, b, b); assertSame(a, numberOrdering.max(ints.iterator())); assertSame(a, numberOrdering.min(ints.iterator())); } public void testIteratorMinExhaustsIterator() { List<Integer> ints = Lists.newArrayList(9, 0, 3, 5); Iterator<Integer> iterator = ints.iterator(); assertEquals(0, (int) numberOrdering.min(iterator)); assertFalse(iterator.hasNext()); } public void testIteratorMaxExhaustsIterator() { List<Integer> ints = Lists.newArrayList(9, 0, 3, 5); Iterator<Integer> iterator = ints.iterator(); assertEquals(9, (int) numberOrdering.max(iterator)); assertFalse(iterator.hasNext()); } public void testIterableMinAndMax() { List<Integer> ints = Lists.newArrayList(5, 3, 0, 9); assertEquals(9, (int) numberOrdering.max(ints)); assertEquals(0, (int) numberOrdering.min(ints)); // when the values are the same, the first argument should be returned Integer a = new Integer(4); Integer b = new Integer(4); ints = Lists.newArrayList(a, b, b); assertSame(a, numberOrdering.max(ints)); assertSame(a, numberOrdering.min(ints)); } public void testVarargsMinAndMax() { // try the min and max values in all positions, since some values are proper // parameters and others are from the varargs array assertEquals(9, (int) numberOrdering.max(9, 3, 0, 5, 8)); assertEquals(9, (int) numberOrdering.max(5, 9, 0, 3, 8)); assertEquals(9, (int) numberOrdering.max(5, 3, 9, 0, 8)); assertEquals(9, (int) numberOrdering.max(5, 3, 0, 9, 8)); assertEquals(9, (int) numberOrdering.max(5, 3, 0, 8, 9)); assertEquals(0, (int) numberOrdering.min(0, 3, 5, 9, 8)); assertEquals(0, (int) numberOrdering.min(5, 0, 3, 9, 8)); assertEquals(0, (int) numberOrdering.min(5, 3, 0, 9, 8)); assertEquals(0, (int) numberOrdering.min(5, 3, 9, 0, 8)); assertEquals(0, (int) numberOrdering.min(5, 3, 0, 9, 0)); // when the values are the same, the first argument should be returned Integer a = new Integer(4); Integer b = new Integer(4); assertSame(a, numberOrdering.max(a, b, b)); assertSame(a, numberOrdering.min(a, b, b)); } public void testParameterMinAndMax() { assertEquals(5, (int) numberOrdering.max(3, 5)); assertEquals(5, (int) numberOrdering.max(5, 3)); assertEquals(3, (int) numberOrdering.min(3, 5)); assertEquals(3, (int) numberOrdering.min(5, 3)); // when the values are the same, the first argument should be returned Integer a = new Integer(4); Integer b = new Integer(4); assertSame(a, numberOrdering.max(a, b)); assertSame(a, numberOrdering.min(a, b)); } private static class NumberOrdering extends Ordering<Number> { @Override public int compare(Number a, Number b) { return ((Double) a.doubleValue()).compareTo(b.doubleValue()); } @Override public int hashCode() { return NumberOrdering.class.hashCode(); } @Override public boolean equals(Object other) { return other instanceof NumberOrdering; } private static final long serialVersionUID = 0; } /* * Now we have monster tests that create hundreds of Orderings using different * combinations of methods, then checks compare(), binarySearch() and so * forth on each one. */ // should periodically try increasing this, but it makes the test run long private static final int RECURSE_DEPTH = 2; public void testCombinationsExhaustively_startingFromNatural() { testExhaustively(Ordering.<String>natural(), "a", "b", "d"); } /** * Requires at least 3 elements in {@code strictlyOrderedElements} in order to * test the varargs version of min/max. */ private static <T> void testExhaustively( Ordering<? super T> ordering, T... strictlyOrderedElements) { checkArgument(strictlyOrderedElements.length >= 3, "strictlyOrderedElements " + "requires at least 3 elements"); List<T> list = Arrays.asList(strictlyOrderedElements); // for use calling Collection.toArray later T[] emptyArray = Platform.newArray(strictlyOrderedElements, 0); // shoot me, but I didn't want to deal with wildcards through the whole test @SuppressWarnings("unchecked") Scenario<T> starter = new Scenario<T>((Ordering) ordering, list, emptyArray); verifyScenario(starter, 0); } private static <T> void verifyScenario(Scenario<T> scenario, int level) { scenario.testCompareTo(); scenario.testIsOrdered(); scenario.testMinAndMax(); scenario.testBinarySearch(); scenario.testSortedCopy(); if (level < RECURSE_DEPTH) { for (OrderingMutation alteration : OrderingMutation.values()) { verifyScenario(alteration.mutate(scenario), level + 1); } } } /** * An aggregation of an ordering with a list (of size > 1) that should prove * to be in strictly increasing order according to that ordering. */ private static class Scenario<T> { final Ordering<T> ordering; final List<T> strictlyOrderedList; final T[] emptyArray; Scenario(Ordering<T> ordering, List<T> strictlyOrderedList, T[] emptyArray) { this.ordering = ordering; this.strictlyOrderedList = strictlyOrderedList; this.emptyArray = emptyArray; } void testCompareTo() { Helpers.testComparator(ordering, strictlyOrderedList); } void testIsOrdered() { assertTrue(ordering.isOrdered(strictlyOrderedList)); assertTrue(ordering.isStrictlyOrdered(strictlyOrderedList)); } @SuppressWarnings("unchecked") // generic arrays and unchecked cast void testMinAndMax() { List<T> shuffledList = Lists.newArrayList(strictlyOrderedList); shuffledList = shuffledCopy(shuffledList, new Random(5)); T min = strictlyOrderedList.get(0); T max = strictlyOrderedList.get(strictlyOrderedList.size() - 1); T first = shuffledList.get(0); T second = shuffledList.get(1); T third = shuffledList.get(2); T[] rest = shuffledList.subList(3, shuffledList.size()).toArray(emptyArray); assertEquals(min, ordering.min(shuffledList)); assertEquals(min, ordering.min(shuffledList.iterator())); assertEquals(min, ordering.min(first, second, third, rest)); assertEquals(min, ordering.min(min, max)); assertEquals(min, ordering.min(max, min)); assertEquals(max, ordering.max(shuffledList)); assertEquals(max, ordering.max(shuffledList.iterator())); assertEquals(max, ordering.max(first, second, third, rest)); assertEquals(max, ordering.max(min, max)); assertEquals(max, ordering.max(max, min)); } void testBinarySearch() { for (int i = 0; i < strictlyOrderedList.size(); i++) { assertEquals(i, ordering.binarySearch( strictlyOrderedList, strictlyOrderedList.get(i))); } List<T> newList = Lists.newArrayList(strictlyOrderedList); T valueNotInList = newList.remove(1); assertEquals(-2, ordering.binarySearch(newList, valueNotInList)); } void testSortedCopy() { List<T> shuffledList = Lists.newArrayList(strictlyOrderedList); shuffledList = shuffledCopy(shuffledList, new Random(5)); assertEquals(strictlyOrderedList, ordering.sortedCopy(shuffledList)); if (!strictlyOrderedList.contains(null)) { assertEquals(strictlyOrderedList, ordering.immutableSortedCopy(shuffledList)); } } } /** * A means for changing an Ordering into another Ordering. Each instance is * responsible for creating the alternate Ordering, and providing a List that * is known to be ordered, based on an input List known to be ordered * according to the input Ordering. */ private enum OrderingMutation { REVERSE { @Override <T> Scenario<?> mutate(Scenario<T> scenario) { List<T> newList = Lists.newArrayList(scenario.strictlyOrderedList); Collections.reverse(newList); return new Scenario<T>(scenario.ordering.reverse(), newList, scenario.emptyArray); } }, NULLS_FIRST { @Override <T> Scenario<?> mutate(Scenario<T> scenario) { @SuppressWarnings("unchecked") List<T> newList = Lists.newArrayList((T) null); for (T t : scenario.strictlyOrderedList) { if (t != null) { newList.add(t); } } return new Scenario<T>(scenario.ordering.nullsFirst(), newList, scenario.emptyArray); } }, NULLS_LAST { @Override <T> Scenario<?> mutate(Scenario<T> scenario) { List<T> newList = Lists.newArrayList(); for (T t : scenario.strictlyOrderedList) { if (t != null) { newList.add(t); } } newList.add(null); return new Scenario<T>(scenario.ordering.nullsLast(), newList, scenario.emptyArray); } }, ON_RESULT_OF { @Override <T> Scenario<?> mutate(final Scenario<T> scenario) { Ordering<Integer> ordering = scenario.ordering.onResultOf( new Function<Integer, T>() { @Override public T apply(@Nullable Integer from) { return scenario.strictlyOrderedList.get(from); } }); List<Integer> list = Lists.newArrayList(); for (int i = 0; i < scenario.strictlyOrderedList.size(); i++) { list.add(i); } return new Scenario<Integer>(ordering, list, new Integer[0]); } }, COMPOUND_THIS_WITH_NATURAL { @SuppressWarnings("unchecked") // raw array @Override <T> Scenario<?> mutate(Scenario<T> scenario) { List<Composite<T>> composites = Lists.newArrayList(); for (T t : scenario.strictlyOrderedList) { composites.add(new Composite<T>(t, 1)); composites.add(new Composite<T>(t, 2)); } Ordering<Composite<T>> ordering = scenario.ordering.onResultOf(Composite.<T>getValueFunction()) .compound(Ordering.natural()); return new Scenario<Composite<T>>(ordering, composites, new Composite[0]); } }, COMPOUND_NATURAL_WITH_THIS { @SuppressWarnings("unchecked") // raw array @Override <T> Scenario<?> mutate(Scenario<T> scenario) { List<Composite<T>> composites = Lists.newArrayList(); for (T t : scenario.strictlyOrderedList) { composites.add(new Composite<T>(t, 1)); } for (T t : scenario.strictlyOrderedList) { composites.add(new Composite<T>(t, 2)); } Ordering<Composite<T>> ordering = Ordering.natural().compound( scenario.ordering.onResultOf(Composite.<T>getValueFunction())); return new Scenario<Composite<T>>(ordering, composites, new Composite[0]); } }, LEXICOGRAPHICAL { @SuppressWarnings("unchecked") // dang varargs @Override <T> Scenario<?> mutate(Scenario<T> scenario) { List<Iterable<T>> words = Lists.newArrayList(); words.add(Collections.<T>emptyList()); for (T t : scenario.strictlyOrderedList) { words.add(Arrays.asList(t)); for (T s : scenario.strictlyOrderedList) { words.add(Arrays.asList(t, s)); } } return new Scenario<Iterable<T>>( scenario.ordering.lexicographical(), words, new Iterable[0]); } }, ; abstract <T> Scenario<?> mutate(Scenario<T> scenario); } /** * A dummy object we create so that we can have something meaningful to have * a compound ordering over. */ private static class Composite<T> implements Comparable<Composite<T>> { final T value; final int rank; Composite(T value, int rank) { this.value = value; this.rank = rank; } // natural order is by rank only; the test will compound() this with the // order of 't'. @Override public int compareTo(Composite<T> that) { return Ints.compare(rank, that.rank); } static <T> Function<Composite<T>, T> getValueFunction() { return new Function<Composite<T>, T>() { @Override public T apply(Composite<T> from) { return from.value; } }; } } private static <T> List<T> shuffledCopy(List<T> in, Random random) { List<T> mutable = newArrayList(in); List<T> out = newArrayList(); while (!mutable.isEmpty()) { out.add(mutable.remove(random.nextInt(mutable.size()))); } return out; } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/OrderingTest.java
Java
asf20
38,792
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableSetMultimap.Builder; import com.google.common.collect.testing.google.UnmodifiableCollectionTests; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collections; import java.util.Map.Entry; /** * Tests for {@link ImmutableSetMultimap}. * * @author Mike Ward */ @GwtCompatible(emulated = true) public class ImmutableSetMultimapTest extends TestCase { public void testBuilder_withImmutableEntry() { ImmutableSetMultimap<String, Integer> multimap = new Builder<String, Integer>() .put(Maps.immutableEntry("one", 1)) .build(); assertEquals(ImmutableSet.of(1), multimap.get("one")); } public void testBuilder_withImmutableEntryAndNullContents() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(Maps.immutableEntry("one", (Integer) null)); fail(); } catch (NullPointerException expected) { } try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) { } } private static class StringHolder { String string; } public void testBuilder_withMutableEntry() { ImmutableSetMultimap.Builder<String, Integer> builder = new Builder<String, Integer>(); final StringHolder holder = new StringHolder(); holder.string = "one"; Entry<String, Integer> entry = new AbstractMapEntry<String, Integer>() { @Override public String getKey() { return holder.string; } @Override public Integer getValue() { return 1; } }; builder.put(entry); holder.string = "two"; assertEquals(ImmutableSet.of(1), builder.build().get("one")); } public void testBuilderPutAllIterable() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.putAll("foo", Arrays.asList(1, 2, 3)); builder.putAll("bar", Arrays.asList(4, 5)); builder.putAll("foo", Arrays.asList(6, 7)); Multimap<String, Integer> multimap = builder.build(); assertEquals(ImmutableSet.of(1, 2, 3, 6, 7), multimap.get("foo")); assertEquals(ImmutableSet.of(4, 5), multimap.get("bar")); assertEquals(7, multimap.size()); } public void testBuilderPutAllVarargs() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.putAll("foo", 1, 2, 3); builder.putAll("bar", 4, 5); builder.putAll("foo", 6, 7); Multimap<String, Integer> multimap = builder.build(); assertEquals(ImmutableSet.of(1, 2, 3, 6, 7), multimap.get("foo")); assertEquals(ImmutableSet.of(4, 5), multimap.get("bar")); assertEquals(7, multimap.size()); } public void testBuilderPutAllMultimap() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put("foo", 1); toPut.put("bar", 4); toPut.put("foo", 2); toPut.put("foo", 3); Multimap<String, Integer> moreToPut = LinkedListMultimap.create(); moreToPut.put("foo", 6); moreToPut.put("bar", 5); moreToPut.put("foo", 7); ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.putAll(toPut); builder.putAll(moreToPut); Multimap<String, Integer> multimap = builder.build(); assertEquals(ImmutableSet.of(1, 2, 3, 6, 7), multimap.get("foo")); assertEquals(ImmutableSet.of(4, 5), multimap.get("bar")); assertEquals(7, multimap.size()); } public void testBuilderPutAllWithDuplicates() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.putAll("foo", 1, 2, 3); builder.putAll("bar", 4, 5); builder.putAll("foo", 1, 6, 7); ImmutableSetMultimap<String, Integer> multimap = builder.build(); assertEquals(7, multimap.size()); } public void testBuilderPutWithDuplicates() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.putAll("foo", 1, 2, 3); builder.putAll("bar", 4, 5); builder.put("foo", 1); ImmutableSetMultimap<String, Integer> multimap = builder.build(); assertEquals(5, multimap.size()); } public void testBuilderPutAllMultimapWithDuplicates() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put("foo", 1); toPut.put("bar", 4); toPut.put("foo", 2); toPut.put("foo", 1); toPut.put("bar", 5); ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.putAll(toPut); ImmutableSetMultimap<String, Integer> multimap = builder.build(); assertEquals(4, multimap.size()); } public void testBuilderPutNullKey() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put("foo", null); ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); try { builder.put(null, 1); fail(); } catch (NullPointerException expected) {} try { builder.putAll(null, Arrays.asList(1, 2, 3)); fail(); } catch (NullPointerException expected) {} try { builder.putAll(null, 1, 2, 3); fail(); } catch (NullPointerException expected) {} try { builder.putAll(toPut); fail(); } catch (NullPointerException expected) {} } public void testBuilderPutNullValue() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put(null, 1); ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); try { builder.put("foo", null); fail(); } catch (NullPointerException expected) {} try { builder.putAll("foo", Arrays.asList(1, null, 3)); fail(); } catch (NullPointerException expected) {} try { builder.putAll("foo", 4, null, 6); fail(); } catch (NullPointerException expected) {} try { builder.putAll(toPut); fail(); } catch (NullPointerException expected) {} } public void testBuilderOrderKeysBy() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.put("b", 3); builder.put("d", 2); builder.put("a", 5); builder.orderKeysBy(Collections.reverseOrder()); builder.put("c", 4); builder.put("a", 2); builder.put("b", 6); ImmutableSetMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); ASSERT.that(multimap.values()).has().exactly(2, 4, 3, 6, 5, 2).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("b")).has().exactly(3, 6).inOrder(); assertFalse(multimap.get("a") instanceof ImmutableSortedSet); assertFalse(multimap.get("x") instanceof ImmutableSortedSet); assertFalse(multimap.asMap().get("a") instanceof ImmutableSortedSet); } public void testBuilderOrderKeysByDuplicates() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.put("bb", 3); builder.put("d", 2); builder.put("a", 5); builder.orderKeysBy(new Ordering<String>() { @Override public int compare(String left, String right) { return left.length() - right.length(); } }); builder.put("cc", 4); builder.put("a", 2); builder.put("bb", 6); ImmutableSetMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("d", "a", "bb", "cc").inOrder(); ASSERT.that(multimap.values()).has().exactly(2, 5, 2, 3, 6, 4).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("bb")).has().exactly(3, 6).inOrder(); assertFalse(multimap.get("a") instanceof ImmutableSortedSet); assertFalse(multimap.get("x") instanceof ImmutableSortedSet); assertFalse(multimap.asMap().get("a") instanceof ImmutableSortedSet); } public void testBuilderOrderValuesBy() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.put("b", 3); builder.put("d", 2); builder.put("a", 5); builder.orderValuesBy(Collections.reverseOrder()); builder.put("c", 4); builder.put("a", 2); builder.put("b", 6); ImmutableSetMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("b", "d", "a", "c").inOrder(); ASSERT.that(multimap.values()).has().exactly(6, 3, 2, 5, 2, 4).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("b")).has().exactly(6, 3).inOrder(); assertTrue(multimap.get("a") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.get("a")).comparator()); assertTrue(multimap.get("x") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.get("x")).comparator()); assertTrue(multimap.asMap().get("a") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.asMap().get("a")).comparator()); } public void testBuilderOrderKeysAndValuesBy() { ImmutableSetMultimap.Builder<String, Integer> builder = ImmutableSetMultimap.builder(); builder.put("b", 3); builder.put("d", 2); builder.put("a", 5); builder.orderKeysBy(Collections.reverseOrder()); builder.orderValuesBy(Collections.reverseOrder()); builder.put("c", 4); builder.put("a", 2); builder.put("b", 6); ImmutableSetMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); ASSERT.that(multimap.values()).has().exactly(2, 4, 6, 3, 5, 2).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("b")).has().exactly(6, 3).inOrder(); assertTrue(multimap.get("a") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.get("a")).comparator()); assertTrue(multimap.get("x") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.get("x")).comparator()); assertTrue(multimap.asMap().get("a") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.asMap().get("a")).comparator()); } public void testCopyOf() { HashMultimap<String, Integer> input = HashMultimap.create(); input.put("foo", 1); input.put("bar", 2); input.put("foo", 3); Multimap<String, Integer> multimap = ImmutableSetMultimap.copyOf(input); assertEquals(multimap, input); assertEquals(input, multimap); } public void testCopyOfWithDuplicates() { ArrayListMultimap<Object, Object> input = ArrayListMultimap.create(); input.put("foo", 1); input.put("bar", 2); input.put("foo", 3); input.put("foo", 1); ImmutableSetMultimap<Object, Object> copy = ImmutableSetMultimap.copyOf(input); assertEquals(3, copy.size()); } public void testCopyOfEmpty() { HashMultimap<String, Integer> input = HashMultimap.create(); Multimap<String, Integer> multimap = ImmutableSetMultimap.copyOf(input); assertEquals(multimap, input); assertEquals(input, multimap); } public void testCopyOfImmutableSetMultimap() { Multimap<String, Integer> multimap = createMultimap(); assertSame(multimap, ImmutableSetMultimap.copyOf(multimap)); } public void testCopyOfNullKey() { HashMultimap<String, Integer> input = HashMultimap.create(); input.put(null, 1); try { ImmutableSetMultimap.copyOf(input); fail(); } catch (NullPointerException expected) {} } public void testCopyOfNullValue() { HashMultimap<String, Integer> input = HashMultimap.create(); input.putAll("foo", Arrays.asList(1, null, 3)); try { ImmutableSetMultimap.copyOf(input); fail(); } catch (NullPointerException expected) {} } public void testEmptyMultimapReads() { Multimap<String, Integer> multimap = ImmutableSetMultimap.of(); assertFalse(multimap.containsKey("foo")); assertFalse(multimap.containsValue(1)); assertFalse(multimap.containsEntry("foo", 1)); assertTrue(multimap.entries().isEmpty()); assertTrue(multimap.equals(HashMultimap.create())); assertEquals(Collections.emptySet(), multimap.get("foo")); assertEquals(0, multimap.hashCode()); assertTrue(multimap.isEmpty()); assertEquals(HashMultiset.create(), multimap.keys()); assertEquals(Collections.emptySet(), multimap.keySet()); assertEquals(0, multimap.size()); assertTrue(multimap.values().isEmpty()); assertEquals("{}", multimap.toString()); } public void testEmptyMultimapWrites() { Multimap<String, Integer> multimap = ImmutableSetMultimap.of(); UnmodifiableCollectionTests.assertMultimapIsUnmodifiable( multimap, "foo", 1); } public void testMultimapReads() { Multimap<String, Integer> multimap = createMultimap(); assertTrue(multimap.containsKey("foo")); assertFalse(multimap.containsKey("cat")); assertTrue(multimap.containsValue(1)); assertFalse(multimap.containsValue(5)); assertTrue(multimap.containsEntry("foo", 1)); assertFalse(multimap.containsEntry("cat", 1)); assertFalse(multimap.containsEntry("foo", 5)); assertFalse(multimap.entries().isEmpty()); assertEquals(3, multimap.size()); assertFalse(multimap.isEmpty()); assertEquals("{foo=[1, 3], bar=[2]}", multimap.toString()); } public void testMultimapWrites() { Multimap<String, Integer> multimap = createMultimap(); UnmodifiableCollectionTests.assertMultimapIsUnmodifiable( multimap, "bar", 2); } public void testMultimapEquals() { Multimap<String, Integer> multimap = createMultimap(); Multimap<String, Integer> hashMultimap = HashMultimap.create(); hashMultimap.putAll("foo", Arrays.asList(1, 3)); hashMultimap.put("bar", 2); new EqualsTester() .addEqualityGroup( multimap, createMultimap(), hashMultimap, ImmutableSetMultimap.<String, Integer>builder() .put("bar", 2).put("foo", 1).put("foo", 3).build(), ImmutableSetMultimap.<String, Integer>builder() .put("bar", 2).put("foo", 3).put("foo", 1).build()) .addEqualityGroup(ImmutableSetMultimap.<String, Integer>builder() .put("foo", 2).put("foo", 3).put("foo", 1).build()) .addEqualityGroup(ImmutableSetMultimap.<String, Integer>builder() .put("bar", 2).put("foo", 3).build()) .testEquals(); } public void testOf() { assertMultimapEquals( ImmutableSetMultimap.of("one", 1), "one", 1); assertMultimapEquals( ImmutableSetMultimap.of("one", 1, "two", 2), "one", 1, "two", 2); assertMultimapEquals( ImmutableSetMultimap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3); assertMultimapEquals( ImmutableSetMultimap.of("one", 1, "two", 2, "three", 3, "four", 4), "one", 1, "two", 2, "three", 3, "four", 4); assertMultimapEquals( ImmutableSetMultimap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); } public void testInverse() { assertEquals( ImmutableSetMultimap.<Integer, String>of(), ImmutableSetMultimap.<String, Integer>of().inverse()); assertEquals( ImmutableSetMultimap.of(1, "one"), ImmutableSetMultimap.of("one", 1).inverse()); assertEquals( ImmutableSetMultimap.of(1, "one", 2, "two"), ImmutableSetMultimap.of("one", 1, "two", 2).inverse()); assertEquals( ImmutableSetMultimap.of('o', "of", 'f', "of", 't', "to", 'o', "to"), ImmutableSetMultimap.of("of", 'o', "of", 'f', "to", 't', "to", 'o').inverse()); } public void testInverseMinimizesWork() { ImmutableSetMultimap<String, Character> multimap = ImmutableSetMultimap.of("of", 'o', "of", 'f', "to", 't', "to", 'o'); assertSame(multimap.inverse(), multimap.inverse()); assertSame(multimap, multimap.inverse().inverse()); } private static <K, V> void assertMultimapEquals(Multimap<K, V> multimap, Object... alternatingKeysAndValues) { assertEquals(multimap.size(), alternatingKeysAndValues.length / 2); int i = 0; for (Entry<K, V> entry : multimap.entries()) { assertEquals(alternatingKeysAndValues[i++], entry.getKey()); assertEquals(alternatingKeysAndValues[i++], entry.getValue()); } } private ImmutableSetMultimap<String, Integer> createMultimap() { return ImmutableSetMultimap.<String, Integer>builder() .put("foo", 1).put("bar", 2).put("foo", 3).build(); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ImmutableSetMultimapTest.java
Java
asf20
17,925
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.google.TestStringBiMapGenerator; import junit.framework.TestCase; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Tests for {@link HashBiMap}. * * @author Mike Bostock */ @GwtCompatible(emulated = true) public class HashBiMapTest extends TestCase { public static final class HashBiMapGenerator extends TestStringBiMapGenerator { @Override protected BiMap<String, String> create(Entry<String, String>[] entries) { BiMap<String, String> result = HashBiMap.create(); for (Entry<String, String> entry : entries) { result.put(entry.getKey(), entry.getValue()); } return result; } } public void testMapConstructor() { /* Test with non-empty Map. */ Map<String, String> map = ImmutableMap.of( "canada", "dollar", "chile", "peso", "switzerland", "franc"); HashBiMap<String, String> bimap = HashBiMap.create(map); assertEquals("dollar", bimap.get("canada")); assertEquals("canada", bimap.inverse().get("dollar")); } private static final int N = 1000; public void testBashIt() throws Exception { BiMap<Integer, Integer> bimap = HashBiMap.create(N); BiMap<Integer, Integer> inverse = bimap.inverse(); for (int i = 0; i < N; i++) { assertNull(bimap.put(2 * i, 2 * i + 1)); } for (int i = 0; i < N; i++) { assertEquals(2 * i + 1, (int) bimap.get(2 * i)); } for (int i = 0; i < N; i++) { assertEquals(2 * i, (int) inverse.get(2 * i + 1)); } for (int i = 0; i < N; i++) { int oldValue = bimap.get(2 * i); assertEquals(2 * i + 1, (int) bimap.put(2 * i, oldValue - 2)); } for (int i = 0; i < N; i++) { assertEquals(2 * i - 1, (int) bimap.get(2 * i)); } for (int i = 0; i < N; i++) { assertEquals(2 * i, (int) inverse.get(2 * i - 1)); } Set<Entry<Integer, Integer>> entries = bimap.entrySet(); for (Entry<Integer, Integer> entry : entries) { entry.setValue(entry.getValue() + 2 * N); } for (int i = 0; i < N; i++) { assertEquals(2 * N + 2 * i - 1, (int) bimap.get(2 * i)); } } public void testBiMapEntrySetIteratorRemove() { BiMap<Integer, String> map = HashBiMap.create(); map.put(1, "one"); Set<Map.Entry<Integer, String>> entries = map.entrySet(); Iterator<Map.Entry<Integer, String>> iterator = entries.iterator(); Map.Entry<Integer, String> entry = iterator.next(); entry.setValue("two"); // changes the iterator's current entry value assertEquals("two", map.get(1)); assertEquals(Integer.valueOf(1), map.inverse().get("two")); iterator.remove(); // removes the updated entry assertTrue(map.isEmpty()); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/HashBiMapTest.java
Java
asf20
3,472
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; /** * Tests common methods in {@link ImmutableTable} * * @author Gregory Kick */ @GwtCompatible(emulated = true) public class ImmutableTableTest extends AbstractTableReadTest { @Override protected Table<String, Integer, Character> create(Object... data) { ImmutableTable.Builder<String, Integer, Character> builder = ImmutableTable.builder(); for (int i = 0; i < data.length; i = i + 3) { builder.put((String) data[i], (Integer) data[i + 1], (Character) data[i + 2]); } return builder.build(); } public void testBuilder() { ImmutableTable.Builder<Character, Integer, String> builder = new ImmutableTable.Builder<Character, Integer, String>(); assertEquals(ImmutableTable.of(), builder.build()); assertEquals(ImmutableTable.of('a', 1, "foo"), builder .put('a', 1, "foo") .build()); Table<Character, Integer, String> expectedTable = HashBasedTable.create(); expectedTable.put('a', 1, "foo"); expectedTable.put('b', 1, "bar"); expectedTable.put('a', 2, "baz"); Table<Character, Integer, String> otherTable = HashBasedTable.create(); otherTable.put('b', 1, "bar"); otherTable.put('a', 2, "baz"); assertEquals(expectedTable, builder .putAll(otherTable) .build()); } public void testBuilder_withImmutableCell() { ImmutableTable.Builder<Character, Integer, String> builder = new ImmutableTable.Builder<Character, Integer, String>(); assertEquals(ImmutableTable.of('a', 1, "foo"), builder .put(Tables.immutableCell('a', 1, "foo")) .build()); } public void testBuilder_withImmutableCellAndNullContents() { ImmutableTable.Builder<Character, Integer, String> builder = new ImmutableTable.Builder<Character, Integer, String>(); try { builder.put(Tables.immutableCell((Character) null, 1, "foo")); fail(); } catch (NullPointerException e) { // success } try { builder.put(Tables.immutableCell('a', (Integer) null, "foo")); fail(); } catch (NullPointerException e) { // success } try { builder.put(Tables.immutableCell('a', 1, (String) null)); fail(); } catch (NullPointerException e) { // success } } private static class StringHolder { String string; } public void testBuilder_withMutableCell() { ImmutableTable.Builder<Character, Integer, String> builder = new ImmutableTable.Builder<Character, Integer, String>(); final StringHolder holder = new StringHolder(); holder.string = "foo"; Table.Cell<Character, Integer, String> mutableCell = new Tables.AbstractCell<Character, Integer, String>() { @Override public Character getRowKey() { return 'K'; } @Override public Integer getColumnKey() { return 42; } @Override public String getValue() { return holder.string; } }; // Add the mutable cell to the builder builder.put(mutableCell); // Mutate the value holder.string = "bar"; // Make sure it uses the original value. assertEquals(ImmutableTable.of('K', 42, "foo"), builder.build()); } public void testBuilder_noDuplicates() { ImmutableTable.Builder<Character, Integer, String> builder = new ImmutableTable.Builder<Character, Integer, String>() .put('a', 1, "foo") .put('a', 1, "bar"); try { builder.build(); fail(); } catch (IllegalArgumentException e) { // success } } public void testBuilder_noNulls() { ImmutableTable.Builder<Character, Integer, String> builder = new ImmutableTable.Builder<Character, Integer, String>(); try { builder.put(null, 1, "foo"); fail(); } catch (NullPointerException e) { // success } try { builder.put('a', null, "foo"); fail(); } catch (NullPointerException e) { // success } try { builder.put('a', 1, null); fail(); } catch (NullPointerException e) { // success } } private static <R, C, V> void validateTableCopies(Table<R, C, V> original) { Table<R, C, V> copy = ImmutableTable.copyOf(original); assertEquals(original, copy); validateViewOrdering(original, copy); Table<R, C, V> built = ImmutableTable.<R, C, V>builder().putAll(original).build(); assertEquals(original, built); validateViewOrdering(original, built); } private static <R, C, V> void validateViewOrdering( Table<R, C, V> original, Table<R, C, V> copy) { assertTrue(Iterables.elementsEqual(original.cellSet(), copy.cellSet())); assertTrue(Iterables.elementsEqual(original.rowKeySet(), copy.rowKeySet())); assertTrue(Iterables.elementsEqual(original.values(), copy.values())); } public void testCopyOf() { Table<Character, Integer, String> table = TreeBasedTable.create(); validateTableCopies(table); table.put('b', 2, "foo"); validateTableCopies(table); table.put('b', 1, "bar"); table.put('a', 2, "baz"); validateTableCopies(table); // Even though rowKeySet, columnKeySet, and cellSet have the same // iteration ordering, row has an inconsistent ordering. ASSERT.that(table.row('b').keySet()).has().exactly(1, 2).inOrder(); ASSERT.that(ImmutableTable.copyOf(table).row('b').keySet()) .has().exactly(2, 1).inOrder(); } public void testCopyOfSparse() { Table<Character, Integer, String> table = TreeBasedTable.create(); table.put('x', 2, "foo"); table.put('r', 1, "bar"); table.put('c', 3, "baz"); table.put('b', 7, "cat"); table.put('e', 5, "dog"); table.put('c', 0, "axe"); table.put('e', 3, "tub"); table.put('r', 4, "foo"); table.put('x', 5, "bar"); validateTableCopies(table); } public void testCopyOfDense() { Table<Character, Integer, String> table = TreeBasedTable.create(); table.put('c', 3, "foo"); table.put('c', 2, "bar"); table.put('c', 1, "baz"); table.put('b', 3, "cat"); table.put('b', 1, "dog"); table.put('a', 3, "foo"); table.put('a', 2, "bar"); table.put('a', 1, "baz"); validateTableCopies(table); } public void testBuilder_orderRowsAndColumnsBy_putAll() { Table<Character, Integer, String> table = HashBasedTable.create(); table.put('b', 2, "foo"); table.put('b', 1, "bar"); table.put('a', 2, "baz"); ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); Table<Character, Integer, String> copy = builder.orderRowsBy(Ordering.natural()) .orderColumnsBy(Ordering.natural()) .putAll(table).build(); ASSERT.that(copy.rowKeySet()).has().exactly('a', 'b').inOrder(); ASSERT.that(copy.columnKeySet()).has().exactly(1, 2).inOrder(); ASSERT.that(copy.values()).has().exactly("baz", "bar", "foo").inOrder(); ASSERT.that(copy.row('b').keySet()).has().exactly(1, 2).inOrder(); } public void testBuilder_orderRowsAndColumnsBy_sparse() { ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); builder.orderRowsBy(Ordering.natural()); builder.orderColumnsBy(Ordering.natural()); builder.put('x', 2, "foo"); builder.put('r', 1, "bar"); builder.put('c', 3, "baz"); builder.put('b', 7, "cat"); builder.put('e', 5, "dog"); builder.put('c', 0, "axe"); builder.put('e', 3, "tub"); builder.put('r', 4, "foo"); builder.put('x', 5, "bar"); Table<Character, Integer, String> table = builder.build(); ASSERT.that(table.rowKeySet()).has().exactly('b', 'c', 'e', 'r', 'x').inOrder(); ASSERT.that(table.columnKeySet()).has().exactly(0, 1, 2, 3, 4, 5, 7).inOrder(); ASSERT.that(table.values()).has().exactly("cat", "axe", "baz", "tub", "dog", "bar", "foo", "foo", "bar").inOrder(); ASSERT.that(table.row('c').keySet()).has().exactly(0, 3).inOrder(); ASSERT.that(table.column(5).keySet()).has().exactly('e', 'x').inOrder(); } public void testBuilder_orderRowsAndColumnsBy_dense() { ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); builder.orderRowsBy(Ordering.natural()); builder.orderColumnsBy(Ordering.natural()); builder.put('c', 3, "foo"); builder.put('c', 2, "bar"); builder.put('c', 1, "baz"); builder.put('b', 3, "cat"); builder.put('b', 1, "dog"); builder.put('a', 3, "foo"); builder.put('a', 2, "bar"); builder.put('a', 1, "baz"); Table<Character, Integer, String> table = builder.build(); ASSERT.that(table.rowKeySet()).has().exactly('a', 'b', 'c').inOrder(); ASSERT.that(table.columnKeySet()).has().exactly(1, 2, 3).inOrder(); ASSERT.that(table.values()).has().exactly("baz", "bar", "foo", "dog", "cat", "baz", "bar", "foo").inOrder(); ASSERT.that(table.row('c').keySet()).has().exactly(1, 2, 3).inOrder(); ASSERT.that(table.column(1).keySet()).has().exactly('a', 'b', 'c').inOrder(); } public void testBuilder_orderRowsBy_sparse() { ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); builder.orderRowsBy(Ordering.natural()); builder.put('x', 2, "foo"); builder.put('r', 1, "bar"); builder.put('c', 3, "baz"); builder.put('b', 7, "cat"); builder.put('e', 5, "dog"); builder.put('c', 0, "axe"); builder.put('e', 3, "tub"); builder.put('r', 4, "foo"); builder.put('x', 5, "bar"); Table<Character, Integer, String> table = builder.build(); ASSERT.that(table.rowKeySet()).has().exactly('b', 'c', 'e', 'r', 'x').inOrder(); ASSERT.that(table.column(5).keySet()).has().exactly('e', 'x').inOrder(); } public void testBuilder_orderRowsBy_dense() { ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); builder.orderRowsBy(Ordering.natural()); builder.put('c', 3, "foo"); builder.put('c', 2, "bar"); builder.put('c', 1, "baz"); builder.put('b', 3, "cat"); builder.put('b', 1, "dog"); builder.put('a', 3, "foo"); builder.put('a', 2, "bar"); builder.put('a', 1, "baz"); Table<Character, Integer, String> table = builder.build(); ASSERT.that(table.rowKeySet()).has().exactly('a', 'b', 'c').inOrder(); ASSERT.that(table.column(1).keySet()).has().exactly('a', 'b', 'c').inOrder(); } public void testBuilder_orderColumnsBy_sparse() { ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); builder.orderColumnsBy(Ordering.natural()); builder.put('x', 2, "foo"); builder.put('r', 1, "bar"); builder.put('c', 3, "baz"); builder.put('b', 7, "cat"); builder.put('e', 5, "dog"); builder.put('c', 0, "axe"); builder.put('e', 3, "tub"); builder.put('r', 4, "foo"); builder.put('x', 5, "bar"); Table<Character, Integer, String> table = builder.build(); ASSERT.that(table.columnKeySet()).has().exactly(0, 1, 2, 3, 4, 5, 7).inOrder(); ASSERT.that(table.row('c').keySet()).has().exactly(0, 3).inOrder(); } public void testBuilder_orderColumnsBy_dense() { ImmutableTable.Builder<Character, Integer, String> builder = ImmutableTable.builder(); builder.orderColumnsBy(Ordering.natural()); builder.put('c', 3, "foo"); builder.put('c', 2, "bar"); builder.put('c', 1, "baz"); builder.put('b', 3, "cat"); builder.put('b', 1, "dog"); builder.put('a', 3, "foo"); builder.put('a', 2, "bar"); builder.put('a', 1, "baz"); Table<Character, Integer, String> table = builder.build(); ASSERT.that(table.columnKeySet()).has().exactly(1, 2, 3).inOrder(); ASSERT.that(table.row('c').keySet()).has().exactly(1, 2, 3).inOrder(); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ImmutableTableTest.java
Java
asf20
12,595
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.testing.Helpers.orderEntriesByKey; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.google.TestBiMapGenerator; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Tests for {@code EnumBiMap}. * * @author Mike Bostock * @author Jared Levy */ @GwtCompatible(emulated = true) public class EnumBiMapTest extends TestCase { private enum Currency { DOLLAR, FRANC, PESO, POUND, YEN } private enum Country { CANADA, CHILE, JAPAN, SWITZERLAND, UK } public static final class EnumBiMapGenerator implements TestBiMapGenerator<Country, Currency> { @SuppressWarnings("unchecked") @Override public BiMap<Country, Currency> create(Object... entries) { BiMap<Country, Currency> result = EnumBiMap.create(Country.class, Currency.class); for (Object object : entries) { Entry<Country, Currency> entry = (Entry<Country, Currency>) object; result.put(entry.getKey(), entry.getValue()); } return result; } @Override public SampleElements<Entry<Country, Currency>> samples() { return new SampleElements<Entry<Country, Currency>>( Helpers.mapEntry(Country.CANADA, Currency.DOLLAR), Helpers.mapEntry(Country.CHILE, Currency.PESO), Helpers.mapEntry(Country.UK, Currency.POUND), Helpers.mapEntry(Country.JAPAN, Currency.YEN), Helpers.mapEntry(Country.SWITZERLAND, Currency.FRANC)); } @SuppressWarnings("unchecked") @Override public Entry<Country, Currency>[] createArray(int length) { return new Entry[length]; } @Override public Iterable<Entry<Country, Currency>> order(List<Entry<Country, Currency>> insertionOrder) { return orderEntriesByKey(insertionOrder); } @Override public Country[] createKeyArray(int length) { return new Country[length]; } @Override public Currency[] createValueArray(int length) { return new Currency[length]; } } public void testCreate() { EnumBiMap<Currency, Country> bimap = EnumBiMap.create(Currency.class, Country.class); assertTrue(bimap.isEmpty()); assertEquals("{}", bimap.toString()); assertEquals(HashBiMap.create(), bimap); bimap.put(Currency.DOLLAR, Country.CANADA); assertEquals(Country.CANADA, bimap.get(Currency.DOLLAR)); assertEquals(Currency.DOLLAR, bimap.inverse().get(Country.CANADA)); } public void testCreateFromMap() { /* Test with non-empty Map. */ Map<Currency, Country> map = ImmutableMap.of( Currency.DOLLAR, Country.CANADA, Currency.PESO, Country.CHILE, Currency.FRANC, Country.SWITZERLAND); EnumBiMap<Currency, Country> bimap = EnumBiMap.create(map); assertEquals(Country.CANADA, bimap.get(Currency.DOLLAR)); assertEquals(Currency.DOLLAR, bimap.inverse().get(Country.CANADA)); /* Map must have at least one entry if not an EnumBiMap. */ try { EnumBiMap.create(Collections.<Currency, Country>emptyMap()); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException expected) {} try { EnumBiMap.create( EnumHashBiMap.<Currency, Country>create(Currency.class)); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException expected) {} /* Map can be empty if it's an EnumBiMap. */ Map<Currency, Country> emptyBimap = EnumBiMap.create(Currency.class, Country.class); bimap = EnumBiMap.create(emptyBimap); assertTrue(bimap.isEmpty()); } public void testEnumBiMapConstructor() { /* Test that it copies existing entries. */ EnumBiMap<Currency, Country> bimap1 = EnumBiMap.create(Currency.class, Country.class); bimap1.put(Currency.DOLLAR, Country.CANADA); EnumBiMap<Currency, Country> bimap2 = EnumBiMap.create(bimap1); assertEquals(Country.CANADA, bimap2.get(Currency.DOLLAR)); assertEquals(bimap1, bimap2); bimap2.inverse().put(Country.SWITZERLAND, Currency.FRANC); assertEquals(Country.SWITZERLAND, bimap2.get(Currency.FRANC)); assertNull(bimap1.get(Currency.FRANC)); assertFalse(bimap2.equals(bimap1)); /* Test that it can be empty. */ EnumBiMap<Currency, Country> emptyBimap = EnumBiMap.create(Currency.class, Country.class); EnumBiMap<Currency, Country> bimap3 = EnumBiMap.create(emptyBimap); assertEquals(bimap3, emptyBimap); } public void testKeyType() { EnumBiMap<Currency, Country> bimap = EnumBiMap.create(Currency.class, Country.class); assertEquals(Currency.class, bimap.keyType()); } public void testValueType() { EnumBiMap<Currency, Country> bimap = EnumBiMap.create(Currency.class, Country.class); assertEquals(Country.class, bimap.valueType()); } public void testIterationOrder() { // The enum orderings are alphabetical, leading to the bimap and its inverse // having inconsistent iteration orderings. Map<Currency, Country> map = ImmutableMap.of( Currency.DOLLAR, Country.CANADA, Currency.PESO, Country.CHILE, Currency.FRANC, Country.SWITZERLAND); EnumBiMap<Currency, Country> bimap = EnumBiMap.create(map); // forward map ordered by currency ASSERT.that(bimap.keySet()) .has().exactly(Currency.DOLLAR, Currency.FRANC, Currency.PESO).inOrder(); // forward map ordered by currency (even for country values) ASSERT.that(bimap.values()) .has().exactly(Country.CANADA, Country.SWITZERLAND, Country.CHILE).inOrder(); // backward map ordered by country ASSERT.that(bimap.inverse().keySet()) .has().exactly(Country.CANADA, Country.CHILE, Country.SWITZERLAND).inOrder(); // backward map ordered by country (even for currency values) ASSERT.that(bimap.inverse().values()) .has().exactly(Currency.DOLLAR, Currency.PESO, Currency.FRANC).inOrder(); } public void testKeySetIteratorRemove() { // The enum orderings are alphabetical, leading to the bimap and its inverse // having inconsistent iteration orderings. Map<Currency, Country> map = ImmutableMap.of( Currency.DOLLAR, Country.CANADA, Currency.PESO, Country.CHILE, Currency.FRANC, Country.SWITZERLAND); EnumBiMap<Currency, Country> bimap = EnumBiMap.create(map); Iterator<Currency> iter = bimap.keySet().iterator(); assertEquals(Currency.DOLLAR, iter.next()); iter.remove(); // forward map ordered by currency ASSERT.that(bimap.keySet()) .has().exactly(Currency.FRANC, Currency.PESO).inOrder(); // forward map ordered by currency (even for country values) ASSERT.that(bimap.values()) .has().exactly(Country.SWITZERLAND, Country.CHILE).inOrder(); // backward map ordered by country ASSERT.that(bimap.inverse().keySet()) .has().exactly(Country.CHILE, Country.SWITZERLAND).inOrder(); // backward map ordered by country (even for currency values) ASSERT.that(bimap.inverse().values()) .has().exactly(Currency.PESO, Currency.FRANC).inOrder(); } public void testValuesIteratorRemove() { // The enum orderings are alphabetical, leading to the bimap and its inverse // having inconsistent iteration orderings. Map<Currency, Country> map = ImmutableMap.of( Currency.DOLLAR, Country.CANADA, Currency.PESO, Country.CHILE, Currency.FRANC, Country.SWITZERLAND); EnumBiMap<Currency, Country> bimap = EnumBiMap.create(map); Iterator<Currency> iter = bimap.keySet().iterator(); assertEquals(Currency.DOLLAR, iter.next()); assertEquals(Currency.FRANC, iter.next()); iter.remove(); // forward map ordered by currency ASSERT.that(bimap.keySet()) .has().exactly(Currency.DOLLAR, Currency.PESO).inOrder(); // forward map ordered by currency (even for country values) ASSERT.that(bimap.values()) .has().exactly(Country.CANADA, Country.CHILE).inOrder(); // backward map ordered by country ASSERT.that(bimap.inverse().keySet()) .has().exactly(Country.CANADA, Country.CHILE).inOrder(); // backward map ordered by country (even for currency values) ASSERT.that(bimap.inverse().values()) .has().exactly(Currency.DOLLAR, Currency.PESO).inOrder(); } public void testEntrySet() { // Bug 3168290 Map<Currency, Country> map = ImmutableMap.of( Currency.DOLLAR, Country.CANADA, Currency.PESO, Country.CHILE, Currency.FRANC, Country.SWITZERLAND); EnumBiMap<Currency, Country> bimap = EnumBiMap.create(map); Set<Object> uniqueEntries = Sets.newIdentityHashSet(); uniqueEntries.addAll(bimap.entrySet()); assertEquals(3, uniqueEntries.size()); } public void testEquals() { new EqualsTester() .addEqualityGroup( EnumBiMap.create(ImmutableMap.of(Currency.DOLLAR, Country.CANADA)), EnumBiMap.create(ImmutableMap.of(Currency.DOLLAR, Country.CANADA))) .addEqualityGroup(EnumBiMap.create(ImmutableMap.of(Currency.DOLLAR, Country.CHILE))) .addEqualityGroup(EnumBiMap.create(ImmutableMap.of(Currency.FRANC, Country.CANADA))) .testEquals(); } /* Remaining behavior tested by AbstractBiMapTest. */ }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/EnumBiMapTest.java
Java
asf20
10,237
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.google.TestStringMultisetGenerator; import junit.framework.TestCase; import java.util.Arrays; import java.util.List; /** * Unit test for {@link LinkedHashMultiset}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class LinkedHashMultisetTest extends TestCase { private static TestStringMultisetGenerator linkedHashMultisetGenerator() { return new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { return LinkedHashMultiset.create(asList(elements)); } @Override public List<String> order(List<String> insertionOrder) { List<String> order = Lists.newArrayList(); for (String s : insertionOrder) { int index = order.indexOf(s); if (index == -1) { order.add(s); } else { order.add(index, s); } } return order; } }; } public void testCreate() { Multiset<String> multiset = LinkedHashMultiset.create(); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); assertEquals("[foo x 2, bar]", multiset.toString()); } public void testCreateWithSize() { Multiset<String> multiset = LinkedHashMultiset.create(50); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); assertEquals("[foo x 2, bar]", multiset.toString()); } public void testCreateFromIterable() { Multiset<String> multiset = LinkedHashMultiset.create(Arrays.asList("foo", "bar", "foo")); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); assertEquals("[foo x 2, bar]", multiset.toString()); } public void testToString() { Multiset<String> ms = LinkedHashMultiset.create(); ms.add("a", 3); ms.add("c", 1); ms.add("b", 2); assertEquals("[a x 3, c, b x 2]", ms.toString()); } public void testLosesPlaceInLine() throws Exception { Multiset<String> ms = LinkedHashMultiset.create(); ms.add("a"); ms.add("b", 2); ms.add("c"); ASSERT.that(ms.elementSet()).has().exactly("a", "b", "c").inOrder(); ms.remove("b"); ASSERT.that(ms.elementSet()).has().exactly("a", "b", "c").inOrder(); ms.add("b"); ASSERT.that(ms.elementSet()).has().exactly("a", "b", "c").inOrder(); ms.remove("b", 2); ms.add("b"); ASSERT.that(ms.elementSet()).has().exactly("a", "c", "b").inOrder(); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/LinkedHashMultisetTest.java
Java
asf20
3,369
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AnEnum; import com.google.common.collect.testing.google.TestEnumMultisetGenerator; import junit.framework.TestCase; import java.util.Collection; import java.util.EnumSet; import java.util.Set; /** * Tests for an {@link EnumMultiset}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class EnumMultisetTest extends TestCase { private static TestEnumMultisetGenerator enumMultisetGenerator() { return new TestEnumMultisetGenerator() { @Override protected Multiset<AnEnum> create(AnEnum[] elements) { return (elements.length == 0) ? EnumMultiset.create(AnEnum.class) : EnumMultiset.create(asList(elements)); } }; } private static enum Color { BLUE, RED, YELLOW, GREEN, WHITE } public void testClassCreate() { Multiset<Color> ms = EnumMultiset.create(Color.class); ms.add(Color.RED); ms.add(Color.YELLOW); ms.add(Color.RED); assertEquals(0, ms.count(Color.BLUE)); assertEquals(1, ms.count(Color.YELLOW)); assertEquals(2, ms.count(Color.RED)); } public void testCollectionCreate() { Multiset<Color> ms = EnumMultiset.create( asList(Color.RED, Color.YELLOW, Color.RED)); assertEquals(0, ms.count(Color.BLUE)); assertEquals(1, ms.count(Color.YELLOW)); assertEquals(2, ms.count(Color.RED)); } public void testIllegalCreate() { Collection<Color> empty = EnumSet.noneOf(Color.class); try { EnumMultiset.create(empty); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateEmptyWithClass() { Multiset<Color> ms = EnumMultiset.create(ImmutableList.<Color>of(), Color.class); ms.add(Color.RED); } public void testCreateEmptyWithoutClassFails() { try { EnumMultiset.create(ImmutableList.<Color> of()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testToString() { Multiset<Color> ms = EnumMultiset.create(Color.class); ms.add(Color.BLUE, 3); ms.add(Color.YELLOW, 1); ms.add(Color.RED, 2); assertEquals("[BLUE x 3, RED x 2, YELLOW]", ms.toString()); } public void testEntrySet() { Multiset<Color> ms = EnumMultiset.create(Color.class); ms.add(Color.BLUE, 3); ms.add(Color.YELLOW, 1); ms.add(Color.RED, 2); Set<Object> uniqueEntries = Sets.newIdentityHashSet(); uniqueEntries.addAll(ms.entrySet()); assertEquals(3, uniqueEntries.size()); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/EnumMultisetTest.java
Java
asf20
3,268
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.testing.EqualsTester; /** * Tests {@link SingletonImmutableTable}. * * @author Gregory Kick */ @GwtCompatible(emulated = true) public class SingletonImmutableTableTest extends AbstractImmutableTableTest { private final ImmutableTable<Character, Integer, String> testTable = new SingletonImmutableTable<Character, Integer, String>('a', 1, "blah"); public void testHashCode() { assertEquals(Objects.hashCode('a', 1, "blah"), testTable.hashCode()); } public void testCellSet() { assertEquals(ImmutableSet.of(Tables.immutableCell('a', 1, "blah")), testTable.cellSet()); } public void testColumn() { assertEquals(ImmutableMap.of(), testTable.column(0)); assertEquals(ImmutableMap.of('a', "blah"), testTable.column(1)); } public void testColumnKeySet() { assertEquals(ImmutableSet.of(1), testTable.columnKeySet()); } public void testColumnMap() { assertEquals(ImmutableMap.of(1, ImmutableMap.of('a', "blah")), testTable.columnMap()); } public void testRow() { assertEquals(ImmutableMap.of(), testTable.row('A')); assertEquals(ImmutableMap.of(1, "blah"), testTable.row('a')); } public void testRowKeySet() { assertEquals(ImmutableSet.of('a'), testTable.rowKeySet()); } public void testRowMap() { assertEquals(ImmutableMap.of('a', ImmutableMap.of(1, "blah")), testTable.rowMap()); } public void testEqualsObject() { new EqualsTester() .addEqualityGroup(testTable, HashBasedTable.create(testTable)) .addEqualityGroup(ImmutableTable.of(), HashBasedTable.create()) .addEqualityGroup(HashBasedTable.create(ImmutableTable.of('A', 2, ""))) .testEquals(); } public void testToString() { assertEquals("{a={1=blah}}", testTable.toString()); } public void testContains() { assertTrue(testTable.contains('a', 1)); assertFalse(testTable.contains('a', 2)); assertFalse(testTable.contains('A', 1)); assertFalse(testTable.contains('A', 2)); } public void testContainsColumn() { assertTrue(testTable.containsColumn(1)); assertFalse(testTable.containsColumn(2)); } public void testContainsRow() { assertTrue(testTable.containsRow('a')); assertFalse(testTable.containsRow('A')); } public void testContainsValue() { assertTrue(testTable.containsValue("blah")); assertFalse(testTable.containsValue("")); } public void testGet() { assertEquals("blah", testTable.get('a', 1)); assertNull(testTable.get('a', 2)); assertNull(testTable.get('A', 1)); assertNull(testTable.get('A', 2)); } public void testIsEmpty() { assertFalse(testTable.isEmpty()); } public void testSize() { assertEquals(1, testTable.size()); } public void testValues() { ASSERT.that(testTable.values()).has().item("blah"); } @Override Iterable<ImmutableTable<Character, Integer, String>> getTestInstances() { return ImmutableSet.of(testTable); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/SingletonImmutableTableTest.java
Java
asf20
3,747
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.testing.AnEnum; import com.google.common.collect.testing.MapInterfaceTest; import com.google.common.collect.testing.MinimalSet; import com.google.common.collect.testing.SampleElements.Colliders; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.io.Serializable; import java.util.Collections; import java.util.EnumMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; /** * Tests for {@link ImmutableMap}. * * @author Kevin Bourrillion * @author Jesse Wilson */ @GwtCompatible(emulated = true) public class ImmutableMapTest extends TestCase { public abstract static class AbstractMapTests<K, V> extends MapInterfaceTest<K, V> { public AbstractMapTests() { super(false, false, false, false, false); } @Override protected Map<K, V> makeEmptyMap() { throw new UnsupportedOperationException(); } private static final Joiner joiner = Joiner.on(", "); @Override protected void assertMoreInvariants(Map<K, V> map) { // TODO: can these be moved to MapInterfaceTest? for (Entry<K, V> entry : map.entrySet()) { assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString()); } assertEquals("{" + joiner.join(map.entrySet()) + "}", map.toString()); assertEquals("[" + joiner.join(map.entrySet()) + "]", map.entrySet().toString()); assertEquals("[" + joiner.join(map.keySet()) + "]", map.keySet().toString()); assertEquals("[" + joiner.join(map.values()) + "]", map.values().toString()); assertEquals(MinimalSet.from(map.entrySet()), map.entrySet()); assertEquals(Sets.newHashSet(map.keySet()), map.keySet()); } } public static class MapTests extends AbstractMapTests<String, Integer> { @Override protected Map<String, Integer> makeEmptyMap() { return ImmutableMap.of(); } @Override protected Map<String, Integer> makePopulatedMap() { return ImmutableMap.of("one", 1, "two", 2, "three", 3); } @Override protected String getKeyNotInPopulatedMap() { return "minus one"; } @Override protected Integer getValueNotInPopulatedMap() { return -1; } } public static class SingletonMapTests extends AbstractMapTests<String, Integer> { @Override protected Map<String, Integer> makePopulatedMap() { return ImmutableMap.of("one", 1); } @Override protected String getKeyNotInPopulatedMap() { return "minus one"; } @Override protected Integer getValueNotInPopulatedMap() { return -1; } } public static class MapTestsWithBadHashes extends AbstractMapTests<Object, Integer> { @Override protected Map<Object, Integer> makeEmptyMap() { throw new UnsupportedOperationException(); } @Override protected Map<Object, Integer> makePopulatedMap() { Colliders colliders = new Colliders(); return ImmutableMap.of( colliders.e0, 0, colliders.e1, 1, colliders.e2, 2, colliders.e3, 3); } @Override protected Object getKeyNotInPopulatedMap() { return new Colliders().e4; } @Override protected Integer getValueNotInPopulatedMap() { return 4; } } public static class CreationTests extends TestCase { public void testEmptyBuilder() { ImmutableMap<String, Integer> map = new Builder<String, Integer>().build(); assertEquals(Collections.<String, Integer>emptyMap(), map); } public void testSingletonBuilder() { ImmutableMap<String, Integer> map = new Builder<String, Integer>() .put("one", 1) .build(); assertMapEquals(map, "one", 1); } public void testBuilder() { ImmutableMap<String, Integer> map = new Builder<String, Integer>() .put("one", 1) .put("two", 2) .put("three", 3) .put("four", 4) .put("five", 5) .build(); assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); } public void testBuilder_withImmutableEntry() { ImmutableMap<String, Integer> map = new Builder<String, Integer>() .put(Maps.immutableEntry("one", 1)) .build(); assertMapEquals(map, "one", 1); } public void testBuilder_withImmutableEntryAndNullContents() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(Maps.immutableEntry("one", (Integer) null)); fail(); } catch (NullPointerException expected) { } try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) { } } private static class StringHolder { String string; } public void testBuilder_withMutableEntry() { ImmutableMap.Builder<String, Integer> builder = new Builder<String, Integer>(); final StringHolder holder = new StringHolder(); holder.string = "one"; Entry<String, Integer> entry = new AbstractMapEntry<String, Integer>() { @Override public String getKey() { return holder.string; } @Override public Integer getValue() { return 1; } }; builder.put(entry); holder.string = "two"; assertMapEquals(builder.build(), "one", 1); } public void testBuilderPutAllWithEmptyMap() { ImmutableMap<String, Integer> map = new Builder<String, Integer>() .putAll(Collections.<String, Integer>emptyMap()) .build(); assertEquals(Collections.<String, Integer>emptyMap(), map); } public void testBuilderPutAll() { Map<String, Integer> toPut = new LinkedHashMap<String, Integer>(); toPut.put("one", 1); toPut.put("two", 2); toPut.put("three", 3); Map<String, Integer> moreToPut = new LinkedHashMap<String, Integer>(); moreToPut.put("four", 4); moreToPut.put("five", 5); ImmutableMap<String, Integer> map = new Builder<String, Integer>() .putAll(toPut) .putAll(moreToPut) .build(); assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); } public void testBuilderReuse() { Builder<String, Integer> builder = new Builder<String, Integer>(); ImmutableMap<String, Integer> mapOne = builder .put("one", 1) .put("two", 2) .build(); ImmutableMap<String, Integer> mapTwo = builder .put("three", 3) .put("four", 4) .build(); assertMapEquals(mapOne, "one", 1, "two", 2); assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4); } public void testBuilderPutNullKeyFailsAtomically() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(null, 1); fail(); } catch (NullPointerException expected) {} builder.put("foo", 2); assertMapEquals(builder.build(), "foo", 2); } public void testBuilderPutImmutableEntryWithNullKeyFailsAtomically() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) {} builder.put("foo", 2); assertMapEquals(builder.build(), "foo", 2); } // for GWT compatibility static class SimpleEntry<K, V> extends AbstractMapEntry<K, V> { public K key; public V value; SimpleEntry(K key, V value) { this.key = key; this.value = value; } @Override public K getKey() { return key; } @Override public V getValue() { return value; } } public void testBuilderPutMutableEntryWithNullKeyFailsAtomically() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(new SimpleEntry<String, Integer>(null, 1)); fail(); } catch (NullPointerException expected) {} builder.put("foo", 2); assertMapEquals(builder.build(), "foo", 2); } public void testBuilderPutNullKey() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(null, 1); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullValue() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put("one", null); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullKeyViaPutAll() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.putAll(Collections.<String, Integer>singletonMap(null, 1)); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullValueViaPutAll() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.putAll(Collections.<String, Integer>singletonMap("one", null)); fail(); } catch (NullPointerException expected) { } } public void testPuttingTheSameKeyTwiceThrowsOnBuild() { Builder<String, Integer> builder = new Builder<String, Integer>() .put("one", 1) .put("one", 1); // throwing on this line would be even better try { builder.build(); fail(); } catch (IllegalArgumentException expected) { } } public void testOf() { assertMapEquals( ImmutableMap.of("one", 1), "one", 1); assertMapEquals( ImmutableMap.of("one", 1, "two", 2), "one", 1, "two", 2); assertMapEquals( ImmutableMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3); assertMapEquals( ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4), "one", 1, "two", 2, "three", 3, "four", 4); assertMapEquals( ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); } public void testOfNullKey() { try { ImmutableMap.of(null, 1); fail(); } catch (NullPointerException expected) { } try { ImmutableMap.of("one", 1, null, 2); fail(); } catch (NullPointerException expected) { } } public void testOfNullValue() { try { ImmutableMap.of("one", null); fail(); } catch (NullPointerException expected) { } try { ImmutableMap.of("one", 1, "two", null); fail(); } catch (NullPointerException expected) { } } public void testOfWithDuplicateKey() { try { ImmutableMap.of("one", 1, "one", 1); fail(); } catch (IllegalArgumentException expected) { } } public void testCopyOfEmptyMap() { ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(Collections.<String, Integer>emptyMap()); assertEquals(Collections.<String, Integer>emptyMap(), copy); assertSame(copy, ImmutableMap.copyOf(copy)); } public void testCopyOfSingletonMap() { ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(Collections.singletonMap("one", 1)); assertMapEquals(copy, "one", 1); assertSame(copy, ImmutableMap.copyOf(copy)); } public void testCopyOf() { Map<String, Integer> original = new LinkedHashMap<String, Integer>(); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(original); assertMapEquals(copy, "one", 1, "two", 2, "three", 3); assertSame(copy, ImmutableMap.copyOf(copy)); } } public void testNullGet() { ImmutableMap<String, Integer> map = ImmutableMap.of("one", 1); assertNull(map.get(null)); } public void testAsMultimap() { ImmutableMap<String, Integer> map = ImmutableMap.of( "one", 1, "won", 1, "two", 2, "too", 2, "three", 3); ImmutableSetMultimap<String, Integer> expected = ImmutableSetMultimap.of( "one", 1, "won", 1, "two", 2, "too", 2, "three", 3); assertEquals(expected, map.asMultimap()); } public void testAsMultimapWhenEmpty() { ImmutableMap<String, Integer> map = ImmutableMap.of(); ImmutableSetMultimap<String, Integer> expected = ImmutableSetMultimap.of(); assertEquals(expected, map.asMultimap()); } public void testAsMultimapCaches() { ImmutableMap<String, Integer> map = ImmutableMap.of("one", 1); ImmutableSetMultimap<String, Integer> multimap1 = map.asMultimap(); ImmutableSetMultimap<String, Integer> multimap2 = map.asMultimap(); assertEquals(1, multimap1.asMap().size()); assertSame(multimap1, multimap2); } private static <K, V> void assertMapEquals(Map<K, V> map, Object... alternatingKeysAndValues) { assertEquals(map.size(), alternatingKeysAndValues.length / 2); int i = 0; for (Entry<K, V> entry : map.entrySet()) { assertEquals(alternatingKeysAndValues[i++], entry.getKey()); assertEquals(alternatingKeysAndValues[i++], entry.getValue()); } } private static class IntHolder implements Serializable { public int value; public IntHolder(int value) { this.value = value; } @Override public boolean equals(Object o) { return (o instanceof IntHolder) && ((IntHolder) o).value == value; } @Override public int hashCode() { return value; } private static final long serialVersionUID = 5; } public void testMutableValues() { IntHolder holderA = new IntHolder(1); IntHolder holderB = new IntHolder(2); Map<String, IntHolder> map = ImmutableMap.of("a", holderA, "b", holderB); holderA.value = 3; assertTrue(map.entrySet().contains( Maps.immutableEntry("a", new IntHolder(3)))); Map<String, Integer> intMap = ImmutableMap.of("a", 3, "b", 2); assertEquals(intMap.hashCode(), map.entrySet().hashCode()); assertEquals(intMap.hashCode(), map.hashCode()); } public void testCopyOfEnumMap() { EnumMap<AnEnum, String> map = new EnumMap<AnEnum, String>(AnEnum.class); map.put(AnEnum.B, "foo"); map.put(AnEnum.C, "bar"); assertTrue(ImmutableMap.copyOf(map) instanceof ImmutableEnumMap); } public void testEquals() { new EqualsTester() .addEqualityGroup(ImmutableList.of(), ImmutableList.of()) .addEqualityGroup(ImmutableList.of(1), ImmutableList.of(1)) .addEqualityGroup(ImmutableList.of(1, 2), ImmutableList.of(1, 2)) .addEqualityGroup(ImmutableList.of(1, 2, 3)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(100, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 200, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 300, 4, 5, 6, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 400, 5, 6, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 500, 6, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 600, 7, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 700, 8, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 800, 9, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 900, 10, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 1000, 11, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1100, 12)) .addEqualityGroup(ImmutableList.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1200)) .testEquals(); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ImmutableMapTest.java
Java
asf20
17,420
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.Table.Cell; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; /** * Tests for {@link Tables}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class TablesTest extends TestCase { public void testImmutableEntryToString() { Cell<String, Integer, Character> entry = Tables.immutableCell("foo", 1, 'a'); assertEquals("(foo,1)=a", entry.toString()); Cell<String, Integer, Character> nullEntry = Tables.immutableCell(null, null, null); assertEquals("(null,null)=null", nullEntry.toString()); } public void testEntryEquals() { Cell<String, Integer, Character> entry = Tables.immutableCell("foo", 1, 'a'); new EqualsTester() .addEqualityGroup(entry, Tables.immutableCell("foo", 1, 'a')) .addEqualityGroup(Tables.immutableCell("bar", 1, 'a')) .addEqualityGroup(Tables.immutableCell("foo", 2, 'a')) .addEqualityGroup(Tables.immutableCell("foo", 1, 'b')) .addEqualityGroup(Tables.immutableCell(null, null, null)) .testEquals(); } public void testEntryEqualsNull() { Cell<String, Integer, Character> entry = Tables.immutableCell(null, null, null); new EqualsTester() .addEqualityGroup(entry, Tables.immutableCell(null, null, null)) .addEqualityGroup(Tables.immutableCell("bar", null, null)) .addEqualityGroup(Tables.immutableCell(null, 2, null)) .addEqualityGroup(Tables.immutableCell(null, null, 'b')) .addEqualityGroup(Tables.immutableCell("foo", 1, 'a')) .testEquals(); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/TablesTest.java
Java
asf20
2,337
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; /** * Variant of {@link SerializableTester} that does not require the reserialized object's class to be * identical to the original. * * @author Chris Povirk */ /* * The whole thing is really @GwtIncompatible, but GwtJUnitConvertedTestModule doesn't have a * parameter for non-GWT, non-test files, and it didn't seem worth adding one for this unusual case. */ @GwtCompatible(emulated = true) final class LenientSerializableTester { /* * TODO(cpovirk): move this to c.g.c.testing if we allow for c.g.c.annotations dependencies so * that it can be GWTified? */ private LenientSerializableTester() {} }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/LenientSerializableTester.java
Java
asf20
1,314
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; /** * Test cases for {@link HashBasedTable}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class HashBasedTableTest extends AbstractTableTest { @Override protected Table<String, Integer, Character> create( Object... data) { Table<String, Integer, Character> table = HashBasedTable.create(); table.put("foo", 4, 'a'); table.put("cat", 1, 'b'); table.clear(); populate(table, data); return table; } public void testCreateWithValidSizes() { Table<String, Integer, Character> table1 = HashBasedTable.create(100, 20); table1.put("foo", 1, 'a'); assertEquals((Character) 'a', table1.get("foo", 1)); Table<String, Integer, Character> table2 = HashBasedTable.create(100, 0); table2.put("foo", 1, 'a'); assertEquals((Character) 'a', table2.get("foo", 1)); Table<String, Integer, Character> table3 = HashBasedTable.create(0, 20); table3.put("foo", 1, 'a'); assertEquals((Character) 'a', table3.get("foo", 1)); Table<String, Integer, Character> table4 = HashBasedTable.create(0, 0); table4.put("foo", 1, 'a'); assertEquals((Character) 'a', table4.get("foo", 1)); } public void testCreateWithInvalidSizes() { try { HashBasedTable.create(100, -5); fail(); } catch (IllegalArgumentException expected) {} try { HashBasedTable.create(-5, 20); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateCopy() { Table<String, Integer, Character> original = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Table<String, Integer, Character> copy = HashBasedTable.create(original); assertEquals(original, copy); assertEquals((Character) 'a', copy.get("foo", 1)); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/HashBasedTableTest.java
Java
asf20
2,453
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSortedMap.Builder; import com.google.common.collect.testing.SortedMapInterfaceTest; import junit.framework.TestCase; import java.io.Serializable; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; /** * Tests for {@link ImmutableSortedMap}. * * @author Kevin Bourrillion * @author Jesse Wilson * @author Jared Levy */ @GwtCompatible(emulated = true) public class ImmutableSortedMapTest extends TestCase { // TODO: Avoid duplicating code in ImmutableMapTest public abstract static class AbstractMapTests<K, V> extends SortedMapInterfaceTest<K, V> { public AbstractMapTests() { super(false, false, false, false, false); } @Override protected SortedMap<K, V> makeEmptyMap() { throw new UnsupportedOperationException(); } private static final Joiner joiner = Joiner.on(", "); @Override protected void assertMoreInvariants(Map<K, V> map) { // TODO: can these be moved to MapInterfaceTest? for (Entry<K, V> entry : map.entrySet()) { assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString()); } assertEquals("{" + joiner.join(map.entrySet()) + "}", map.toString()); assertEquals("[" + joiner.join(map.entrySet()) + "]", map.entrySet().toString()); assertEquals("[" + joiner.join(map.keySet()) + "]", map.keySet().toString()); assertEquals("[" + joiner.join(map.values()) + "]", map.values().toString()); assertEquals(Sets.newHashSet(map.entrySet()), map.entrySet()); assertEquals(Sets.newHashSet(map.keySet()), map.keySet()); } } public static class MapTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makeEmptyMap() { return ImmutableSortedMap.of(); } @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("one", 1, "two", 2, "three", 3); } @Override protected String getKeyNotInPopulatedMap() { return "minus one"; } @Override protected Integer getValueNotInPopulatedMap() { return -1; } } public static class SingletonMapTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("one", 1); } @Override protected String getKeyNotInPopulatedMap() { return "minus one"; } @Override protected Integer getValueNotInPopulatedMap() { return -1; } } public static class HeadMapTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5) .headMap("d"); } @Override protected String getKeyNotInPopulatedMap() { return "d"; } @Override protected Integer getValueNotInPopulatedMap() { return 4; } } public static class HeadMapInclusiveTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5) .headMap("c", true); } @Override protected String getKeyNotInPopulatedMap() { return "d"; } @Override protected Integer getValueNotInPopulatedMap() { return 4; } } public static class TailMapTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5) .tailMap("b"); } @Override protected String getKeyNotInPopulatedMap() { return "a"; } @Override protected Integer getValueNotInPopulatedMap() { return 1; } } public static class TailExclusiveMapTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5) .tailMap("a", false); } @Override protected String getKeyNotInPopulatedMap() { return "a"; } @Override protected Integer getValueNotInPopulatedMap() { return 1; } } public static class SubMapTests extends AbstractMapTests<String, Integer> { @Override protected SortedMap<String, Integer> makePopulatedMap() { return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5) .subMap("b", "d"); } @Override protected String getKeyNotInPopulatedMap() { return "a"; } @Override protected Integer getValueNotInPopulatedMap() { return 4; } } public static class CreationTests extends TestCase { public void testEmptyBuilder() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>naturalOrder().build(); assertEquals(Collections.<String, Integer>emptyMap(), map); } public void testSingletonBuilder() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>naturalOrder() .put("one", 1) .build(); assertMapEquals(map, "one", 1); } public void testBuilder() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>naturalOrder() .put("one", 1) .put("two", 2) .put("three", 3) .put("four", 4) .put("five", 5) .build(); assertMapEquals(map, "five", 5, "four", 4, "one", 1, "three", 3, "two", 2); } public void testBuilder_withImmutableEntry() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>naturalOrder() .put(Maps.immutableEntry("one", 1)) .build(); assertMapEquals(map, "one", 1); } public void testBuilder_withImmutableEntryAndNullContents() { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); try { builder.put(Maps.immutableEntry("one", (Integer) null)); fail(); } catch (NullPointerException expected) { } try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) { } } private static class StringHolder { String string; } public void testBuilder_withMutableEntry() { ImmutableSortedMap.Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); final StringHolder holder = new StringHolder(); holder.string = "one"; Entry<String, Integer> entry = new AbstractMapEntry<String, Integer>() { @Override public String getKey() { return holder.string; } @Override public Integer getValue() { return 1; } }; builder.put(entry); holder.string = "two"; assertMapEquals(builder.build(), "one", 1); } public void testBuilderPutAllWithEmptyMap() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>naturalOrder() .putAll(Collections.<String, Integer>emptyMap()) .build(); assertEquals(Collections.<String, Integer>emptyMap(), map); } public void testBuilderPutAll() { Map<String, Integer> toPut = new LinkedHashMap<String, Integer>(); toPut.put("one", 1); toPut.put("two", 2); toPut.put("three", 3); Map<String, Integer> moreToPut = new LinkedHashMap<String, Integer>(); moreToPut.put("four", 4); moreToPut.put("five", 5); ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>naturalOrder() .putAll(toPut) .putAll(moreToPut) .build(); assertMapEquals(map, "five", 5, "four", 4, "one", 1, "three", 3, "two", 2); } public void testBuilderReuse() { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); ImmutableSortedMap<String, Integer> mapOne = builder .put("one", 1) .put("two", 2) .build(); ImmutableSortedMap<String, Integer> mapTwo = builder .put("three", 3) .put("four", 4) .build(); assertMapEquals(mapOne, "one", 1, "two", 2); assertMapEquals(mapTwo, "four", 4, "one", 1, "three", 3, "two", 2); } public void testBuilderPutNullKey() { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); try { builder.put(null, 1); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullValue() { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); try { builder.put("one", null); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullKeyViaPutAll() { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); try { builder.putAll(Collections.<String, Integer>singletonMap(null, 1)); fail(); } catch (NullPointerException expected) { } } public void testBuilderPutNullValueViaPutAll() { Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder(); try { builder.putAll(Collections.<String, Integer>singletonMap("one", null)); fail(); } catch (NullPointerException expected) { } } public void testPuttingTheSameKeyTwiceThrowsOnBuild() { Builder<String, Integer> builder = ImmutableSortedMap.<String, Integer>naturalOrder() .put("one", 1) .put("one", 2); // throwing on this line would be even better try { builder.build(); fail(); } catch (IllegalArgumentException expected) { } } public void testOf() { assertMapEquals( ImmutableSortedMap.of("one", 1), "one", 1); assertMapEquals( ImmutableSortedMap.of("one", 1, "two", 2), "one", 1, "two", 2); assertMapEquals( ImmutableSortedMap.of("one", 1, "two", 2, "three", 3), "one", 1, "three", 3, "two", 2); assertMapEquals( ImmutableSortedMap.of("one", 1, "two", 2, "three", 3, "four", 4), "four", 4, "one", 1, "three", 3, "two", 2); assertMapEquals( ImmutableSortedMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5), "five", 5, "four", 4, "one", 1, "three", 3, "two", 2); } public void testOfNullKey() { Integer n = null; try { ImmutableSortedMap.of(n, 1); fail(); } catch (NullPointerException expected) { } try { ImmutableSortedMap.of("one", 1, null, 2); fail(); } catch (NullPointerException expected) { } } public void testOfNullValue() { try { ImmutableSortedMap.of("one", null); fail(); } catch (NullPointerException expected) { } try { ImmutableSortedMap.of("one", 1, "two", null); fail(); } catch (NullPointerException expected) { } } public void testOfWithDuplicateKey() { try { ImmutableSortedMap.of("one", 1, "one", 1); fail(); } catch (IllegalArgumentException expected) { } } public void testCopyOfEmptyMap() { ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(Collections.<String, Integer>emptyMap()); assertEquals(Collections.<String, Integer>emptyMap(), copy); assertSame(copy, ImmutableSortedMap.copyOf(copy)); assertSame(Ordering.natural(), copy.comparator()); } public void testCopyOfSingletonMap() { ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(Collections.singletonMap("one", 1)); assertMapEquals(copy, "one", 1); assertSame(copy, ImmutableSortedMap.copyOf(copy)); assertSame(Ordering.natural(), copy.comparator()); } public void testCopyOf() { Map<String, Integer> original = new LinkedHashMap<String, Integer>(); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original); assertMapEquals(copy, "one", 1, "three", 3, "two", 2); assertSame(copy, ImmutableSortedMap.copyOf(copy)); assertSame(Ordering.natural(), copy.comparator()); } public void testCopyOfExplicitComparator() { Comparator<String> comparator = Ordering.natural().reverse(); Map<String, Integer> original = new LinkedHashMap<String, Integer>(); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original, comparator); assertMapEquals(copy, "two", 2, "three", 3, "one", 1); assertSame(copy, ImmutableSortedMap.copyOf(copy, comparator)); assertSame(comparator, copy.comparator()); } public void testCopyOfImmutableSortedSetDifferentComparator() { Comparator<String> comparator = Ordering.natural().reverse(); Map<String, Integer> original = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3); ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original, comparator); assertMapEquals(copy, "two", 2, "three", 3, "one", 1); assertSame(copy, ImmutableSortedMap.copyOf(copy, comparator)); assertSame(comparator, copy.comparator()); } public void testCopyOfSortedNatural() { SortedMap<String, Integer> original = Maps.newTreeMap(); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOfSorted(original); assertMapEquals(copy, "one", 1, "three", 3, "two", 2); assertSame(copy, ImmutableSortedMap.copyOfSorted(copy)); assertSame(Ordering.natural(), copy.comparator()); } public void testCopyOfSortedExplicit() { Comparator<String> comparator = Ordering.natural().reverse(); SortedMap<String, Integer> original = Maps.newTreeMap(comparator); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOfSorted(original); assertMapEquals(copy, "two", 2, "three", 3, "one", 1); assertSame(copy, ImmutableSortedMap.copyOfSorted(copy)); assertSame(comparator, copy.comparator()); } private static class IntegerDiv10 implements Comparable<IntegerDiv10> { final int value; IntegerDiv10(int value) { this.value = value; } @Override public int compareTo(IntegerDiv10 o) { return value / 10 - o.value / 10; } @Override public String toString() { return Integer.toString(value); } } public void testCopyOfDuplicateKey() { Map<IntegerDiv10, String> original = ImmutableMap.of( new IntegerDiv10(3), "three", new IntegerDiv10(20), "twenty", new IntegerDiv10(11), "eleven", new IntegerDiv10(35), "thirty five", new IntegerDiv10(12), "twelve" ); try { ImmutableSortedMap.copyOf(original); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testImmutableMapCopyOfImmutableSortedMap() { IntegerDiv10 three = new IntegerDiv10(3); IntegerDiv10 eleven = new IntegerDiv10(11); IntegerDiv10 twelve = new IntegerDiv10(12); IntegerDiv10 twenty = new IntegerDiv10(20); Map<IntegerDiv10, String> original = ImmutableSortedMap.of( three, "three", eleven, "eleven", twenty, "twenty"); Map<IntegerDiv10, String> copy = ImmutableMap.copyOf(original); assertTrue(original.containsKey(twelve)); assertFalse(copy.containsKey(twelve)); } public void testBuilderReverseOrder() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.<String, Integer>reverseOrder() .put("one", 1) .put("two", 2) .put("three", 3) .put("four", 4) .put("five", 5) .build(); assertMapEquals(map, "two", 2, "three", 3, "one", 1, "four", 4, "five", 5); assertEquals(Ordering.natural().reverse(), map.comparator()); } public void testBuilderComparator() { Comparator<String> comparator = Ordering.natural().reverse(); ImmutableSortedMap<String, Integer> map = new ImmutableSortedMap.Builder<String, Integer>(comparator) .put("one", 1) .put("two", 2) .put("three", 3) .put("four", 4) .put("five", 5) .build(); assertMapEquals(map, "two", 2, "three", 3, "one", 1, "four", 4, "five", 5); assertSame(comparator, map.comparator()); } } public void testNullGet() { ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.of("one", 1); assertNull(map.get(null)); } private static <K, V> void assertMapEquals(Map<K, V> map, Object... alternatingKeysAndValues) { assertEquals(map.size(), alternatingKeysAndValues.length / 2); int i = 0; for (Entry<K, V> entry : map.entrySet()) { assertEquals(alternatingKeysAndValues[i++], entry.getKey()); assertEquals(alternatingKeysAndValues[i++], entry.getValue()); } } private static class IntHolder implements Serializable { public int value; public IntHolder(int value) { this.value = value; } @Override public boolean equals(Object o) { return (o instanceof IntHolder) && ((IntHolder) o).value == value; } @Override public int hashCode() { return value; } private static final long serialVersionUID = 5; } public void testMutableValues() { IntHolder holderA = new IntHolder(1); IntHolder holderB = new IntHolder(2); Map<String, IntHolder> map = ImmutableSortedMap.of("a", holderA, "b", holderB); holderA.value = 3; assertTrue(map.entrySet().contains(Maps.immutableEntry("a", new IntHolder(3)))); Map<String, Integer> intMap = ImmutableSortedMap.of("a", 3, "b", 2); assertEquals(intMap.hashCode(), map.entrySet().hashCode()); assertEquals(intMap.hashCode(), map.hashCode()); } @SuppressWarnings("unchecked") // varargs public void testHeadMapInclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).headMap("three", true); ASSERT.that(map.entrySet()).has().exactly( Maps.immutableEntry("one", 1), Maps.immutableEntry("three", 3)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testHeadMapExclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).headMap("three", false); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("one", 1)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testTailMapInclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).tailMap("three", true); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("three", 3), Maps.immutableEntry("two", 2)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testTailMapExclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).tailMap("three", false); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("two", 2)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testSubMapExclusiveExclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).subMap("one", false, "two", false); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("three", 3)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testSubMapInclusiveExclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).subMap("one", true, "two", false); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("one", 1), Maps.immutableEntry("three", 3)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testSubMapExclusiveInclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).subMap("one", false, "two", true); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("three", 3), Maps.immutableEntry("two", 2)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testSubMapInclusiveInclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).subMap("one", true, "two", true); ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("one", 1), Maps.immutableEntry("three", 3), Maps.immutableEntry("two", 2)).inOrder(); } private static class SelfComparableExample implements Comparable<SelfComparableExample> { @Override public int compareTo(SelfComparableExample o) { return 0; } } public void testBuilderGenerics_SelfComparable() { ImmutableSortedMap.Builder<SelfComparableExample, Object> natural = ImmutableSortedMap.naturalOrder(); ImmutableSortedMap.Builder<SelfComparableExample, Object> reverse = ImmutableSortedMap.reverseOrder(); } private static class SuperComparableExample extends SelfComparableExample {} public void testBuilderGenerics_SuperComparable() { ImmutableSortedMap.Builder<SuperComparableExample, Object> natural = ImmutableSortedMap.naturalOrder(); ImmutableSortedMap.Builder<SuperComparableExample, Object> reverse = ImmutableSortedMap.reverseOrder(); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ImmutableSortedMapTest.java
Java
asf20
23,203
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations * under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Optional; import junit.framework.TestCase; import java.util.Arrays; import java.util.List; import javax.annotation.Nullable; /** * Tests for {@code TreeTraverser}. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class TreeTraverserTest extends TestCase { private static final class Tree { final char value; final List<Tree> children; public Tree(char value, Tree... children) { this.value = value; this.children = Arrays.asList(children); } } private static final class BinaryTree { final char value; @Nullable final BinaryTree left; @Nullable final BinaryTree right; private BinaryTree(char value, BinaryTree left, BinaryTree right) { this.value = value; this.left = left; this.right = right; } } private static final TreeTraverser<Tree> ADAPTER = new TreeTraverser<Tree>() { @Override public Iterable<Tree> children(Tree node) { return node.children; } }; private static final BinaryTreeTraverser<BinaryTree> BIN_ADAPTER = new BinaryTreeTraverser<BinaryTree>() { @Override public Optional<BinaryTree> leftChild(BinaryTree node) { return Optional.fromNullable(node.left); } @Override public Optional<BinaryTree> rightChild(BinaryTree node) { return Optional.fromNullable(node.right); } }; // h // / | \ // / e \ // d g // /|\ | // / | \ f // a b c static final Tree a = new Tree('a'); static final Tree b = new Tree('b'); static final Tree c = new Tree('c'); static final Tree d = new Tree('d', a, b, c); static final Tree e = new Tree('e'); static final Tree f = new Tree('f'); static final Tree g = new Tree('g', f); static final Tree h = new Tree('h', d, e, g); // d // / \ // b e // / \ \ // a c f // / // g static final BinaryTree ba = new BinaryTree('a', null, null); static final BinaryTree bc = new BinaryTree('c', null, null); static final BinaryTree bb = new BinaryTree('b', ba, bc); static final BinaryTree bg = new BinaryTree('g', null, null); static final BinaryTree bf = new BinaryTree('f', bg, null); static final BinaryTree be = new BinaryTree('e', null, bf); static final BinaryTree bd = new BinaryTree('d', bb, be); static String iterationOrder(Iterable<Tree> iterable) { StringBuilder builder = new StringBuilder(); for (Tree t : iterable) { builder.append(t.value); } return builder.toString(); } static String binaryIterationOrder(Iterable<BinaryTree> iterable) { StringBuilder builder = new StringBuilder(); for (BinaryTree t : iterable) { builder.append(t.value); } return builder.toString(); } public void testPreOrder() { ASSERT.that(iterationOrder(ADAPTER.preOrderTraversal(h))).is("hdabcegf"); ASSERT.that(binaryIterationOrder(BIN_ADAPTER.preOrderTraversal(bd))).is("dbacefg"); } public void testPostOrder() { ASSERT.that(iterationOrder(ADAPTER.postOrderTraversal(h))).is("abcdefgh"); ASSERT.that(binaryIterationOrder(BIN_ADAPTER.postOrderTraversal(bd))).is("acbgfed"); } public void testBreadthOrder() { ASSERT.that(iterationOrder(ADAPTER.breadthFirstTraversal(h))).is("hdegabcf"); ASSERT.that(binaryIterationOrder(BIN_ADAPTER.breadthFirstTraversal(bd))).is("dbeacfg"); } public void testInOrder() { ASSERT.that(binaryIterationOrder(BIN_ADAPTER.inOrderTraversal(bd))).is("abcdegf"); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/TreeTraverserTest.java
Java
asf20
4,301
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.BoundType.CLOSED; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.SortedSet; /** * Unit test for {@link TreeMultiset}. * * @author Neal Kanodia */ @GwtCompatible(emulated = true) public class TreeMultisetTest extends TestCase { public void testCreate() { TreeMultiset<String> multiset = TreeMultiset.create(); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); assertEquals(Ordering.natural(), multiset.comparator()); assertEquals("[bar, foo x 2]", multiset.toString()); } public void testCreateWithComparator() { Multiset<String> multiset = TreeMultiset.create(Collections.reverseOrder()); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); assertEquals("[foo x 2, bar]", multiset.toString()); } public void testCreateFromIterable() { Multiset<String> multiset = TreeMultiset.create(Arrays.asList("foo", "bar", "foo")); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); assertEquals("[bar, foo x 2]", multiset.toString()); } public void testToString() { Multiset<String> ms = TreeMultiset.create(); ms.add("a", 3); ms.add("c", 1); ms.add("b", 2); assertEquals("[a x 3, b x 2, c]", ms.toString()); } public void testElementSetSortedSetMethods() { TreeMultiset<String> ms = TreeMultiset.create(); ms.add("c", 1); ms.add("a", 3); ms.add("b", 2); SortedSet<String> elementSet = ms.elementSet(); assertEquals("a", elementSet.first()); assertEquals("c", elementSet.last()); assertEquals(Ordering.natural(), elementSet.comparator()); ASSERT.that(elementSet.headSet("b")).has().exactly("a").inOrder(); ASSERT.that(elementSet.tailSet("b")).has().exactly("b", "c").inOrder(); ASSERT.that(elementSet.subSet("a", "c")).has().exactly("a", "b").inOrder(); } public void testElementSetSubsetRemove() { TreeMultiset<String> ms = TreeMultiset.create(); ms.add("a", 1); ms.add("b", 3); ms.add("c", 2); ms.add("d", 1); ms.add("e", 3); ms.add("f", 2); SortedSet<String> elementSet = ms.elementSet(); ASSERT.that(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); SortedSet<String> subset = elementSet.subSet("b", "f"); ASSERT.that(subset).has().exactly("b", "c", "d", "e").inOrder(); assertTrue(subset.remove("c")); ASSERT.that(elementSet).has().exactly("a", "b", "d", "e", "f").inOrder(); ASSERT.that(subset).has().exactly("b", "d", "e").inOrder(); assertEquals(10, ms.size()); assertFalse(subset.remove("a")); ASSERT.that(elementSet).has().exactly("a", "b", "d", "e", "f").inOrder(); ASSERT.that(subset).has().exactly("b", "d", "e").inOrder(); assertEquals(10, ms.size()); } public void testElementSetSubsetRemoveAll() { TreeMultiset<String> ms = TreeMultiset.create(); ms.add("a", 1); ms.add("b", 3); ms.add("c", 2); ms.add("d", 1); ms.add("e", 3); ms.add("f", 2); SortedSet<String> elementSet = ms.elementSet(); ASSERT.that(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); SortedSet<String> subset = elementSet.subSet("b", "f"); ASSERT.that(subset).has().exactly("b", "c", "d", "e").inOrder(); assertTrue(subset.removeAll(Arrays.asList("a", "c"))); ASSERT.that(elementSet).has().exactly("a", "b", "d", "e", "f").inOrder(); ASSERT.that(subset).has().exactly("b", "d", "e").inOrder(); assertEquals(10, ms.size()); } public void testElementSetSubsetRetainAll() { TreeMultiset<String> ms = TreeMultiset.create(); ms.add("a", 1); ms.add("b", 3); ms.add("c", 2); ms.add("d", 1); ms.add("e", 3); ms.add("f", 2); SortedSet<String> elementSet = ms.elementSet(); ASSERT.that(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); SortedSet<String> subset = elementSet.subSet("b", "f"); ASSERT.that(subset).has().exactly("b", "c", "d", "e").inOrder(); assertTrue(subset.retainAll(Arrays.asList("a", "c"))); ASSERT.that(elementSet).has().exactly("a", "c", "f").inOrder(); ASSERT.that(subset).has().exactly("c").inOrder(); assertEquals(5, ms.size()); } public void testElementSetSubsetClear() { TreeMultiset<String> ms = TreeMultiset.create(); ms.add("a", 1); ms.add("b", 3); ms.add("c", 2); ms.add("d", 1); ms.add("e", 3); ms.add("f", 2); SortedSet<String> elementSet = ms.elementSet(); ASSERT.that(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); SortedSet<String> subset = elementSet.subSet("b", "f"); ASSERT.that(subset).has().exactly("b", "c", "d", "e").inOrder(); subset.clear(); ASSERT.that(elementSet).has().exactly("a", "f").inOrder(); ASSERT.that(subset).isEmpty(); assertEquals(3, ms.size()); } public void testCustomComparator() throws Exception { Comparator<String> comparator = new Comparator<String>() { @Override public int compare(String o1, String o2) { return o2.compareTo(o1); } }; TreeMultiset<String> ms = TreeMultiset.create(comparator); ms.add("b"); ms.add("c"); ms.add("a"); ms.add("b"); ms.add("d"); ASSERT.that(ms).has().exactly("d", "c", "b", "b", "a").inOrder(); SortedSet<String> elementSet = ms.elementSet(); assertEquals("d", elementSet.first()); assertEquals("a", elementSet.last()); assertEquals(comparator, elementSet.comparator()); } public void testNullAcceptingComparator() throws Exception { Comparator<String> comparator = Ordering.<String>natural().nullsFirst(); TreeMultiset<String> ms = TreeMultiset.create(comparator); ms.add("b"); ms.add(null); ms.add("a"); ms.add("b"); ms.add(null, 2); ASSERT.that(ms).has().exactly(null, null, null, "a", "b", "b").inOrder(); assertEquals(3, ms.count(null)); SortedSet<String> elementSet = ms.elementSet(); assertEquals(null, elementSet.first()); assertEquals("b", elementSet.last()); assertEquals(comparator, elementSet.comparator()); } private static final Comparator<String> DEGENERATE_COMPARATOR = new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.length() - o2.length(); } }; /** * Test a TreeMultiset with a comparator that can return 0 when comparing * unequal values. */ public void testDegenerateComparator() throws Exception { TreeMultiset<String> ms = TreeMultiset.create(DEGENERATE_COMPARATOR); ms.add("foo"); ms.add("a"); ms.add("bar"); ms.add("b"); ms.add("c"); assertEquals(2, ms.count("bar")); assertEquals(3, ms.count("b")); Multiset<String> ms2 = TreeMultiset.create(DEGENERATE_COMPARATOR); ms2.add("cat", 2); ms2.add("x", 3); assertEquals(ms, ms2); assertEquals(ms2, ms); SortedSet<String> elementSet = ms.elementSet(); assertEquals("a", elementSet.first()); assertEquals("foo", elementSet.last()); assertEquals(DEGENERATE_COMPARATOR, elementSet.comparator()); } public void testSubMultisetSize() { TreeMultiset<String> ms = TreeMultiset.create(); ms.add("a", Integer.MAX_VALUE); ms.add("b", Integer.MAX_VALUE); ms.add("c", 3); assertEquals(Integer.MAX_VALUE, ms.count("a")); assertEquals(Integer.MAX_VALUE, ms.count("b")); assertEquals(3, ms.count("c")); assertEquals(Integer.MAX_VALUE, ms.headMultiset("c", CLOSED).size()); assertEquals(Integer.MAX_VALUE, ms.headMultiset("b", CLOSED).size()); assertEquals(Integer.MAX_VALUE, ms.headMultiset("a", CLOSED).size()); assertEquals(3, ms.tailMultiset("c", CLOSED).size()); assertEquals(Integer.MAX_VALUE, ms.tailMultiset("b", CLOSED).size()); assertEquals(Integer.MAX_VALUE, ms.tailMultiset("a", CLOSED).size()); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/TreeMultisetTest.java
Java
asf20
8,862
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.DerivedComparable; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collections; /** * Tests for {@link Multisets}. * * @author Mike Bostock * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class MultisetsTest extends TestCase { /* See MultisetsImmutableEntryTest for immutableEntry() tests. */ public void testNewTreeMultisetDerived() { TreeMultiset<DerivedComparable> set = TreeMultiset.create(); assertTrue(set.isEmpty()); set.add(new DerivedComparable("foo"), 2); set.add(new DerivedComparable("bar"), 3); ASSERT.that(set).has().exactly( new DerivedComparable("bar"), new DerivedComparable("bar"), new DerivedComparable("bar"), new DerivedComparable("foo"), new DerivedComparable("foo")).inOrder(); } public void testNewTreeMultisetNonGeneric() { TreeMultiset<LegacyComparable> set = TreeMultiset.create(); assertTrue(set.isEmpty()); set.add(new LegacyComparable("foo"), 2); set.add(new LegacyComparable("bar"), 3); ASSERT.that(set).has().exactly(new LegacyComparable("bar"), new LegacyComparable("bar"), new LegacyComparable("bar"), new LegacyComparable("foo"), new LegacyComparable("foo")).inOrder(); } public void testNewTreeMultisetComparator() { TreeMultiset<String> multiset = TreeMultiset.create(Collections.reverseOrder()); multiset.add("bar", 3); multiset.add("foo", 2); ASSERT.that(multiset).has().exactly("foo", "foo", "bar", "bar", "bar").inOrder(); } public void testRetainOccurrencesEmpty() { Multiset<String> multiset = HashMultiset.create(); Multiset<String> toRetain = HashMultiset.create(Arrays.asList("a", "b", "a")); assertFalse(Multisets.retainOccurrences(multiset, toRetain)); ASSERT.that(multiset).isEmpty(); } public void testRemoveOccurrencesEmpty() { Multiset<String> multiset = HashMultiset.create(); Multiset<String> toRemove = HashMultiset.create(Arrays.asList("a", "b", "a")); assertFalse(Multisets.retainOccurrences(multiset, toRemove)); assertTrue(multiset.isEmpty()); } public void testUnion() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create( Arrays.asList("a", "b", "b", "c")); ASSERT.that(Multisets.union(ms1, ms2)).has().exactly("a", "a", "b", "b", "c"); } public void testUnionEqualMultisets() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "a")); assertEquals(ms1, Multisets.union(ms1, ms2)); } public void testUnionEmptyNonempty() { Multiset<String> ms1 = HashMultiset.create(); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "a")); assertEquals(ms2, Multisets.union(ms1, ms2)); } public void testUnionNonemptyEmpty() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(); assertEquals(ms1, Multisets.union(ms1, ms2)); } public void testIntersectEmptyNonempty() { Multiset<String> ms1 = HashMultiset.create(); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "a")); ASSERT.that(Multisets.intersection(ms1, ms2)).isEmpty(); } public void testIntersectNonemptyEmpty() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(); ASSERT.that(Multisets.intersection(ms1, ms2)).isEmpty(); } public void testSum() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("b", "c")); ASSERT.that(Multisets.sum(ms1, ms2)).has().exactly("a", "a", "b", "b", "c"); } public void testSumEmptyNonempty() { Multiset<String> ms1 = HashMultiset.create(); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "a")); ASSERT.that(Multisets.sum(ms1, ms2)).has().exactly("a", "b", "a"); } public void testSumNonemptyEmpty() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(); ASSERT.that(Multisets.sum(ms1, ms2)).has().exactly("a", "b", "a"); } public void testDifferenceWithNoRemovedElements() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a")); ASSERT.that(Multisets.difference(ms1, ms2)).has().exactly("a", "b"); } public void testDifferenceWithRemovedElement() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("b")); ASSERT.that(Multisets.difference(ms1, ms2)).has().exactly("a", "a"); } public void testDifferenceWithMoreElementsInSecondMultiset() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "b", "b")); Multiset<String> diff = Multisets.difference(ms1, ms2); ASSERT.that(diff).has().item("a"); assertEquals(0, diff.count("b")); assertEquals(1, diff.count("a")); assertFalse(diff.contains("b")); assertTrue(diff.contains("a")); } public void testDifferenceEmptyNonempty() { Multiset<String> ms1 = HashMultiset.create(); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "a")); assertEquals(ms1, Multisets.difference(ms1, ms2)); } public void testDifferenceNonemptyEmpty() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(); assertEquals(ms1, Multisets.difference(ms1, ms2)); } public void testContainsOccurrencesEmpty() { Multiset<String> superMultiset = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> subMultiset = HashMultiset.create(); assertTrue(Multisets.containsOccurrences(superMultiset, subMultiset)); assertFalse(Multisets.containsOccurrences(subMultiset, superMultiset)); } public void testContainsOccurrences() { Multiset<String> superMultiset = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> subMultiset = HashMultiset.create(Arrays.asList("a", "b")); assertTrue(Multisets.containsOccurrences(superMultiset, subMultiset)); assertFalse(Multisets.containsOccurrences(subMultiset, superMultiset)); Multiset<String> diffMultiset = HashMultiset.create(Arrays.asList("a", "b", "c")); assertFalse(Multisets.containsOccurrences(superMultiset, diffMultiset)); assertTrue(Multisets.containsOccurrences(diffMultiset, subMultiset)); } public void testRetainEmptyOccurrences() { Multiset<String> multiset = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> toRetain = HashMultiset.create(); assertTrue(Multisets.retainOccurrences(multiset, toRetain)); assertTrue(multiset.isEmpty()); } public void testRetainOccurrences() { Multiset<String> multiset = TreeMultiset.create(Arrays.asList("a", "b", "a", "c")); Multiset<String> toRetain = HashMultiset.create(Arrays.asList("a", "b", "b")); assertTrue(Multisets.retainOccurrences(multiset, toRetain)); ASSERT.that(multiset).has().exactly("a", "b").inOrder(); } public void testRemoveEmptyOccurrences() { Multiset<String> multiset = TreeMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> toRemove = HashMultiset.create(); assertFalse(Multisets.removeOccurrences(multiset, toRemove)); ASSERT.that(multiset).has().exactly("a", "a", "b").inOrder(); } public void testRemoveOccurrences() { Multiset<String> multiset = TreeMultiset.create(Arrays.asList("a", "b", "a", "c")); Multiset<String> toRemove = HashMultiset.create(Arrays.asList("a", "b", "b")); assertTrue(Multisets.removeOccurrences(multiset, toRemove)); ASSERT.that(multiset).has().exactly("a", "c").inOrder(); } @SuppressWarnings("deprecation") public void testUnmodifiableMultisetShortCircuit() { Multiset<String> mod = HashMultiset.create(); Multiset<String> unmod = Multisets.unmodifiableMultiset(mod); assertNotSame(mod, unmod); assertSame(unmod, Multisets.unmodifiableMultiset(unmod)); ImmutableMultiset<String> immutable = ImmutableMultiset.of("a", "a", "b", "a"); assertSame(immutable, Multisets.unmodifiableMultiset(immutable)); assertSame(immutable, Multisets.unmodifiableMultiset((Multiset<String>) immutable)); } public void testHighestCountFirst() { Multiset<String> multiset = HashMultiset.create( Arrays.asList("a", "a", "a", "b", "c", "c")); ImmutableMultiset<String> sortedMultiset = Multisets.copyHighestCountFirst(multiset); ASSERT.that(sortedMultiset.entrySet()).has().exactly( Multisets.immutableEntry("a", 3), Multisets.immutableEntry("c", 2), Multisets.immutableEntry("b", 1)).inOrder(); ASSERT.that(sortedMultiset).has().exactly( "a", "a", "a", "c", "c", "b").inOrder(); ASSERT.that(Multisets.copyHighestCountFirst(ImmutableMultiset.of())).isEmpty(); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/MultisetsTest.java
Java
asf20
10,144
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static java.util.Arrays.asList; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.MinimalIterable; import junit.framework.TestCase; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Base class for {@link ImmutableSet} and {@link ImmutableSortedSet} tests. * * @author Kevin Bourrillion * @author Jared Levy */ @GwtCompatible(emulated = true) public abstract class AbstractImmutableSetTest extends TestCase { protected abstract Set<String> of(); protected abstract Set<String> of(String e); protected abstract Set<String> of(String e1, String e2); protected abstract Set<String> of(String e1, String e2, String e3); protected abstract Set<String> of(String e1, String e2, String e3, String e4); protected abstract Set<String> of(String e1, String e2, String e3, String e4, String e5); protected abstract Set<String> of(String e1, String e2, String e3, String e4, String e5, String e6, String... rest); protected abstract Set<String> copyOf(String[] elements); protected abstract Set<String> copyOf(Collection<String> elements); protected abstract Set<String> copyOf(Iterable<String> elements); protected abstract Set<String> copyOf(Iterator<String> elements); public void testCreation_noArgs() { Set<String> set = of(); assertEquals(Collections.<String>emptySet(), set); assertSame(of(), set); } public void testCreation_oneElement() { Set<String> set = of("a"); assertEquals(Collections.singleton("a"), set); } public void testCreation_twoElements() { Set<String> set = of("a", "b"); assertEquals(Sets.newHashSet("a", "b"), set); } public void testCreation_threeElements() { Set<String> set = of("a", "b", "c"); assertEquals(Sets.newHashSet("a", "b", "c"), set); } public void testCreation_fourElements() { Set<String> set = of("a", "b", "c", "d"); assertEquals(Sets.newHashSet("a", "b", "c", "d"), set); } public void testCreation_fiveElements() { Set<String> set = of("a", "b", "c", "d", "e"); assertEquals(Sets.newHashSet("a", "b", "c", "d", "e"), set); } public void testCreation_sixElements() { Set<String> set = of("a", "b", "c", "d", "e", "f"); assertEquals(Sets.newHashSet("a", "b", "c", "d", "e", "f"), set); } public void testCreation_sevenElements() { Set<String> set = of("a", "b", "c", "d", "e", "f", "g"); assertEquals(Sets.newHashSet("a", "b", "c", "d", "e", "f", "g"), set); } public void testCreation_eightElements() { Set<String> set = of("a", "b", "c", "d", "e", "f", "g", "h"); assertEquals(Sets.newHashSet("a", "b", "c", "d", "e", "f", "g", "h"), set); } public void testCopyOf_emptyArray() { String[] array = new String[0]; Set<String> set = copyOf(array); assertEquals(Collections.<String>emptySet(), set); assertSame(of(), set); } public void testCopyOf_arrayOfOneElement() { String[] array = new String[] { "a" }; Set<String> set = copyOf(array); assertEquals(Collections.singleton("a"), set); } public void testCopyOf_nullArray() { try { copyOf((String[]) null); fail(); } catch (NullPointerException expected) { } } public void testCopyOf_arrayContainingOnlyNull() { String[] array = new String[] { null }; try { copyOf(array); fail(); } catch (NullPointerException expected) { } } public void testCopyOf_collection_empty() { // "<String>" is required to work around a javac 1.5 bug. Collection<String> c = MinimalCollection.<String>of(); Set<String> set = copyOf(c); assertEquals(Collections.<String>emptySet(), set); assertSame(of(), set); } public void testCopyOf_collection_oneElement() { Collection<String> c = MinimalCollection.of("a"); Set<String> set = copyOf(c); assertEquals(Collections.singleton("a"), set); } public void testCopyOf_collection_oneElementRepeated() { Collection<String> c = MinimalCollection.of("a", "a", "a"); Set<String> set = copyOf(c); assertEquals(Collections.singleton("a"), set); } public void testCopyOf_collection_general() { Collection<String> c = MinimalCollection.of("a", "b", "a"); Set<String> set = copyOf(c); assertEquals(2, set.size()); assertTrue(set.contains("a")); assertTrue(set.contains("b")); } public void testCopyOf_collectionContainingNull() { Collection<String> c = MinimalCollection.of("a", null, "b"); try { copyOf(c); fail(); } catch (NullPointerException expected) { } } public void testCopyOf_iterator_empty() { Iterator<String> iterator = Iterators.emptyIterator(); Set<String> set = copyOf(iterator); assertEquals(Collections.<String>emptySet(), set); assertSame(of(), set); } public void testCopyOf_iterator_oneElement() { Iterator<String> iterator = Iterators.singletonIterator("a"); Set<String> set = copyOf(iterator); assertEquals(Collections.singleton("a"), set); } public void testCopyOf_iterator_oneElementRepeated() { Iterator<String> iterator = Iterators.forArray("a", "a", "a"); Set<String> set = copyOf(iterator); assertEquals(Collections.singleton("a"), set); } public void testCopyOf_iterator_general() { Iterator<String> iterator = Iterators.forArray("a", "b", "a"); Set<String> set = copyOf(iterator); assertEquals(2, set.size()); assertTrue(set.contains("a")); assertTrue(set.contains("b")); } public void testCopyOf_iteratorContainingNull() { Iterator<String> c = Iterators.forArray("a", null, "b"); try { copyOf(c); fail(); } catch (NullPointerException expected) { } } private static class CountingIterable implements Iterable<String> { int count = 0; @Override public Iterator<String> iterator() { count++; return Iterators.forArray("a", "b", "a"); } } public void testCopyOf_plainIterable() { CountingIterable iterable = new CountingIterable(); Set<String> set = copyOf(iterable); assertEquals(2, set.size()); assertTrue(set.contains("a")); assertTrue(set.contains("b")); } public void testCopyOf_plainIterable_iteratesOnce() { CountingIterable iterable = new CountingIterable(); copyOf(iterable); assertEquals(1, iterable.count); } public void testCopyOf_shortcut_empty() { Collection<String> c = of(); assertEquals(Collections.<String>emptySet(), copyOf(c)); assertSame(c, copyOf(c)); } public void testCopyOf_shortcut_singleton() { Collection<String> c = of("a"); assertEquals(Collections.singleton("a"), copyOf(c)); assertSame(c, copyOf(c)); } public void testCopyOf_shortcut_sameType() { Collection<String> c = of("a", "b", "c"); assertSame(c, copyOf(c)); } public void testToString() { Set<String> set = of("a", "b", "c", "d", "e", "f", "g"); assertEquals("[a, b, c, d, e, f, g]", set.toString()); } public void testContainsAll_sameType() { Collection<String> c = of("a", "b", "c"); assertFalse(c.containsAll(of("a", "b", "c", "d"))); assertFalse(c.containsAll(of("a", "d"))); assertTrue(c.containsAll(of("a", "c"))); assertTrue(c.containsAll(of("a", "b", "c"))); } public void testEquals_sameType() { Collection<String> c = of("a", "b", "c"); assertTrue(c.equals(of("a", "b", "c"))); assertFalse(c.equals(of("a", "b", "d"))); } abstract <E extends Comparable<E>> ImmutableSet.Builder<E> builder(); public void testBuilderWithNonDuplicateElements() { ImmutableSet<String> set = this.<String>builder() .add("a") .add("b", "c") .add("d", "e", "f") .add("g", "h", "i", "j") .build(); ASSERT.that(set).has().exactly( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j").inOrder(); } public void testReuseBuilderWithNonDuplicateElements() { ImmutableSet.Builder<String> builder = this.<String>builder() .add("a") .add("b"); ASSERT.that(builder.build()).has().exactly("a", "b").inOrder(); builder.add("c", "d"); ASSERT.that(builder.build()).has().exactly("a", "b", "c", "d").inOrder(); } public void testBuilderWithDuplicateElements() { ImmutableSet<String> set = this.<String>builder() .add("a") .add("a", "a") .add("a", "a", "a") .add("a", "a", "a", "a") .build(); assertTrue(set.contains("a")); assertFalse(set.contains("b")); assertEquals(1, set.size()); } public void testReuseBuilderWithDuplicateElements() { ImmutableSet.Builder<String> builder = this.<String>builder() .add("a") .add("a", "a") .add("b"); ASSERT.that(builder.build()).has().exactly("a", "b").inOrder(); builder.add("a", "b", "c", "c"); ASSERT.that(builder.build()).has().exactly("a", "b", "c").inOrder(); } public void testBuilderAddAll() { List<String> a = asList("a", "b", "c"); List<String> b = asList("c", "d", "e"); ImmutableSet<String> set = this.<String>builder() .addAll(a) .addAll(b) .build(); ASSERT.that(set).has().exactly("a", "b", "c", "d", "e").inOrder(); } static final int LAST_COLOR_ADDED = 0x00BFFF; public void testComplexBuilder() { List<Integer> colorElem = asList(0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF); // javac won't compile this without "this.<Integer>" ImmutableSet.Builder<Integer> webSafeColorsBuilder = this.<Integer>builder(); for (Integer red : colorElem) { for (Integer green : colorElem) { for (Integer blue : colorElem) { webSafeColorsBuilder.add((red << 16) + (green << 8) + blue); } } } ImmutableSet<Integer> webSafeColors = webSafeColorsBuilder.build(); assertEquals(216, webSafeColors.size()); Integer[] webSafeColorArray = webSafeColors.toArray(new Integer[webSafeColors.size()]); assertEquals(0x000000, (int) webSafeColorArray[0]); assertEquals(0x000033, (int) webSafeColorArray[1]); assertEquals(0x000066, (int) webSafeColorArray[2]); assertEquals(0x003300, (int) webSafeColorArray[6]); assertEquals(0x330000, (int) webSafeColorArray[36]); ImmutableSet<Integer> addedColor = webSafeColorsBuilder.add(LAST_COLOR_ADDED).build(); assertEquals( "Modifying the builder should not have changed any already built sets", 216, webSafeColors.size()); assertEquals("the new array should be one bigger than webSafeColors", 217, addedColor.size()); Integer[] appendColorArray = addedColor.toArray(new Integer[addedColor.size()]); assertEquals( getComplexBuilderSetLastElement(), (int) appendColorArray[216]); } abstract int getComplexBuilderSetLastElement(); public void testBuilderAddHandlesNullsCorrectly() { ImmutableSet.Builder<String> builder = this.<String>builder(); try { builder.add((String) null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } builder = this.<String>builder(); try { builder.add((String[]) null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } builder = this.<String>builder(); try { builder.add("a", (String) null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } builder = this.<String>builder(); try { builder.add("a", "b", (String) null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } builder = this.<String>builder(); try { builder.add("a", "b", "c", null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } builder = this.<String>builder(); try { builder.add("a", "b", null, "c"); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } } public void testBuilderAddAllHandlesNullsCorrectly() { ImmutableSet.Builder<String> builder = this.<String>builder(); try { builder.addAll((Iterable<String>) null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } try { builder.addAll((Iterator<String>) null); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } builder = this.<String>builder(); List<String> listWithNulls = asList("a", null, "b"); try { builder.addAll(listWithNulls); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } Iterable<String> iterableWithNulls = MinimalIterable.of("a", null, "b"); try { builder.addAll(iterableWithNulls); fail("expected NullPointerException"); // COV_NF_LINE } catch (NullPointerException expected) { } } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/AbstractImmutableSetTest.java
Java
asf20
13,910
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import junit.framework.TestCase; import java.util.Arrays; import java.util.List; /** * Tests for {@code GeneralRange}. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class GeneralRangeTest extends TestCase { private static final Ordering<Integer> ORDERING = Ordering.natural().nullsFirst(); private static final List<Integer> IN_ORDER_VALUES = Arrays.asList(null, 1, 2, 3, 4, 5); public void testCreateEmptyRangeFails() { for (BoundType lboundType : BoundType.values()) { for (BoundType uboundType : BoundType.values()) { try { GeneralRange.range(ORDERING, 4, lboundType, 2, uboundType); fail("Expected IAE"); } catch (IllegalArgumentException expected) {} } } } public void testCreateEmptyRangeOpenOpenFails() { for (Integer i : IN_ORDER_VALUES) { try { GeneralRange.range(ORDERING, i, OPEN, i, OPEN); fail("Expected IAE"); } catch (IllegalArgumentException expected) {} } } public void testCreateEmptyRangeClosedOpenSucceeds() { for (Integer i : IN_ORDER_VALUES) { GeneralRange<Integer> range = GeneralRange.range(ORDERING, i, CLOSED, i, OPEN); for (Integer j : IN_ORDER_VALUES) { assertFalse(range.contains(j)); } } } public void testCreateEmptyRangeOpenClosedSucceeds() { for (Integer i : IN_ORDER_VALUES) { GeneralRange<Integer> range = GeneralRange.range(ORDERING, i, OPEN, i, CLOSED); for (Integer j : IN_ORDER_VALUES) { assertFalse(range.contains(j)); } } } public void testCreateSingletonRangeSucceeds() { for (Integer i : IN_ORDER_VALUES) { GeneralRange<Integer> range = GeneralRange.range(ORDERING, i, CLOSED, i, CLOSED); for (Integer j : IN_ORDER_VALUES) { assertEquals(Objects.equal(i, j), range.contains(j)); } } } public void testSingletonRange() { GeneralRange<Integer> range = GeneralRange.range(ORDERING, 3, CLOSED, 3, CLOSED); for (Integer i : IN_ORDER_VALUES) { assertEquals(ORDERING.compare(i, 3) == 0, range.contains(i)); } } public void testLowerRange() { for (BoundType lBoundType : BoundType.values()) { GeneralRange<Integer> range = GeneralRange.downTo(ORDERING, 3, lBoundType); for (Integer i : IN_ORDER_VALUES) { assertEquals(ORDERING.compare(i, 3) > 0 || (ORDERING.compare(i, 3) == 0 && lBoundType == CLOSED), range.contains(i)); assertEquals(ORDERING.compare(i, 3) < 0 || (ORDERING.compare(i, 3) == 0 && lBoundType == OPEN), range.tooLow(i)); assertFalse(range.tooHigh(i)); } } } public void testUpperRange() { for (BoundType lBoundType : BoundType.values()) { GeneralRange<Integer> range = GeneralRange.upTo(ORDERING, 3, lBoundType); for (Integer i : IN_ORDER_VALUES) { assertEquals(ORDERING.compare(i, 3) < 0 || (ORDERING.compare(i, 3) == 0 && lBoundType == CLOSED), range.contains(i)); assertEquals(ORDERING.compare(i, 3) > 0 || (ORDERING.compare(i, 3) == 0 && lBoundType == OPEN), range.tooHigh(i)); assertFalse(range.tooLow(i)); } } } public void testDoublyBoundedAgainstRange() { for (BoundType lboundType : BoundType.values()) { for (BoundType uboundType : BoundType.values()) { Range<Integer> range = Range.range(2, lboundType, 4, uboundType); GeneralRange<Integer> gRange = GeneralRange.range(ORDERING, 2, lboundType, 4, uboundType); for (Integer i : IN_ORDER_VALUES) { assertEquals(i != null && range.contains(i), gRange.contains(i)); } } } } public void testIntersectAgainstMatchingEndpointsRange() { GeneralRange<Integer> range = GeneralRange.range(ORDERING, 2, CLOSED, 4, OPEN); assertEquals(GeneralRange.range(ORDERING, 2, OPEN, 4, OPEN), range.intersect(GeneralRange.range(ORDERING, 2, OPEN, 4, CLOSED))); } public void testIntersectAgainstBiggerRange() { GeneralRange<Integer> range = GeneralRange.range(ORDERING, 2, CLOSED, 4, OPEN); assertEquals(GeneralRange.range(ORDERING, 2, CLOSED, 4, OPEN), range.intersect(GeneralRange.range(ORDERING, null, OPEN, 5, CLOSED))); assertEquals(GeneralRange.range(ORDERING, 2, OPEN, 4, OPEN), range.intersect(GeneralRange.range(ORDERING, 2, OPEN, 5, CLOSED))); assertEquals(GeneralRange.range(ORDERING, 2, CLOSED, 4, OPEN), range.intersect(GeneralRange.range(ORDERING, 1, OPEN, 4, OPEN))); } public void testIntersectAgainstSmallerRange() { GeneralRange<Integer> range = GeneralRange.range(ORDERING, 2, OPEN, 4, OPEN); assertEquals(GeneralRange.range(ORDERING, 3, CLOSED, 4, OPEN), range.intersect(GeneralRange.range(ORDERING, 3, CLOSED, 4, CLOSED))); } public void testIntersectOverlappingRange() { GeneralRange<Integer> range = GeneralRange.range(ORDERING, 2, OPEN, 4, CLOSED); assertEquals(GeneralRange.range(ORDERING, 3, CLOSED, 4, CLOSED), range.intersect(GeneralRange.range(ORDERING, 3, CLOSED, 5, CLOSED))); assertEquals(GeneralRange.range(ORDERING, 2, OPEN, 3, OPEN), range.intersect(GeneralRange.range(ORDERING, 1, OPEN, 3, OPEN))); } public void testIntersectNonOverlappingRange() { GeneralRange<Integer> range = GeneralRange.range(ORDERING, 2, OPEN, 4, CLOSED); assertTrue(range.intersect(GeneralRange.range(ORDERING, 5, CLOSED, 6, CLOSED)).isEmpty()); assertTrue(range.intersect(GeneralRange.range(ORDERING, 1, OPEN, 2, OPEN)).isEmpty()); } public void testFromRangeAll() { assertEquals(GeneralRange.all(Ordering.natural()), GeneralRange.from(Range.all())); } public void testFromRangeOneEnd() { for (BoundType endpointType : BoundType.values()) { assertEquals(GeneralRange.upTo(Ordering.natural(), 3, endpointType), GeneralRange.from(Range.upTo(3, endpointType))); assertEquals(GeneralRange.downTo(Ordering.natural(), 3, endpointType), GeneralRange.from(Range.downTo(3, endpointType))); } } public void testFromRangeTwoEnds() { for (BoundType lowerType : BoundType.values()) { for (BoundType upperType : BoundType.values()) { assertEquals(GeneralRange.range(Ordering.natural(), 3, lowerType, 4, upperType), GeneralRange.from(Range.range(3, lowerType, 4, upperType))); } } } public void testReverse() { assertEquals(GeneralRange.all(ORDERING.reverse()), GeneralRange.all(ORDERING).reverse()); assertEquals(GeneralRange.downTo(ORDERING.reverse(), 3, CLOSED), GeneralRange.upTo(ORDERING, 3, CLOSED).reverse()); assertEquals(GeneralRange.upTo(ORDERING.reverse(), 3, OPEN), GeneralRange.downTo(ORDERING, 3, OPEN).reverse()); assertEquals(GeneralRange.range(ORDERING.reverse(), 5, OPEN, 3, CLOSED), GeneralRange.range(ORDERING, 3, CLOSED, 5, OPEN).reverse()); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/GeneralRangeTest.java
Java
asf20
7,780
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AnEnum; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.TestEnumMapGenerator; import junit.framework.TestCase; import java.util.Map; import java.util.Map.Entry; /** * Tests for {@code ImmutableEnumMap}. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class ImmutableEnumMapTest extends TestCase { public static class ImmutableEnumMapGenerator extends TestEnumMapGenerator { @Override protected Map<AnEnum, String> create(Entry<AnEnum, String>[] entries) { Map<AnEnum, String> map = Maps.newHashMap(); for (Entry<AnEnum, String> entry : entries) { map.put(entry.getKey(), entry.getValue()); } return Maps.immutableEnumMap(map); } } public void testEmptyImmutableEnumMap() { ImmutableMap<AnEnum, String> map = Maps.immutableEnumMap(ImmutableMap.<AnEnum, String>of()); assertEquals(ImmutableMap.of(), map); } public void testImmutableEnumMapOrdering() { ImmutableMap<AnEnum, String> map = Maps.immutableEnumMap( ImmutableMap.of(AnEnum.C, "c", AnEnum.A, "a", AnEnum.E, "e")); ASSERT.that(map.entrySet()).has().exactly( Helpers.mapEntry(AnEnum.A, "a"), Helpers.mapEntry(AnEnum.C, "c"), Helpers.mapEntry(AnEnum.E, "e")).inOrder(); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ImmutableEnumMapTest.java
Java
asf20
2,080
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.SortedLists.KeyAbsentBehavior; import com.google.common.collect.SortedLists.KeyPresentBehavior; import junit.framework.TestCase; import java.util.List; /** * Tests for SortedLists. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class SortedListsTest extends TestCase { private static final ImmutableList<Integer> LIST_WITH_DUPS = ImmutableList.of(1, 1, 2, 4, 4, 4, 8); private static final ImmutableList<Integer> LIST_WITHOUT_DUPS = ImmutableList.of(1, 2, 4, 8); void assertModelAgrees(List<Integer> list, Integer key, int answer, KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { switch (presentBehavior) { case FIRST_PRESENT: if (list.contains(key)) { assertEquals(list.indexOf(key), answer); return; } break; case LAST_PRESENT: if (list.contains(key)) { assertEquals(list.lastIndexOf(key), answer); return; } break; case ANY_PRESENT: if (list.contains(key)) { assertEquals(key, list.get(answer)); return; } break; case FIRST_AFTER: if (list.contains(key)) { assertEquals(list.lastIndexOf(key) + 1, answer); return; } break; case LAST_BEFORE: if (list.contains(key)) { assertEquals(list.indexOf(key) - 1, answer); return; } break; default: throw new AssertionError(); } // key is not present int nextHigherIndex = list.size(); for (int i = list.size() - 1; i >= 0 && list.get(i) > key; i--) { nextHigherIndex = i; } switch (absentBehavior) { case NEXT_LOWER: assertEquals(nextHigherIndex - 1, answer); return; case NEXT_HIGHER: assertEquals(nextHigherIndex, answer); return; case INVERTED_INSERTION_INDEX: assertEquals(-1 - nextHigherIndex, answer); return; default: throw new AssertionError(); } } public void testWithoutDups() { for (KeyPresentBehavior presentBehavior : KeyPresentBehavior.values()) { for (KeyAbsentBehavior absentBehavior : KeyAbsentBehavior.values()) { for (int key = 0; key <= 10; key++) { assertModelAgrees(LIST_WITHOUT_DUPS, key, SortedLists.binarySearch(LIST_WITHOUT_DUPS, key, presentBehavior, absentBehavior), presentBehavior, absentBehavior); } } } } public void testWithDups() { for (KeyPresentBehavior presentBehavior : KeyPresentBehavior.values()) { for (KeyAbsentBehavior absentBehavior : KeyAbsentBehavior.values()) { for (int key = 0; key <= 10; key++) { assertModelAgrees(LIST_WITH_DUPS, key, SortedLists.binarySearch(LIST_WITH_DUPS, key, presentBehavior, absentBehavior), presentBehavior, absentBehavior); } } } } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/SortedListsTest.java
Java
asf20
3,686
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import static com.google.common.collect.DiscreteDomain.integers; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Set; /** * @author Gregory Kick */ @GwtCompatible(emulated = true) public class ContiguousSetTest extends TestCase { private static DiscreteDomain<Integer> NOT_EQUAL_TO_INTEGERS = new DiscreteDomain<Integer>() { @Override public Integer next(Integer value) { return integers().next(value); } @Override public Integer previous(Integer value) { return integers().previous(value); } @Override public long distance(Integer start, Integer end) { return integers().distance(start, end); } @Override public Integer minValue() { return integers().minValue(); } @Override public Integer maxValue() { return integers().maxValue(); } }; public void testEquals() { new EqualsTester() .addEqualityGroup( ContiguousSet.create(Range.closed(1, 3), integers()), ContiguousSet.create(Range.closedOpen(1, 4), integers()), ContiguousSet.create(Range.openClosed(0, 3), integers()), ContiguousSet.create(Range.open(0, 4), integers()), ContiguousSet.create(Range.closed(1, 3), NOT_EQUAL_TO_INTEGERS), ContiguousSet.create(Range.closedOpen(1, 4), NOT_EQUAL_TO_INTEGERS), ContiguousSet.create(Range.openClosed(0, 3), NOT_EQUAL_TO_INTEGERS), ContiguousSet.create(Range.open(0, 4), NOT_EQUAL_TO_INTEGERS), ImmutableSortedSet.of(1, 2, 3)) .testEquals(); // not testing hashCode for these because it takes forever to compute assertEquals( ContiguousSet.create(Range.closed(Integer.MIN_VALUE, Integer.MAX_VALUE), integers()), ContiguousSet.create(Range.<Integer>all(), integers())); assertEquals( ContiguousSet.create(Range.closed(Integer.MIN_VALUE, Integer.MAX_VALUE), integers()), ContiguousSet.create(Range.atLeast(Integer.MIN_VALUE), integers())); assertEquals( ContiguousSet.create(Range.closed(Integer.MIN_VALUE, Integer.MAX_VALUE), integers()), ContiguousSet.create(Range.atMost(Integer.MAX_VALUE), integers())); } public void testCreate_noMin() { Range<Integer> range = Range.lessThan(0); try { ContiguousSet.create(range, RangeTest.UNBOUNDED_DOMAIN); fail(); } catch (IllegalArgumentException expected) {} } public void testCreate_noMax() { Range<Integer> range = Range.greaterThan(0); try { ContiguousSet.create(range, RangeTest.UNBOUNDED_DOMAIN); fail(); } catch (IllegalArgumentException expected) {} } public void testCreate_empty() { assertEquals(ImmutableSet.of(), ContiguousSet.create(Range.closedOpen(1, 1), integers())); assertEquals(ImmutableSet.of(), ContiguousSet.create(Range.openClosed(5, 5), integers())); assertEquals(ImmutableSet.of(), ContiguousSet.create(Range.lessThan(Integer.MIN_VALUE), integers())); assertEquals(ImmutableSet.of(), ContiguousSet.create(Range.greaterThan(Integer.MAX_VALUE), integers())); } public void testHeadSet() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); ASSERT.that(set.headSet(1)).isEmpty(); ASSERT.that(set.headSet(2)).has().item(1); ASSERT.that(set.headSet(3)).has().exactly(1, 2).inOrder(); ASSERT.that(set.headSet(4)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.headSet(Integer.MAX_VALUE)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.headSet(1, true)).has().item(1); ASSERT.that(set.headSet(2, true)).has().exactly(1, 2).inOrder(); ASSERT.that(set.headSet(3, true)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.headSet(4, true)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.headSet(Integer.MAX_VALUE, true)).has().exactly(1, 2, 3).inOrder(); } public void testHeadSet_tooSmall() { ASSERT.that(ContiguousSet.create(Range.closed(1, 3), integers()).headSet(0)).isEmpty(); } public void testTailSet() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); ASSERT.that(set.tailSet(Integer.MIN_VALUE)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.tailSet(1)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.tailSet(2)).has().exactly(2, 3).inOrder(); ASSERT.that(set.tailSet(3)).has().item(3); ASSERT.that(set.tailSet(Integer.MIN_VALUE, false)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.tailSet(1, false)).has().exactly(2, 3).inOrder(); ASSERT.that(set.tailSet(2, false)).has().item(3); ASSERT.that(set.tailSet(3, false)).isEmpty(); } public void testTailSet_tooLarge() { ASSERT.that(ContiguousSet.create(Range.closed(1, 3), integers()).tailSet(4)).isEmpty(); } public void testSubSet() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); ASSERT.that(set.subSet(1, 4)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.subSet(2, 4)).has().exactly(2, 3).inOrder(); ASSERT.that(set.subSet(3, 4)).has().item(3); ASSERT.that(set.subSet(3, 3)).isEmpty(); ASSERT.that(set.subSet(2, 3)).has().item(2); ASSERT.that(set.subSet(1, 3)).has().exactly(1, 2).inOrder(); ASSERT.that(set.subSet(1, 2)).has().item(1); ASSERT.that(set.subSet(2, 2)).isEmpty(); ASSERT.that(set.subSet(Integer.MIN_VALUE, Integer.MAX_VALUE)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.subSet(1, true, 3, true)).has().exactly(1, 2, 3).inOrder(); ASSERT.that(set.subSet(1, false, 3, true)).has().exactly(2, 3).inOrder(); ASSERT.that(set.subSet(1, true, 3, false)).has().exactly(1, 2).inOrder(); ASSERT.that(set.subSet(1, false, 3, false)).has().item(2); } public void testSubSet_outOfOrder() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); try { set.subSet(3, 2); fail(); } catch (IllegalArgumentException expected) {} } public void testSubSet_tooLarge() { ASSERT.that(ContiguousSet.create(Range.closed(1, 3), integers()).subSet(4, 6)).isEmpty(); } public void testSubSet_tooSmall() { ASSERT.that(ContiguousSet.create(Range.closed(1, 3), integers()).subSet(-1, 0)).isEmpty(); } public void testFirst() { assertEquals(1, ContiguousSet.create(Range.closed(1, 3), integers()).first().intValue()); assertEquals(1, ContiguousSet.create(Range.open(0, 4), integers()).first().intValue()); assertEquals(Integer.MIN_VALUE, ContiguousSet.create(Range.<Integer>all(), integers()).first().intValue()); } public void testLast() { assertEquals(3, ContiguousSet.create(Range.closed(1, 3), integers()).last().intValue()); assertEquals(3, ContiguousSet.create(Range.open(0, 4), integers()).last().intValue()); assertEquals(Integer.MAX_VALUE, ContiguousSet.create(Range.<Integer>all(), integers()).last().intValue()); } public void testContains() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); assertFalse(set.contains(0)); assertTrue(set.contains(1)); assertTrue(set.contains(2)); assertTrue(set.contains(3)); assertFalse(set.contains(4)); set = ContiguousSet.create(Range.open(0, 4), integers()); assertFalse(set.contains(0)); assertTrue(set.contains(1)); assertTrue(set.contains(2)); assertTrue(set.contains(3)); assertFalse(set.contains(4)); assertFalse(set.contains("blah")); } public void testContainsAll() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); for (Set<Integer> subset : Sets.powerSet(ImmutableSet.of(1, 2, 3))) { assertTrue(set.containsAll(subset)); } for (Set<Integer> subset : Sets.powerSet(ImmutableSet.of(1, 2, 3))) { assertFalse(set.containsAll(Sets.union(subset, ImmutableSet.of(9)))); } assertFalse(set.containsAll(ImmutableSet.of("blah"))); } public void testRange() { assertEquals(Range.closed(1, 3), ContiguousSet.create(Range.closed(1, 3), integers()).range()); assertEquals(Range.closed(1, 3), ContiguousSet.create(Range.closedOpen(1, 4), integers()).range()); assertEquals(Range.closed(1, 3), ContiguousSet.create(Range.open(0, 4), integers()).range()); assertEquals(Range.closed(1, 3), ContiguousSet.create(Range.openClosed(0, 3), integers()).range()); assertEquals(Range.openClosed(0, 3), ContiguousSet.create(Range.closed(1, 3), integers()).range(OPEN, CLOSED)); assertEquals(Range.openClosed(0, 3), ContiguousSet.create(Range.closedOpen(1, 4), integers()).range(OPEN, CLOSED)); assertEquals(Range.openClosed(0, 3), ContiguousSet.create(Range.open(0, 4), integers()).range(OPEN, CLOSED)); assertEquals(Range.openClosed(0, 3), ContiguousSet.create(Range.openClosed(0, 3), integers()).range(OPEN, CLOSED)); assertEquals(Range.open(0, 4), ContiguousSet.create(Range.closed(1, 3), integers()).range(OPEN, OPEN)); assertEquals(Range.open(0, 4), ContiguousSet.create(Range.closedOpen(1, 4), integers()).range(OPEN, OPEN)); assertEquals(Range.open(0, 4), ContiguousSet.create(Range.open(0, 4), integers()).range(OPEN, OPEN)); assertEquals(Range.open(0, 4), ContiguousSet.create(Range.openClosed(0, 3), integers()).range(OPEN, OPEN)); assertEquals(Range.closedOpen(1, 4), ContiguousSet.create(Range.closed(1, 3), integers()).range(CLOSED, OPEN)); assertEquals(Range.closedOpen(1, 4), ContiguousSet.create(Range.closedOpen(1, 4), integers()).range(CLOSED, OPEN)); assertEquals(Range.closedOpen(1, 4), ContiguousSet.create(Range.open(0, 4), integers()).range(CLOSED, OPEN)); assertEquals(Range.closedOpen(1, 4), ContiguousSet.create(Range.openClosed(0, 3), integers()).range(CLOSED, OPEN)); } public void testRange_unboundedRange() { assertEquals(Range.closed(Integer.MIN_VALUE, Integer.MAX_VALUE), ContiguousSet.create(Range.<Integer>all(), integers()).range()); assertEquals(Range.atLeast(Integer.MIN_VALUE), ContiguousSet.create(Range.<Integer>all(), integers()).range(CLOSED, OPEN)); assertEquals(Range.all(), ContiguousSet.create(Range.<Integer>all(), integers()).range(OPEN, OPEN)); assertEquals(Range.atMost(Integer.MAX_VALUE), ContiguousSet.create(Range.<Integer>all(), integers()).range(OPEN, CLOSED)); } public void testIntersection_empty() { ContiguousSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); ContiguousSet<Integer> emptySet = ContiguousSet.create(Range.closedOpen(2, 2), integers()); assertEquals(ImmutableSet.of(), set.intersection(emptySet)); assertEquals(ImmutableSet.of(), emptySet.intersection(set)); assertEquals(ImmutableSet.of(), ContiguousSet.create(Range.closed(-5, -1), integers()).intersection( ContiguousSet.create(Range.open(3, 64), integers()))); } public void testIntersection() { ContiguousSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); assertEquals(ImmutableSet.of(1, 2, 3), ContiguousSet.create(Range.open(-1, 4), integers()).intersection(set)); assertEquals(ImmutableSet.of(1, 2, 3), set.intersection(ContiguousSet.create(Range.open(-1, 4), integers()))); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ContiguousSetTest.java
Java
asf20
12,298
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.google.TestStringMultisetGenerator; import junit.framework.TestCase; import java.util.Arrays; /** * Unit test for {@link HashMultiset}. * * @author Kevin Bourrillion * @author Jared Levy */ @GwtCompatible(emulated = true) public class HashMultisetTest extends TestCase { private static TestStringMultisetGenerator hashMultisetGenerator() { return new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { return HashMultiset.create(asList(elements)); } }; } public void testCreate() { Multiset<String> multiset = HashMultiset.create(); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); } public void testCreateWithSize() { Multiset<String> multiset = HashMultiset.create(50); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); } public void testCreateFromIterable() { Multiset<String> multiset = HashMultiset.create(Arrays.asList("foo", "bar", "foo")); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); } /* * The behavior of toString() and iteration is tested by LinkedHashMultiset, * which shares a lot of code with HashMultiset and has deterministic * iteration order. */ }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/HashMultisetTest.java
Java
asf20
2,184
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.MultimapBuilder.MultimapBuilderWithKeys; import com.google.common.testing.SerializableTester; import junit.framework.TestCase; import java.math.RoundingMode; import java.util.SortedMap; import java.util.SortedSet; /** * Tests for {@link MultimapBuilder}. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class MultimapBuilderTest extends TestCase { public void testGenerics_gwtCompatible() { ListMultimap<String, Integer> a = MultimapBuilder.hashKeys().arrayListValues().<String, Integer>build(); SortedSetMultimap<String, Integer> b = MultimapBuilder.linkedHashKeys().treeSetValues().<String, Integer>build(); SetMultimap<String, Integer> c = MultimapBuilder.treeKeys(String.CASE_INSENSITIVE_ORDER) .hashSetValues().<String, Integer>build(); } public void testTreeKeys_gwtCompatible() { ListMultimap<String, Integer> multimap = MultimapBuilder.treeKeys().arrayListValues().<String, Integer>build(); assertTrue(multimap.keySet() instanceof SortedSet); assertTrue(multimap.asMap() instanceof SortedMap); } public void testSerialization() { for (MultimapBuilderWithKeys<?> builderWithKeys : ImmutableList.of( MultimapBuilder.hashKeys(), MultimapBuilder.linkedHashKeys(), MultimapBuilder.treeKeys(), MultimapBuilder.enumKeys(RoundingMode.class))) { for (MultimapBuilder<?, ?> builder : ImmutableList.of( builderWithKeys.arrayListValues(), builderWithKeys.linkedListValues(), builderWithKeys.hashSetValues(), builderWithKeys.linkedHashSetValues(), builderWithKeys.treeSetValues(), builderWithKeys.enumSetValues(RoundingMode.class))) { SerializableTester.reserializeAndAssert(builder.build()); } } } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/MultimapBuilderTest.java
Java
asf20
2,524
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Lists.newArrayList; import static java.util.Arrays.asList; import static java.util.Collections.nCopies; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Predicate; import junit.framework.TestCase; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * Tests for {@link Collections2}. * * @author Chris Povirk * @author Jared Levy */ @GwtCompatible(emulated = true) public class Collections2Test extends TestCase { static final Predicate<String> NOT_YYY_ZZZ = new Predicate<String>() { @Override public boolean apply(String input) { return !"yyy".equals(input) && !"zzz".equals(input); } }; static final Predicate<String> LENGTH_1 = new Predicate<String>() { @Override public boolean apply(String input) { return input.length() == 1; } }; static final Predicate<String> STARTS_WITH_VOWEL = new Predicate<String>() { @Override public boolean apply(String input) { return asList('a', 'e', 'i', 'o', 'u').contains(input.charAt(0)); } }; private static final Function<String, String> REMOVE_FIRST_CHAR = new Function<String, String>() { @Override public String apply(String from) { return ((from == null) || "".equals(from)) ? null : from.substring(1); } }; public void testOrderedPermutationSetEmpty() { List<Integer> list = newArrayList(); Collection<List<Integer>> permutationSet = Collections2.orderedPermutations(list); assertEquals(1, permutationSet.size()); ASSERT.that(permutationSet).has().item(list); Iterator<List<Integer>> permutations = permutationSet.iterator(); assertNextPermutation(Lists.<Integer>newArrayList(), permutations); assertNoMorePermutations(permutations); } public void testOrderedPermutationSetOneElement() { List<Integer> list = newArrayList(1); Iterator<List<Integer>> permutations = Collections2.orderedPermutations(list).iterator(); assertNextPermutation(newArrayList(1), permutations); assertNoMorePermutations(permutations); } public void testOrderedPermutationSetThreeElements() { List<String> list = newArrayList("b", "a", "c"); Iterator<List<String>> permutations = Collections2.orderedPermutations(list).iterator(); assertNextPermutation(newArrayList("a", "b", "c"), permutations); assertNextPermutation(newArrayList("a", "c", "b"), permutations); assertNextPermutation(newArrayList("b", "a", "c"), permutations); assertNextPermutation(newArrayList("b", "c", "a"), permutations); assertNextPermutation(newArrayList("c", "a", "b"), permutations); assertNextPermutation(newArrayList("c", "b", "a"), permutations); assertNoMorePermutations(permutations); } public void testOrderedPermutationSetRepeatedElements() { List<Integer> list = newArrayList(1, 1, 2, 2); Iterator<List<Integer>> permutations = Collections2.orderedPermutations(list, Ordering.natural()).iterator(); assertNextPermutation(newArrayList(1, 1, 2, 2), permutations); assertNextPermutation(newArrayList(1, 2, 1, 2), permutations); assertNextPermutation(newArrayList(1, 2, 2, 1), permutations); assertNextPermutation(newArrayList(2, 1, 1, 2), permutations); assertNextPermutation(newArrayList(2, 1, 2, 1), permutations); assertNextPermutation(newArrayList(2, 2, 1, 1), permutations); assertNoMorePermutations(permutations); } public void testOrderedPermutationSetRepeatedElementsSize() { List<Integer> list = newArrayList(1, 1, 1, 1, 2, 2, 3); Collection<List<Integer>> permutations = Collections2.orderedPermutations(list, Ordering.natural()); assertPermutationsCount(105, permutations); } public void testOrderedPermutationSetSizeOverflow() { // 12 elements won't overflow assertEquals(479001600 /*12!*/, Collections2.orderedPermutations( newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)).size()); // 13 elements overflow an int assertEquals(Integer.MAX_VALUE, Collections2.orderedPermutations( newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)).size()); // 21 elements overflow a long assertEquals(Integer.MAX_VALUE, Collections2.orderedPermutations( newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21)).size()); // Almost force an overflow in the binomial coefficient calculation assertEquals(1391975640 /*C(34,14)*/, Collections2.orderedPermutations( concat(nCopies(20, 1), nCopies(14, 2))).size()); // Do force an overflow in the binomial coefficient calculation assertEquals(Integer.MAX_VALUE, Collections2.orderedPermutations( concat(nCopies(21, 1), nCopies(14, 2))).size()); } public void testOrderedPermutationSetContains() { List<Integer> list = newArrayList(3, 2, 1); Collection<List<Integer>> permutationSet = Collections2.orderedPermutations(list); assertTrue(permutationSet.contains(newArrayList(1, 2, 3))); assertTrue(permutationSet.contains(newArrayList(2, 3, 1))); assertFalse(permutationSet.contains(newArrayList(1, 2))); assertFalse(permutationSet.contains(newArrayList(1, 1, 2, 3))); assertFalse(permutationSet.contains(newArrayList(1, 2, 3, 4))); assertFalse(permutationSet.contains(null)); } public void testPermutationSetEmpty() { Collection<List<Integer>> permutationSet = Collections2.permutations(Collections.<Integer>emptyList()); assertEquals(1, permutationSet.size()); assertTrue(permutationSet.contains(Collections.<Integer> emptyList())); Iterator<List<Integer>> permutations = permutationSet.iterator(); assertNextPermutation(Collections.<Integer> emptyList(), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetOneElement() { Iterator<List<Integer>> permutations = Collections2.permutations(Collections.<Integer> singletonList(1)) .iterator(); assertNextPermutation(newArrayList(1), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetTwoElements() { Iterator<List<Integer>> permutations = Collections2.permutations( newArrayList(1, 2)).iterator(); assertNextPermutation(newArrayList(1, 2), permutations); assertNextPermutation(newArrayList(2, 1), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetThreeElements() { Iterator<List<Integer>> permutations = Collections2.permutations( newArrayList(1, 2, 3)).iterator(); assertNextPermutation(newArrayList(1, 2, 3), permutations); assertNextPermutation(newArrayList(1, 3, 2), permutations); assertNextPermutation(newArrayList(3, 1, 2), permutations); assertNextPermutation(newArrayList(3, 2, 1), permutations); assertNextPermutation(newArrayList(2, 3, 1), permutations); assertNextPermutation(newArrayList(2, 1, 3), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetThreeElementsOutOfOrder() { Iterator<List<Integer>> permutations = Collections2.permutations( newArrayList(3, 2, 1)).iterator(); assertNextPermutation(newArrayList(3, 2, 1), permutations); assertNextPermutation(newArrayList(3, 1, 2), permutations); assertNextPermutation(newArrayList(1, 3, 2), permutations); assertNextPermutation(newArrayList(1, 2, 3), permutations); assertNextPermutation(newArrayList(2, 1, 3), permutations); assertNextPermutation(newArrayList(2, 3, 1), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetThreeRepeatedElements() { Iterator<List<Integer>> permutations = Collections2.permutations( newArrayList(1, 1, 2)).iterator(); assertNextPermutation(newArrayList(1, 1, 2), permutations); assertNextPermutation(newArrayList(1, 2, 1), permutations); assertNextPermutation(newArrayList(2, 1, 1), permutations); assertNextPermutation(newArrayList(2, 1, 1), permutations); assertNextPermutation(newArrayList(1, 2, 1), permutations); assertNextPermutation(newArrayList(1, 1, 2), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetFourElements() { Iterator<List<Integer>> permutations = Collections2.permutations( newArrayList(1, 2, 3, 4)).iterator(); assertNextPermutation(newArrayList(1, 2, 3, 4), permutations); assertNextPermutation(newArrayList(1, 2, 4, 3), permutations); assertNextPermutation(newArrayList(1, 4, 2, 3), permutations); assertNextPermutation(newArrayList(4, 1, 2, 3), permutations); assertNextPermutation(newArrayList(4, 1, 3, 2), permutations); assertNextPermutation(newArrayList(1, 4, 3, 2), permutations); assertNextPermutation(newArrayList(1, 3, 4, 2), permutations); assertNextPermutation(newArrayList(1, 3, 2, 4), permutations); assertNextPermutation(newArrayList(3, 1, 2, 4), permutations); assertNextPermutation(newArrayList(3, 1, 4, 2), permutations); assertNextPermutation(newArrayList(3, 4, 1, 2), permutations); assertNextPermutation(newArrayList(4, 3, 1, 2), permutations); assertNextPermutation(newArrayList(4, 3, 2, 1), permutations); assertNextPermutation(newArrayList(3, 4, 2, 1), permutations); assertNextPermutation(newArrayList(3, 2, 4, 1), permutations); assertNextPermutation(newArrayList(3, 2, 1, 4), permutations); assertNextPermutation(newArrayList(2, 3, 1, 4), permutations); assertNextPermutation(newArrayList(2, 3, 4, 1), permutations); assertNextPermutation(newArrayList(2, 4, 3, 1), permutations); assertNextPermutation(newArrayList(4, 2, 3, 1), permutations); assertNextPermutation(newArrayList(4, 2, 1, 3), permutations); assertNextPermutation(newArrayList(2, 4, 1, 3), permutations); assertNextPermutation(newArrayList(2, 1, 4, 3), permutations); assertNextPermutation(newArrayList(2, 1, 3, 4), permutations); assertNoMorePermutations(permutations); } public void testPermutationSetSize() { assertPermutationsCount(1, Collections2.permutations(Collections.<Integer>emptyList())); assertPermutationsCount(1, Collections2.permutations(newArrayList(1))); assertPermutationsCount(2, Collections2.permutations(newArrayList(1, 2))); assertPermutationsCount(6, Collections2.permutations(newArrayList(1, 2, 3))); assertPermutationsCount(5040, Collections2.permutations(newArrayList(1, 2, 3, 4, 5, 6, 7))); assertPermutationsCount(40320, Collections2.permutations(newArrayList(1, 2, 3, 4, 5, 6, 7, 8))); } public void testPermutationSetSizeOverflow() { // 13 elements overflow an int assertEquals(Integer.MAX_VALUE, Collections2.permutations(newArrayList( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)).size()); // 21 elements overflow a long assertEquals(Integer.MAX_VALUE, Collections2.orderedPermutations( newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)).size()); assertEquals(Integer.MAX_VALUE, Collections2.orderedPermutations( newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21)).size()); } public void testPermutationSetContains() { List<Integer> list = newArrayList(3, 2, 1); Collection<List<Integer>> permutationSet = Collections2.permutations(list); assertTrue(permutationSet.contains(newArrayList(1, 2, 3))); assertTrue(permutationSet.contains(newArrayList(2, 3, 1))); assertFalse(permutationSet.contains(newArrayList(1, 2))); assertFalse(permutationSet.contains(newArrayList(1, 1, 2, 3))); assertFalse(permutationSet.contains(newArrayList(1, 2, 3, 4))); assertFalse(permutationSet.contains(null)); } private <T> void assertNextPermutation(List<T> expectedPermutation, Iterator<List<T>> permutations) { assertTrue("Expected another permutation, but there was none.", permutations.hasNext()); assertEquals(expectedPermutation, permutations.next()); } private <T> void assertNoMorePermutations( Iterator<List<T>> permutations) { assertFalse("Expected no more permutations, but there was one.", permutations.hasNext()); try { permutations.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException expected) {} } private <T> void assertPermutationsCount(int expected, Collection<List<T>> permutationSet) { assertEquals(expected, permutationSet.size()); Iterator<List<T>> permutations = permutationSet.iterator(); for (int i = 0; i < expected; i++) { assertTrue(permutations.hasNext()); permutations.next(); } assertNoMorePermutations(permutations); } public void testToStringImplWithNullEntries() throws Exception { List<String> list = Lists.newArrayList(); list.add("foo"); list.add(null); assertEquals(list.toString(), Collections2.toStringImpl(list)); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/Collections2Test.java
Java
asf20
14,046
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableListMultimap.Builder; import com.google.common.collect.testing.google.TestStringListMultimapGenerator; import com.google.common.collect.testing.google.UnmodifiableCollectionTests; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collections; import java.util.Map.Entry; /** * Tests for {@link ImmutableListMultimap}. * * @author Jared Levy */ @GwtCompatible(emulated = true) public class ImmutableListMultimapTest extends TestCase { public static class ImmutableListMultimapGenerator extends TestStringListMultimapGenerator { @Override protected ListMultimap<String, String> create(Entry<String, String>[] entries) { ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder(); for (Entry<String, String> entry : entries) { builder.put(entry.getKey(), entry.getValue()); } return builder.build(); } } public void testBuilder_withImmutableEntry() { ImmutableListMultimap<String, Integer> multimap = new Builder<String, Integer>() .put(Maps.immutableEntry("one", 1)) .build(); assertEquals(Arrays.asList(1), multimap.get("one")); } public void testBuilder_withImmutableEntryAndNullContents() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(Maps.immutableEntry("one", (Integer) null)); fail(); } catch (NullPointerException expected) { } try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) { } } private static class StringHolder { String string; } public void testBuilder_withMutableEntry() { ImmutableListMultimap.Builder<String, Integer> builder = new Builder<String, Integer>(); final StringHolder holder = new StringHolder(); holder.string = "one"; Entry<String, Integer> entry = new AbstractMapEntry<String, Integer>() { @Override public String getKey() { return holder.string; } @Override public Integer getValue() { return 1; } }; builder.put(entry); holder.string = "two"; assertEquals(Arrays.asList(1), builder.build().get("one")); } public void testBuilderPutAllIterable() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.putAll("foo", Arrays.asList(1, 2, 3)); builder.putAll("bar", Arrays.asList(4, 5)); builder.putAll("foo", Arrays.asList(6, 7)); Multimap<String, Integer> multimap = builder.build(); assertEquals(Arrays.asList(1, 2, 3, 6, 7), multimap.get("foo")); assertEquals(Arrays.asList(4, 5), multimap.get("bar")); assertEquals(7, multimap.size()); } public void testBuilderPutAllVarargs() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.putAll("foo", 1, 2, 3); builder.putAll("bar", 4, 5); builder.putAll("foo", 6, 7); Multimap<String, Integer> multimap = builder.build(); assertEquals(Arrays.asList(1, 2, 3, 6, 7), multimap.get("foo")); assertEquals(Arrays.asList(4, 5), multimap.get("bar")); assertEquals(7, multimap.size()); } public void testBuilderPutAllMultimap() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put("foo", 1); toPut.put("bar", 4); toPut.put("foo", 2); toPut.put("foo", 3); Multimap<String, Integer> moreToPut = LinkedListMultimap.create(); moreToPut.put("foo", 6); moreToPut.put("bar", 5); moreToPut.put("foo", 7); ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.putAll(toPut); builder.putAll(moreToPut); Multimap<String, Integer> multimap = builder.build(); assertEquals(Arrays.asList(1, 2, 3, 6, 7), multimap.get("foo")); assertEquals(Arrays.asList(4, 5), multimap.get("bar")); assertEquals(7, multimap.size()); } public void testBuilderPutAllWithDuplicates() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.putAll("foo", 1, 2, 3); builder.putAll("bar", 4, 5); builder.putAll("foo", 1, 6, 7); ImmutableListMultimap<String, Integer> multimap = builder.build(); assertEquals(Arrays.asList(1, 2, 3, 1, 6, 7), multimap.get("foo")); assertEquals(Arrays.asList(4, 5), multimap.get("bar")); assertEquals(8, multimap.size()); } public void testBuilderPutWithDuplicates() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.putAll("foo", 1, 2, 3); builder.putAll("bar", 4, 5); builder.put("foo", 1); ImmutableListMultimap<String, Integer> multimap = builder.build(); assertEquals(Arrays.asList(1, 2, 3, 1), multimap.get("foo")); assertEquals(Arrays.asList(4, 5), multimap.get("bar")); assertEquals(6, multimap.size()); } public void testBuilderPutAllMultimapWithDuplicates() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put("foo", 1); toPut.put("bar", 4); toPut.put("foo", 2); toPut.put("foo", 1); toPut.put("bar", 5); Multimap<String, Integer> moreToPut = LinkedListMultimap.create(); moreToPut.put("foo", 6); moreToPut.put("bar", 4); moreToPut.put("foo", 7); moreToPut.put("foo", 2); ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.putAll(toPut); builder.putAll(moreToPut); Multimap<String, Integer> multimap = builder.build(); assertEquals(Arrays.asList(1, 2, 1, 6, 7, 2), multimap.get("foo")); assertEquals(Arrays.asList(4, 5, 4), multimap.get("bar")); assertEquals(9, multimap.size()); } public void testBuilderPutNullKey() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put("foo", null); ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); try { builder.put(null, 1); fail(); } catch (NullPointerException expected) {} try { builder.putAll(null, Arrays.asList(1, 2, 3)); fail(); } catch (NullPointerException expected) {} try { builder.putAll(null, 1, 2, 3); fail(); } catch (NullPointerException expected) {} try { builder.putAll(toPut); fail(); } catch (NullPointerException expected) {} } public void testBuilderPutNullValue() { Multimap<String, Integer> toPut = LinkedListMultimap.create(); toPut.put(null, 1); ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); try { builder.put("foo", null); fail(); } catch (NullPointerException expected) {} try { builder.putAll("foo", Arrays.asList(1, null, 3)); fail(); } catch (NullPointerException expected) {} try { builder.putAll("foo", 1, null, 3); fail(); } catch (NullPointerException expected) {} try { builder.putAll(toPut); fail(); } catch (NullPointerException expected) {} } public void testBuilderOrderKeysBy() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.put("b", 3); builder.put("d", 2); builder.put("a", 5); builder.orderKeysBy(Collections.reverseOrder()); builder.put("c", 4); builder.put("a", 2); builder.put("b", 6); ImmutableListMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); ASSERT.that(multimap.values()).has().exactly(2, 4, 3, 6, 5, 2).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("b")).has().exactly(3, 6).inOrder(); } public void testBuilderOrderKeysByDuplicates() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.put("bb", 3); builder.put("d", 2); builder.put("a", 5); builder.orderKeysBy(new Ordering<String>() { @Override public int compare(String left, String right) { return left.length() - right.length(); } }); builder.put("cc", 4); builder.put("a", 2); builder.put("bb", 6); ImmutableListMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("d", "a", "bb", "cc").inOrder(); ASSERT.that(multimap.values()).has().exactly(2, 5, 2, 3, 6, 4).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("bb")).has().exactly(3, 6).inOrder(); } public void testBuilderOrderValuesBy() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.put("b", 3); builder.put("d", 2); builder.put("a", 5); builder.orderValuesBy(Collections.reverseOrder()); builder.put("c", 4); builder.put("a", 2); builder.put("b", 6); ImmutableListMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("b", "d", "a", "c").inOrder(); ASSERT.that(multimap.values()).has().exactly(6, 3, 2, 5, 2, 4).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("b")).has().exactly(6, 3).inOrder(); } public void testBuilderOrderKeysAndValuesBy() { ImmutableListMultimap.Builder<String, Integer> builder = ImmutableListMultimap.builder(); builder.put("b", 3); builder.put("d", 2); builder.put("a", 5); builder.orderKeysBy(Collections.reverseOrder()); builder.orderValuesBy(Collections.reverseOrder()); builder.put("c", 4); builder.put("a", 2); builder.put("b", 6); ImmutableListMultimap<String, Integer> multimap = builder.build(); ASSERT.that(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); ASSERT.that(multimap.values()).has().exactly(2, 4, 6, 3, 5, 2).inOrder(); ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); ASSERT.that(multimap.get("b")).has().exactly(6, 3).inOrder(); } public void testCopyOf() { ArrayListMultimap<String, Integer> input = ArrayListMultimap.create(); input.put("foo", 1); input.put("bar", 2); input.put("foo", 3); Multimap<String, Integer> multimap = ImmutableListMultimap.copyOf(input); assertEquals(multimap, input); assertEquals(input, multimap); } public void testCopyOfWithDuplicates() { ArrayListMultimap<String, Integer> input = ArrayListMultimap.create(); input.put("foo", 1); input.put("bar", 2); input.put("foo", 3); input.put("foo", 1); Multimap<String, Integer> multimap = ImmutableListMultimap.copyOf(input); assertEquals(multimap, input); assertEquals(input, multimap); } public void testCopyOfEmpty() { ArrayListMultimap<String, Integer> input = ArrayListMultimap.create(); Multimap<String, Integer> multimap = ImmutableListMultimap.copyOf(input); assertEquals(multimap, input); assertEquals(input, multimap); } public void testCopyOfImmutableListMultimap() { Multimap<String, Integer> multimap = createMultimap(); assertSame(multimap, ImmutableListMultimap.copyOf(multimap)); } public void testCopyOfNullKey() { ArrayListMultimap<String, Integer> input = ArrayListMultimap.create(); input.put(null, 1); try { ImmutableListMultimap.copyOf(input); fail(); } catch (NullPointerException expected) {} } public void testCopyOfNullValue() { ArrayListMultimap<String, Integer> input = ArrayListMultimap.create(); input.putAll("foo", Arrays.asList(1, null, 3)); try { ImmutableListMultimap.copyOf(input); fail(); } catch (NullPointerException expected) {} } public void testEmptyMultimapReads() { Multimap<String, Integer> multimap = ImmutableListMultimap.of(); assertFalse(multimap.containsKey("foo")); assertFalse(multimap.containsValue(1)); assertFalse(multimap.containsEntry("foo", 1)); assertTrue(multimap.entries().isEmpty()); assertTrue(multimap.equals(ArrayListMultimap.create())); assertEquals(Collections.emptyList(), multimap.get("foo")); assertEquals(0, multimap.hashCode()); assertTrue(multimap.isEmpty()); assertEquals(HashMultiset.create(), multimap.keys()); assertEquals(Collections.emptySet(), multimap.keySet()); assertEquals(0, multimap.size()); assertTrue(multimap.values().isEmpty()); assertEquals("{}", multimap.toString()); } public void testEmptyMultimapWrites() { Multimap<String, Integer> multimap = ImmutableListMultimap.of(); UnmodifiableCollectionTests.assertMultimapIsUnmodifiable( multimap, "foo", 1); } private Multimap<String, Integer> createMultimap() { return ImmutableListMultimap.<String, Integer>builder() .put("foo", 1).put("bar", 2).put("foo", 3).build(); } public void testMultimapReads() { Multimap<String, Integer> multimap = createMultimap(); assertTrue(multimap.containsKey("foo")); assertFalse(multimap.containsKey("cat")); assertTrue(multimap.containsValue(1)); assertFalse(multimap.containsValue(5)); assertTrue(multimap.containsEntry("foo", 1)); assertFalse(multimap.containsEntry("cat", 1)); assertFalse(multimap.containsEntry("foo", 5)); assertFalse(multimap.entries().isEmpty()); assertEquals(3, multimap.size()); assertFalse(multimap.isEmpty()); assertEquals("{foo=[1, 3], bar=[2]}", multimap.toString()); } public void testMultimapWrites() { Multimap<String, Integer> multimap = createMultimap(); UnmodifiableCollectionTests.assertMultimapIsUnmodifiable( multimap, "bar", 2); } public void testMultimapEquals() { Multimap<String, Integer> multimap = createMultimap(); Multimap<String, Integer> arrayListMultimap = ArrayListMultimap.create(); arrayListMultimap.putAll("foo", Arrays.asList(1, 3)); arrayListMultimap.put("bar", 2); new EqualsTester() .addEqualityGroup(multimap, createMultimap(), arrayListMultimap, ImmutableListMultimap.<String, Integer>builder() .put("bar", 2).put("foo", 1).put("foo", 3).build()) .addEqualityGroup(ImmutableListMultimap.<String, Integer>builder() .put("bar", 2).put("foo", 3).put("foo", 1).build()) .addEqualityGroup(ImmutableListMultimap.<String, Integer>builder() .put("foo", 2).put("foo", 3).put("foo", 1).build()) .addEqualityGroup(ImmutableListMultimap.<String, Integer>builder() .put("bar", 2).put("foo", 3).build()) .testEquals(); } public void testOf() { assertMultimapEquals( ImmutableListMultimap.of("one", 1), "one", 1); assertMultimapEquals( ImmutableListMultimap.of("one", 1, "two", 2), "one", 1, "two", 2); assertMultimapEquals( ImmutableListMultimap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3); assertMultimapEquals( ImmutableListMultimap.of("one", 1, "two", 2, "three", 3, "four", 4), "one", 1, "two", 2, "three", 3, "four", 4); assertMultimapEquals( ImmutableListMultimap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); } public void testInverse() { assertEquals( ImmutableListMultimap.<Integer, String>of(), ImmutableListMultimap.<String, Integer>of().inverse()); assertEquals( ImmutableListMultimap.of(1, "one"), ImmutableListMultimap.of("one", 1).inverse()); assertEquals( ImmutableListMultimap.of(1, "one", 2, "two"), ImmutableListMultimap.of("one", 1, "two", 2).inverse()); assertEquals( ImmutableListMultimap.of("of", 'o', "of", 'f', "to", 't', "to", 'o').inverse(), ImmutableListMultimap.of('o', "of", 'f', "of", 't', "to", 'o', "to")); assertEquals( ImmutableListMultimap.of('f', "foo", 'o', "foo", 'o', "foo"), ImmutableListMultimap.of("foo", 'f', "foo", 'o', "foo", 'o').inverse()); } public void testInverseMinimizesWork() { ImmutableListMultimap<String, Character> multimap = ImmutableListMultimap.<String, Character>builder() .put("foo", 'f') .put("foo", 'o') .put("foo", 'o') .put("poo", 'p') .put("poo", 'o') .put("poo", 'o') .build(); assertSame(multimap.inverse(), multimap.inverse()); assertSame(multimap, multimap.inverse().inverse()); } private static <K, V> void assertMultimapEquals(Multimap<K, V> multimap, Object... alternatingKeysAndValues) { assertEquals(multimap.size(), alternatingKeysAndValues.length / 2); int i = 0; for (Entry<K, V> entry : multimap.entries()) { assertEquals(alternatingKeysAndValues[i++], entry.getKey()); assertEquals(alternatingKeysAndValues[i++], entry.getValue()); } } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ImmutableListMultimapTest.java
Java
asf20
17,964
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.net; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Ascii; import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; /** * {@link TestCase} for {@link InternetDomainName}. * * @author Craig Berry */ @GwtCompatible(emulated = true) public final class InternetDomainNameTest extends TestCase { private static final InternetDomainName UNICODE_EXAMPLE = InternetDomainName.from("j\u00f8rpeland.no"); private static final InternetDomainName PUNYCODE_EXAMPLE = InternetDomainName.from("xn--jrpeland-54a.no"); /** * The Greek letter delta, used in unicode testing. */ private static final String DELTA = "\u0394"; /** * A domain part which is valid under lenient validation, but invalid under * strict validation. */ static final String LOTS_OF_DELTAS = Strings.repeat(DELTA, 62); private static final String ALMOST_TOO_MANY_LEVELS = Strings.repeat("a.", 127); private static final String ALMOST_TOO_LONG = Strings.repeat("aaaaa.", 40) + "1234567890.c"; private static final ImmutableSet<String> VALID_NAME = ImmutableSet.of( "foo.com", "f-_-o.cOM", "f--1.com", "f11-1.com", "www", "abc.a23", "biz.com.ua", "x", "fOo", "f--o", "f_a", "foo.net.us\uFF61ocm", "woo.com.", "a" + DELTA + "b.com", ALMOST_TOO_MANY_LEVELS, ALMOST_TOO_LONG); private static final ImmutableSet<String> INVALID_NAME = ImmutableSet.of( "", " ", "127.0.0.1", "::1", "13", "abc.12c", "foo-.com", "_bar.quux", "foo+bar.com", "foo!bar.com", ".foo.com", "..bar.com", "baz..com", "..quiffle.com", "fleeb.com..", ".", "..", "...", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com", "a" + DELTA + " .com", ALMOST_TOO_MANY_LEVELS + "com", ALMOST_TOO_LONG + ".c"); private static final ImmutableSet<String> PS = ImmutableSet.of( "com", "co.uk", "foo.bd", "xxxxxx.bd", "org.mK", "us", "uk\uFF61com.", // Alternate dot character "\u7f51\u7edc.Cn", // "网络.Cn" "j\u00f8rpeland.no", // "jorpeland.no" (first o slashed) "xn--jrpeland-54a.no" // IDNA (punycode) encoding of above ); private static final ImmutableSet<String> NO_PS = ImmutableSet.of( "www", "foo.google", "x.y.z"); private static final ImmutableSet<String> NON_PS = ImmutableSet.of( "foo.bar.com", "foo.ca", "foo.bar.ca", "foo.bar.co.il", "state.CA.us", "www.state.pa.us", "pvt.k12.ca.us", "www.google.com", "www4.yahoo.co.uk", "home.netscape.com", "web.MIT.edu", "foo.eDu.au", "utenti.blah.IT", "dominio.com.co"); private static final ImmutableSet<String> TOP_PRIVATE_DOMAIN = ImmutableSet.of("google.com", "foo.Co.uk", "foo.ca.us."); private static final ImmutableSet<String> UNDER_PRIVATE_DOMAIN = ImmutableSet.of("foo.bar.google.com", "a.b.co.uk", "x.y.ca.us"); private static final ImmutableSet<String> VALID_IP_ADDRS = ImmutableSet.of( "1.2.3.4", "127.0.0.1", "::1", "2001:db8::1"); private static final ImmutableSet<String> INVALID_IP_ADDRS = ImmutableSet.of( "", "1", "1.2.3", "...", "1.2.3.4.5", "400.500.600.700", ":", ":::1", "2001:db8:"); private static final ImmutableSet<String> SOMEWHERE_UNDER_PS = ImmutableSet.of( "foo.bar.google.com", "a.b.c.1.2.3.ca.us", "site.jp", "uomi-online.kir.jp", "jprs.co.jp", "site.quick.jp", "site.tenki.jp", "site.or.jp", "site.gr.jp", "site.ne.jp", "site.ac.jp", "site.ad.jp", "site.ed.jp", "site.geo.jp", "site.go.jp", "site.lg.jp", "1.fm", "site.cc", "site.ee", "site.fi", "site.fm", "site.gr", "www.leguide.ma", "site.ma", "some.org.mk", "site.mk", "site.tv", "site.us", "www.odev.us", "www.GOOGLE.com", "www.com", "google.com", "www7.google.co.uk", "google.Co.uK", "jobs.kt.com.", "home.netscape.com", "web.stanford.edu", "stanford.edu", "state.ca.us", "www.state.ca.us", "state.ca.us", "pvt.k12.ca.us", "www.rave.ca.", "cnn.ca", "ledger-enquirer.com", "it-trace.ch", "cool.dk", "cool.co.uk", "cool.de", "cool.es", "cool\uFF61fr", // Alternate dot character "cool.nl", "members.blah.nl.", "cool.se", "utenti.blah.it", "kt.co", "a\u7f51\u7edcA.\u7f51\u7edc.Cn" // "a网络A.网络.Cn" ); public void testValid() { for (String name : VALID_NAME) { InternetDomainName.from(name); } } public void testInvalid() { for (String name : INVALID_NAME) { try { InternetDomainName.from(name); fail("Should have been invalid: '" + name + "'"); } catch (IllegalArgumentException expected) { // Expected case } } } public void testPublicSuffix() { for (String name : PS) { final InternetDomainName domain = InternetDomainName.from(name); assertTrue(name, domain.isPublicSuffix()); assertTrue(name, domain.hasPublicSuffix()); assertFalse(name, domain.isUnderPublicSuffix()); assertFalse(name, domain.isTopPrivateDomain()); assertEquals(domain, domain.publicSuffix()); } for (String name : NO_PS) { final InternetDomainName domain = InternetDomainName.from(name); assertFalse(name, domain.isPublicSuffix()); assertFalse(name, domain.hasPublicSuffix()); assertFalse(name, domain.isUnderPublicSuffix()); assertFalse(name, domain.isTopPrivateDomain()); assertNull(domain.publicSuffix()); } for (String name : NON_PS) { final InternetDomainName domain = InternetDomainName.from(name); assertFalse(name, domain.isPublicSuffix()); assertTrue(name, domain.hasPublicSuffix()); assertTrue(name, domain.isUnderPublicSuffix()); } } public void testUnderPublicSuffix() { for (String name : SOMEWHERE_UNDER_PS) { final InternetDomainName domain = InternetDomainName.from(name); assertFalse(name, domain.isPublicSuffix()); assertTrue(name, domain.hasPublicSuffix()); assertTrue(name, domain.isUnderPublicSuffix()); } } public void testTopPrivateDomain() { for (String name : TOP_PRIVATE_DOMAIN) { final InternetDomainName domain = InternetDomainName.from(name); assertFalse(name, domain.isPublicSuffix()); assertTrue(name, domain.hasPublicSuffix()); assertTrue(name, domain.isUnderPublicSuffix()); assertTrue(name, domain.isTopPrivateDomain()); assertEquals(domain.parent(), domain.publicSuffix()); } } public void testUnderPrivateDomain() { for (String name : UNDER_PRIVATE_DOMAIN) { final InternetDomainName domain = InternetDomainName.from(name); assertFalse(name, domain.isPublicSuffix()); assertTrue(name, domain.hasPublicSuffix()); assertTrue(name, domain.isUnderPublicSuffix()); assertFalse(name, domain.isTopPrivateDomain()); } } public void testParent() { assertEquals( "com", InternetDomainName.from("google.com").parent().toString()); assertEquals( "uk", InternetDomainName.from("co.uk").parent().toString()); assertEquals( "google.com", InternetDomainName.from("www.google.com").parent().toString()); try { InternetDomainName.from("com").parent(); fail("'com' should throw ISE on .parent() call"); } catch (IllegalStateException expected) { } } public void testChild() { InternetDomainName domain = InternetDomainName.from("foo.com"); assertEquals("www.foo.com", domain.child("www").toString()); try { domain.child("www."); fail("www..google.com should have been invalid"); } catch (IllegalArgumentException expected) { // Expected outcome } } public void testParentChild() { InternetDomainName origin = InternetDomainName.from("foo.com"); InternetDomainName parent = origin.parent(); assertEquals("com", parent.toString()); // These would throw an exception if leniency were not preserved during parent() and child() // calls. InternetDomainName child = parent.child(LOTS_OF_DELTAS); child.child(LOTS_OF_DELTAS); } public void testValidTopPrivateDomain() { InternetDomainName googleDomain = InternetDomainName.from("google.com"); assertEquals(googleDomain, googleDomain.topPrivateDomain()); assertEquals(googleDomain, googleDomain.child("mail").topPrivateDomain()); assertEquals(googleDomain, googleDomain.child("foo.bar").topPrivateDomain()); } public void testInvalidTopPrivateDomain() { ImmutableSet<String> badCookieDomains = ImmutableSet.of("co.uk", "foo", "com"); for (String domain : badCookieDomains) { try { InternetDomainName.from(domain).topPrivateDomain(); fail(domain); } catch (IllegalStateException expected) { } } } public void testIsValid() { final Iterable<String> validCases = Iterables.concat( VALID_NAME, PS, NO_PS, NON_PS); final Iterable<String> invalidCases = Iterables.concat( INVALID_NAME, VALID_IP_ADDRS, INVALID_IP_ADDRS); for (String valid : validCases) { assertTrue(valid, InternetDomainName.isValid(valid)); } for (String invalid : invalidCases) { assertFalse(invalid, InternetDomainName.isValid(invalid)); } } public void testToString() { for (String inputName : SOMEWHERE_UNDER_PS) { InternetDomainName domain = InternetDomainName.from(inputName); /* * We would ordinarily use constants for the expected results, but * doing it by derivation allows us to reuse the test case definitions * used in other tests. */ String expectedName = Ascii.toLowerCase(inputName); expectedName = expectedName.replaceAll("[\u3002\uFF0E\uFF61]", "."); if (expectedName.endsWith(".")) { expectedName = expectedName.substring(0, expectedName.length() - 1); } assertEquals(expectedName, domain.toString()); } } public void testExclusion() { InternetDomainName domain = InternetDomainName.from("foo.nic.uk"); assertTrue(domain.hasPublicSuffix()); assertEquals("uk", domain.publicSuffix().toString()); // Behold the weirdness! assertFalse(domain.publicSuffix().isPublicSuffix()); } public void testMultipleUnders() { // PSL has both *.uk and *.sch.uk; the latter should win. // See http://code.google.com/p/guava-libraries/issues/detail?id=1176 InternetDomainName domain = InternetDomainName.from("www.essex.sch.uk"); assertTrue(domain.hasPublicSuffix()); assertEquals("essex.sch.uk", domain.publicSuffix().toString()); assertEquals("www.essex.sch.uk", domain.topPrivateDomain().toString()); } public void testEquality() { new EqualsTester() .addEqualityGroup( idn("google.com"), idn("google.com"), idn("GOOGLE.COM")) .addEqualityGroup(idn("www.google.com")) .addEqualityGroup(UNICODE_EXAMPLE) .addEqualityGroup(PUNYCODE_EXAMPLE) .testEquals(); } private static InternetDomainName idn(String domain) { return InternetDomainName.from(domain); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/net/super/com/google/common/net/InternetDomainNameTest.java
Java
asf20
12,532
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.net; import static com.google.common.base.Charsets.UTF_8; import static com.google.common.net.MediaType.ANY_APPLICATION_TYPE; import static com.google.common.net.MediaType.ANY_AUDIO_TYPE; import static com.google.common.net.MediaType.ANY_IMAGE_TYPE; import static com.google.common.net.MediaType.ANY_TEXT_TYPE; import static com.google.common.net.MediaType.ANY_TYPE; import static com.google.common.net.MediaType.ANY_VIDEO_TYPE; import static com.google.common.net.MediaType.HTML_UTF_8; import static com.google.common.net.MediaType.JPEG; import static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Optional; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMultimap; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; /** * Tests for {@link MediaType}. * * @author Gregory Kick */ @Beta @GwtCompatible(emulated = true) public class MediaTypeTest extends TestCase { public void testCreate_invalidType() { try { MediaType.create("te><t", "plaintext"); fail(); } catch (IllegalArgumentException expected) {} } public void testCreate_invalidSubtype() { try { MediaType.create("text", "pl@intext"); fail(); } catch (IllegalArgumentException expected) {} } public void testCreate_wildcardTypeDeclaredSubtype() { try { MediaType.create("*", "text"); fail(); } catch (IllegalArgumentException expected) {} } public void testCreateApplicationType() { MediaType newType = MediaType.createApplicationType("yams"); assertEquals("application", newType.type()); assertEquals("yams", newType.subtype()); } public void testCreateAudioType() { MediaType newType = MediaType.createAudioType("yams"); assertEquals("audio", newType.type()); assertEquals("yams", newType.subtype()); } public void testCreateImageType() { MediaType newType = MediaType.createImageType("yams"); assertEquals("image", newType.type()); assertEquals("yams", newType.subtype()); } public void testCreateTextType() { MediaType newType = MediaType.createTextType("yams"); assertEquals("text", newType.type()); assertEquals("yams", newType.subtype()); } public void testCreateVideoType() { MediaType newType = MediaType.createVideoType("yams"); assertEquals("video", newType.type()); assertEquals("yams", newType.subtype()); } public void testGetType() { assertEquals("text", MediaType.parse("text/plain").type()); assertEquals("application", MediaType.parse("application/atom+xml; charset=utf-8").type()); } public void testGetSubtype() { assertEquals("plain", MediaType.parse("text/plain").subtype()); assertEquals("atom+xml", MediaType.parse("application/atom+xml; charset=utf-8").subtype()); } private static final ImmutableListMultimap<String, String> PARAMETERS = ImmutableListMultimap.of("a", "1", "a", "2", "b", "3"); public void testGetParameters() { assertEquals(ImmutableListMultimap.of(), MediaType.parse("text/plain").parameters()); assertEquals(ImmutableListMultimap.of("charset", "utf-8"), MediaType.parse("application/atom+xml; charset=utf-8").parameters()); assertEquals(PARAMETERS, MediaType.parse("application/atom+xml; a=1; a=2; b=3").parameters()); } public void testWithoutParameters() { assertSame(MediaType.parse("image/gif"), MediaType.parse("image/gif").withoutParameters()); assertEquals(MediaType.parse("image/gif"), MediaType.parse("image/gif; foo=bar").withoutParameters()); } public void testWithParameters() { assertEquals(MediaType.parse("text/plain; a=1; a=2; b=3"), MediaType.parse("text/plain").withParameters(PARAMETERS)); assertEquals(MediaType.parse("text/plain; a=1; a=2; b=3"), MediaType.parse("text/plain; a=1; a=2; b=3").withParameters(PARAMETERS)); } public void testWithParameters_invalidAttribute() { MediaType mediaType = MediaType.parse("text/plain"); ImmutableListMultimap<String, String> parameters = ImmutableListMultimap.of("a", "1", "@", "2", "b", "3"); try { mediaType.withParameters(parameters); fail(); } catch (IllegalArgumentException expected) {} } public void testWithParameter() { assertEquals(MediaType.parse("text/plain; a=1"), MediaType.parse("text/plain").withParameter("a", "1")); assertEquals(MediaType.parse("text/plain; a=1"), MediaType.parse("text/plain; a=1; a=2").withParameter("a", "1")); assertEquals(MediaType.parse("text/plain; a=3"), MediaType.parse("text/plain; a=1; a=2").withParameter("a", "3")); assertEquals(MediaType.parse("text/plain; a=1; a=2; b=3"), MediaType.parse("text/plain; a=1; a=2").withParameter("b", "3")); } public void testWithParameter_invalidAttribute() { MediaType mediaType = MediaType.parse("text/plain"); try { mediaType.withParameter("@", "2"); fail(); } catch (IllegalArgumentException expected) {} } public void testWithCharset() { assertEquals(MediaType.parse("text/plain; charset=utf-8"), MediaType.parse("text/plain").withCharset(UTF_8)); assertEquals(MediaType.parse("text/plain; charset=utf-8"), MediaType.parse("text/plain; charset=utf-16").withCharset(UTF_8)); } public void testHasWildcard() { assertFalse(PLAIN_TEXT_UTF_8.hasWildcard()); assertFalse(JPEG.hasWildcard()); assertTrue(ANY_TYPE.hasWildcard()); assertTrue(ANY_APPLICATION_TYPE.hasWildcard()); assertTrue(ANY_AUDIO_TYPE.hasWildcard()); assertTrue(ANY_IMAGE_TYPE.hasWildcard()); assertTrue(ANY_TEXT_TYPE.hasWildcard()); assertTrue(ANY_VIDEO_TYPE.hasWildcard()); } public void testIs() { assertTrue(PLAIN_TEXT_UTF_8.is(ANY_TYPE)); assertTrue(JPEG.is(ANY_TYPE)); assertTrue(ANY_TEXT_TYPE.is(ANY_TYPE)); assertTrue(PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE)); assertTrue(PLAIN_TEXT_UTF_8.withoutParameters().is(ANY_TEXT_TYPE)); assertFalse(JPEG.is(ANY_TEXT_TYPE)); assertTrue(PLAIN_TEXT_UTF_8.is(PLAIN_TEXT_UTF_8)); assertTrue(PLAIN_TEXT_UTF_8.is(PLAIN_TEXT_UTF_8.withoutParameters())); assertFalse(PLAIN_TEXT_UTF_8.withoutParameters().is(PLAIN_TEXT_UTF_8)); assertFalse(PLAIN_TEXT_UTF_8.is(HTML_UTF_8)); assertFalse(PLAIN_TEXT_UTF_8.withParameter("charset", "UTF-16").is(PLAIN_TEXT_UTF_8)); assertFalse(PLAIN_TEXT_UTF_8.is(PLAIN_TEXT_UTF_8.withParameter("charset", "UTF-16"))); } public void testParse_empty() { try { MediaType.parse(""); fail(); } catch (IllegalArgumentException expected) {} } public void testParse_badInput() { try { MediaType.parse("/"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("te<t/plain"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/pl@in"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain;"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; "); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a="); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=@"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=\"@"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=1;"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=1; "); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=1; b"); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=1; b="); fail(); } catch (IllegalArgumentException expected) {} try { MediaType.parse("text/plain; a=\u2025"); fail(); } catch (IllegalArgumentException expected) {} } public void testGetCharset() { assertEquals(Optional.absent(), MediaType.parse("text/plain").charset()); assertEquals(Optional.of(UTF_8), MediaType.parse("text/plain; charset=utf-8").charset()); } public void testGetCharset_tooMany() { MediaType mediaType = MediaType.parse("text/plain; charset=utf-8; charset=utf-16"); try { mediaType.charset(); fail(); } catch (IllegalStateException expected) {} } public void testGetCharset_illegalCharset() { MediaType mediaType = MediaType.parse( "text/plain; charset=\"!@#$%^&*()\""); try { mediaType.charset(); fail(); } catch (IllegalCharsetNameException expected) {} } public void testGetCharset_unsupportedCharset() { MediaType mediaType = MediaType.parse( "text/plain; charset=utf-wtf"); try { mediaType.charset(); fail(); } catch (UnsupportedCharsetException expected) {} } public void testEquals() { new EqualsTester() .addEqualityGroup(MediaType.create("text", "plain"), MediaType.create("TEXT", "PLAIN"), MediaType.parse("text/plain"), MediaType.parse("TEXT/PLAIN"), MediaType.create("text", "plain").withParameter("a", "1").withoutParameters()) .addEqualityGroup( MediaType.create("text", "plain").withCharset(UTF_8), MediaType.create("text", "plain").withParameter("CHARSET", "UTF-8"), MediaType.create("text", "plain").withParameters( ImmutableMultimap.of("charset", "utf-8")), MediaType.parse("text/plain;charset=utf-8"), MediaType.parse("text/plain; charset=utf-8"), MediaType.parse("text/plain; charset=utf-8"), MediaType.parse("text/plain; \tcharset=utf-8"), MediaType.parse("text/plain; \r\n\tcharset=utf-8"), MediaType.parse("text/plain; CHARSET=utf-8"), MediaType.parse("text/plain; charset=\"utf-8\""), MediaType.parse("text/plain; charset=\"\\u\\tf-\\8\""), MediaType.parse("text/plain; charset=UTF-8")) .addEqualityGroup(MediaType.parse("text/plain; charset=utf-8; charset=utf-8")) .addEqualityGroup(MediaType.create("text", "plain").withParameter("a", "value"), MediaType.create("text", "plain").withParameter("A", "value")) .addEqualityGroup(MediaType.create("text", "plain").withParameter("a", "VALUE"), MediaType.create("text", "plain").withParameter("A", "VALUE")) .addEqualityGroup( MediaType.create("text", "plain") .withParameters(ImmutableListMultimap.of("a", "1", "a", "2")), MediaType.create("text", "plain") .withParameters(ImmutableListMultimap.of("a", "2", "a", "1"))) .addEqualityGroup(MediaType.create("text", "csv")) .addEqualityGroup(MediaType.create("application", "atom+xml")) .testEquals(); } public void testToString() { assertEquals("text/plain", MediaType.create("text", "plain").toString()); assertEquals("text/plain; something=\"cr@zy\"; something-else=\"crazy with spaces\"", MediaType.create("text", "plain") .withParameter("something", "cr@zy") .withParameter("something-else", "crazy with spaces") .toString()); } }
zzhhhhh-aw4rwer
guava-gwt/test-super/com/google/common/net/super/com/google/common/net/MediaTypeTest.java
Java
asf20
12,770
SELECT [name] ,[idcode] ,[sex] ,[birthday] ,[location] ,[locationcode] ,[poname] ,[poldcode] ,[onechildcardcode] ,[childbirthday] ,[childsex] ,[paydate] ,[paynum] ,[isoldinsure] ,[lushi] ,[lushidate] ,[shenghe] ,[shengheren] ,[shenghedate] ,[shenghenoreason] ,[familycode] ,[unitname] ,[unitxingzhi] ,[username] ,[inputdate] FROM [lydxDB].[dbo].[dsznfmjlb]
zzlydx-jiftle
trunk/SqlScript/查询脚本.sql
TSQL
asf20
527
sp_configure 'show advanced options', 1; GO RECONFIGURE; GO sp_configure 'min server memory', 5; GO RECONFIGURE; GO sp_configure 'max server memory', 50; GO RECONFIGURE; GO sp_configure 'show advanced options', 0; GO RECONFIGURE; GO
zzlydx-jiftle
trunk/SqlScript/设置MSSQL内存占用.sql
TSQL
asf20
249
<%@ Application Codebehind="Global.asax.cs" Inherits="zzlydx.Global" Language="C#" %>
zzlydx-jiftle
trunk/zzlydx/Global.asax
ASP.NET
asf20
90
/*@charset "utf-8"; html {background: #FFF;} body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,p,blockquote,th,td,ins,hr{margin: 0px;padding: 0px;} p{cursor: text;} h1,h2,h3,h4,h5,h6{font-size:100%;} ol,ul{list-style-type: none;} address,caption,cite,code,dfn,em,th,var{font-style:normal;font-weight:normal;} table{border-collapse:collapse;} fieldset,img{border:0;} img{display:block;} caption,th{text-align:left;} body{position: relative;font-size:62.5%;font-family: "宋体"} a{text-decoration: none;}/* /*demo所用元素值*/ li{margin: 0px;padding: 0px;} dfn{font-style:normal;font-weight:normal;} #need {margin: 20px auto 0;width: 610px;} #need li {height: 26px;width: 600px;font: 12px/26px Arial, Helvetica, sans-serif;background: #FFD;border-bottom: 1px dashed #E0E0E0;display: block;cursor: text;padding: 7px 0px 7px 10px!important;padding: 5px 0px 5px 10px;} #need li:hover,#need li.hover {background: #FFE8E8;} #need input {line-height: 14px;background: #FFF;height: 14px;width: 200px;border: 1px solid #E0E0E0;vertical-align: middle;padding: 6px;} #need label {padding-left: 30px;} #need label.old_password {background-position: 0 -277px;} #need label.new_password {background-position: 0 -1576px;} #need label.rePassword {background-position: 0 -1638px;} #need label.email {background-position: 0 -429px;} #need dfn {display: none;} #need li:hover dfn, #need li.hover dfn {display:inline;margin-left: 7px;color: #676767;}
zzlydx-jiftle
trunk/zzlydx/Styles/StyleSheet_jiftle.css
CSS
asf20
1,484
/* DEFAULTS ----------------------------------------------------------*/ body { background: #b6b7bc; font-size: .80em; font-family: "Helvetica Neue", "Lucida Grande", "Segoe UI", Arial, Helvetica, Verdana, sans-serif; margin: 0px; padding: 0px; color: #696969; } a:link, a:visited { color: #034af3; } a:hover { color: #1d60ff; text-decoration: none; } a:active { color: #034af3; } p { margin-bottom: 10px; line-height: 1.6em; } /* HEADINGS ----------------------------------------------------------*/ h1, h2, h3, h4, h5, h6 { font-size: 1.5em; color: #666666; font-variant: small-caps; text-transform: none; font-weight: 200; margin-bottom: 0px; } h1 { font-size: 1.6em; padding-bottom: 0px; margin-bottom: 0px; } h2 { font-size: 1.5em; font-weight: 600; } h3 { font-size: 1.2em; } h4 { font-size: 1.1em; } h5, h6 { font-size: 1em; } /* this rule styles <h1> and <h2> tags that are the first child of the left and right table columns */ .rightColumn > h1, .rightColumn > h2, .leftColumn > h1, .leftColumn > h2 { margin-top: 0px; } /* PRIMARY LAYOUT ELEMENTS ----------------------------------------------------------*/ .page { width: 960px; background-color: #fff; margin: 20px auto 0px auto; border: 1px solid #496077; } .header { position: relative; margin: 0px; padding: 0px; background: #4b6c9e; width: 100%; } .header h1 { font-weight: 700; margin: 0px; padding: 0px 0px 0px 20px; color: #f9f9f9; border: none; line-height: 2em; font-size: 2em; } .main { padding: 0px 12px; margin: 12px 8px 8px 8px; min-height: 420px; } .leftCol { padding: 6px 0px; margin: 12px 8px 8px 8px; width: 200px; min-height: 200px; } .footer { color: #4e5766; padding: 8px 0px 0px 0px; margin: 0px auto; text-align: center; line-height: normal; } /* TAB MENU ----------------------------------------------------------*/ div.hideSkiplink { background-color:#3a4f63; width:100%; } div.menu { padding: 4px 0px 4px 8px; } div.menu ul { list-style: none; margin: 0px; padding: 0px; width: auto; } div.menu ul li a, div.menu ul li a:visited { background-color: #465c71; border: 1px #4e667d solid; color: #dde4ec; display: block; line-height: 1.35em; padding: 4px 20px; text-decoration: none; white-space: nowrap; } div.menu ul li a:hover { background-color: #bfcbd6; color: #465c71; text-decoration: none; } div.menu ul li a:active { background-color: #465c71; color: #cfdbe6; text-decoration: none; } /* FORM ELEMENTS ----------------------------------------------------------*/ fieldset { margin: 1em 0px; padding: 1em; border: 1px solid #ccc; } fieldset p { margin: 2px 12px 10px 10px; } fieldset.login label, fieldset.register label, fieldset.changePassword label { display: block; } fieldset label.inline { display: inline; } legend { font-size: 1.1em; font-weight: 600; padding: 2px 4px 8px 4px; } input.textEntry { width: 320px; border: 1px solid #ccc; } input.passwordEntry { width: 320px; border: 1px solid #ccc; } div.accountInfo { width: 42%; } /* MISC ----------------------------------------------------------*/ .clear { clear: both; } .title { display: block; float: left; text-align: left; width: auto; } .loginDisplay { font-size: 1.1em; display: block; text-align: right; padding: 10px; color: White; } .loginDisplay a:link { color: white; } .loginDisplay a:visited { color: white; } .loginDisplay a:hover { color: white; } .failureNotification { font-size: 1.2em; color: Red; } .bold { font-weight: bold; } .submitButton { text-align: right; padding-right: 10px; }
zzlydx-jiftle
trunk/zzlydx/Styles/Site.css
CSS
asf20
4,256
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OnlyOneChildQuery.aspx.cs" Inherits="zzlydx.OnlyOneChildQuery_1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" CellPadding="4" Width="100%" ForeColor="Black" HorizontalAlign="Center" Font-Size="12px" Font-Underline="False" AllowSorting="True" AllowPaging="True" DataSourceID="SqlDataSource1" > <RowStyle BackColor="#F7F6F3" ForeColor="#333333" Wrap="False" /> <EditRowStyle BackColor="#999999" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" Wrap="False" /> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> <Columns> <asp:BoundField DataField="姓名" HeaderText="姓名" SortExpression="姓名" /> <asp:BoundField DataField="身份证号" HeaderText="身份证号" SortExpression="身份证号" /> <asp:BoundField DataField="性别" HeaderText="性别" SortExpression="性别" /> <asp:BoundField DataField="出生日期" HeaderText="出生日期" SortExpression="出生日期" /> <asp:BoundField DataField="户籍地" HeaderText="户籍地" SortExpression="户籍地" /> <asp:BoundField DataField="户籍地代码" HeaderText="户籍地代码" SortExpression="户籍地代码" /> <asp:BoundField DataField="配偶姓名" HeaderText="配偶姓名" SortExpression="配偶姓名" /> <asp:BoundField DataField="配偶身份证号" HeaderText="配偶身份证号" SortExpression="配偶身份证号" /> <asp:BoundField DataField="独生子女证编号" HeaderText="独生子女证编号" SortExpression="独生子女证编号" /> <asp:BoundField DataField="孩子出生日期" HeaderText="孩子出生日期" SortExpression="孩子出生日期" /> <asp:BoundField DataField="孩子性别" HeaderText="孩子性别" SortExpression="孩子性别" /> <asp:BoundField DataField="发放日期" HeaderText="发放日期" SortExpression="发放日期" /> <asp:BoundField DataField="发放日期1" HeaderText="发放日期1" SortExpression="发放日期1" /> <asp:BoundField DataField="是否参加养老保险" HeaderText="是否参加养老保险" SortExpression="是否参加养老保险" /> <asp:BoundField DataField="落实情况" HeaderText="落实情况" SortExpression="落实情况" /> <asp:BoundField DataField="落实日期" HeaderText="落实日期" SortExpression="落实日期" /> <asp:BoundField DataField="审核情况" HeaderText="审核情况" SortExpression="审核情况" /> <asp:BoundField DataField="审核人" HeaderText="审核人" SortExpression="审核人" /> <asp:BoundField DataField="审核日期" HeaderText="审核日期" SortExpression="审核日期" /> <asp:BoundField DataField="审核不通过原因" HeaderText="审核不通过原因" SortExpression="审核不通过原因" /> <asp:BoundField DataField="户编号" HeaderText="户编号" SortExpression="户编号" /> <asp:BoundField DataField="单位名称" HeaderText="单位名称" SortExpression="单位名称" /> <asp:BoundField DataField="单位性质" HeaderText="单位性质" SortExpression="单位性质" /> <asp:BoundField DataField="操作员" HeaderText="操作员" SortExpression="操作员" /> <asp:BoundField DataField="录入时间" HeaderText="录入时间" SortExpression="录入时间" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT name AS 姓名, idcode AS 身份证号, sex AS 性别, birthday AS 出生日期, location AS 户籍地, locationcode AS 户籍地代码, poname AS 配偶姓名, poldcode AS 配偶身份证号, onechildcardcode AS 独生子女证编号, childbirthday AS 孩子出生日期, childsex AS 孩子性别, paydate AS 发放日期, paynum AS 发放日期, isoldinsure AS 是否参加养老保险, lushi AS 落实情况, lushidate AS 落实日期, shenghe AS 审核情况, shengheren AS 审核人, shenghedate AS 审核日期, shenghenoreason AS 审核不通过原因, familycode AS 户编号, unitname AS 单位名称, unitxingzhi AS 单位性质, username AS 操作员, inputdate AS 录入时间 FROM dsznfmjlb"></asp:SqlDataSource> </div> </form> </body> </html>
zzlydx-jiftle
trunk/zzlydx/OnlyOneChildQuery.aspx
ASP.NET
asf20
5,149
/* * My97 DatePicker 4.7 Skin:whyGreen */ .WdateDiv{ width:180px; background-color:#fff; border:#C5E1E4 1px solid; padding:2px; } .WdateDiv2{ width:360px; } .WdateDiv *{font-size:9pt;} .WdateDiv .NavImg a{ cursor:pointer; display:block; width:16px; height:16px; margin-top:1px; } .WdateDiv .NavImgll a{ float:left; background:url(img.gif) no-repeat; } .WdateDiv .NavImgl a{ float:left; background:url(img.gif) no-repeat -16px 0px; } .WdateDiv .NavImgr a{ float:right; background:url(img.gif) no-repeat -32px 0px; } .WdateDiv .NavImgrr a{ float:right; background:url(img.gif) no-repeat -48px 0px; } .WdateDiv #dpTitle{ height:24px; padding:1px; border:#c5d9e8 1px solid; background:url(bg.jpg); margin-bottom:2px; } .WdateDiv .yminput{ margin-top:2px; text-align:center; border:0px; height:20px; width:50px; color:#034c50; background-color:transparent; cursor:pointer; } .WdateDiv .yminputfocus{ margin-top:2px; text-align:center; border:#939393 1px solid; font-weight:bold; color:#034c50; height:20px; width:50px; } .WdateDiv .menuSel{ z-index:1; position:absolute; background-color:#FFFFFF; border:#A3C6C8 1px solid; display:none; } .WdateDiv .menu{ cursor:pointer; background-color:#fff; color:#11777C; } .WdateDiv .menuOn{ cursor:pointer; background-color:#BEEBEE; } .WdateDiv .invalidMenu{ color:#aaa; } .WdateDiv .YMenu{ margin-top:20px; } .WdateDiv .MMenu{ margin-top:20px; *width:62px; } .WdateDiv .hhMenu{ margin-top:-90px; margin-left:26px; } .WdateDiv .mmMenu{ margin-top:-46px; margin-left:26px; } .WdateDiv .ssMenu{ margin-top:-24px; margin-left:26px; } .WdateDiv .Wweek { text-align:center; background:#DAF3F5; border-right:#BDEBEE 1px solid; } .WdateDiv .MTitle{ color:#13777e; background-color:#bdebee; } .WdateDiv .WdayTable2{ border-collapse:collapse; border:#BEE9F0 1px solid; } .WdateDiv .WdayTable2 table{ border:0; } .WdateDiv .WdayTable{ line-height:20px; color:#13777e; background-color:#edfbfb; border:#BEE9F0 1px solid; } .WdateDiv .WdayTable td{ text-align:center; } .WdateDiv .Wday{ cursor:pointer; } .WdateDiv .WdayOn{ cursor:pointer; background-color:#74d2d9 ; } .WdateDiv .Wwday{ cursor:pointer; color:#ab1e1e; } .WdateDiv .WwdayOn{ cursor:pointer; background-color:#74d2d9; } .WdateDiv .Wtoday{ cursor:pointer; color:blue; } .WdateDiv .Wselday{ background-color:#A7E2E7; } .WdateDiv .WspecialDay{ background-color:#66F4DF; } .WdateDiv .WotherDay{ cursor:pointer; color:#0099CC; } .WdateDiv .WotherDayOn{ cursor:pointer; background-color:#C0EBEF; } .WdateDiv .WinvalidDay{ color:#aaa; } .WdateDiv #dpTime{ float:left; margin-top:3px; margin-right:30px; } .WdateDiv #dpTime #dpTimeStr{ margin-left:1px; color:#497F7F; } .WdateDiv #dpTime input{ height:20px; width:18px; text-align:center; color:#333; border:#61CAD0 1px solid; } .WdateDiv #dpTime .tB{ border-right:0px; } .WdateDiv #dpTime .tE{ border-left:0; border-right:0; } .WdateDiv #dpTime .tm{ width:7px; border-left:0; border-right:0; } .WdateDiv #dpTime #dpTimeUp{ height:10px; width:13px; border:0px; background:url(img.gif) no-repeat -32px -16px; } .WdateDiv #dpTime #dpTimeDown{ height:10px; width:13px; border:0px; background:url(img.gif) no-repeat -48px -16px; } .WdateDiv #dpQS { float:left; margin-right:3px; margin-top:3px; background:url(img.gif) no-repeat 0px -16px; width:20px; height:20px; cursor:pointer; } .WdateDiv #dpControl { text-align:right; margin-top:3px; } .WdateDiv .dpButton{ height:20px; width:45px; margin-top:2px; border:#38B1B9 1px solid; background-color:#CFEBEE; color:#08575B; }
zzlydx-jiftle
trunk/zzlydx/My97DatePicker/skin/whyGreen/datepicker.css
CSS
asf20
3,933
.Wdate{ border:#999 1px solid; height:20px; background:#fff url(datePicker.gif) no-repeat right; } .WdateFmtErr{ font-weight:bold; color:red; }
zzlydx-jiftle
trunk/zzlydx/My97DatePicker/skin/WdatePicker.css
CSS
asf20
158
/* * My97 DatePicker 4.7 */ .WdateDiv{ width:180px; background-color:#FFFFFF; border:#bbb 1px solid; padding:2px; } .WdateDiv2{ width:360px; } .WdateDiv *{font-size:9pt;} .WdateDiv .NavImg a{ display:block; cursor:pointer; height:16px; width:16px; } .WdateDiv .NavImgll a{ float:left; background:transparent url(img.gif) no-repeat scroll 0 0; } .WdateDiv .NavImgl a{ float:left; background:transparent url(img.gif) no-repeat scroll -16px 0; } .WdateDiv .NavImgr a{ float:right; background:transparent url(img.gif) no-repeat scroll -32px 0; } .WdateDiv .NavImgrr a{ float:right; background:transparent url(img.gif) no-repeat scroll -48px 0; } .WdateDiv #dpTitle{ height:24px; margin-bottom:2px; padding:1px; } .WdateDiv .yminput{ margin-top:2px; text-align:center; height:20px; border:0px; width:50px; cursor:pointer; } .WdateDiv .yminputfocus{ margin-top:2px; text-align:center; font-weight:bold; height:20px; color:blue; border:#ccc 1px solid; width:50px; } .WdateDiv .menuSel{ z-index:1; position:absolute; background-color:#FFFFFF; border:#ccc 1px solid; display:none; } .WdateDiv .menu{ cursor:pointer; background-color:#fff; } .WdateDiv .menuOn{ cursor:pointer; background-color:#BEEBEE; } .WdateDiv .invalidMenu{ color:#aaa; } .WdateDiv .YMenu{ margin-top:20px; } .WdateDiv .MMenu{ margin-top:20px; *width:62px; } .WdateDiv .hhMenu{ margin-top:-90px; margin-left:26px; } .WdateDiv .mmMenu{ margin-top:-46px; margin-left:26px; } .WdateDiv .ssMenu{ margin-top:-24px; margin-left:26px; } .WdateDiv .Wweek { text-align:center; background:#DAF3F5; border-right:#BDEBEE 1px solid; } .WdateDiv .MTitle{ background-color:#BDEBEE; } .WdateDiv .WdayTable2{ border-collapse:collapse; border:#c5d9e8 1px solid; } .WdateDiv .WdayTable2 table{ border:0; } .WdateDiv .WdayTable{ line-height:20px; border:#c5d9e8 1px solid; } .WdateDiv .WdayTable td{ text-align:center; } .WdateDiv .Wday{ cursor:pointer; } .WdateDiv .WdayOn{ cursor:pointer; background-color:#C0EBEF; } .WdateDiv .Wwday{ cursor:pointer; color:#FF2F2F; } .WdateDiv .WwdayOn{ cursor:pointer; color:#000; background-color:#C0EBEF; } .WdateDiv .Wtoday{ cursor:pointer; color:blue; } .WdateDiv .Wselday{ background-color:#A9E4E9; } .WdateDiv .WspecialDay{ background-color:#66F4DF; } .WdateDiv .WotherDay{ cursor:pointer; color:#6A6AFF; } .WdateDiv .WotherDayOn{ cursor:pointer; background-color:#C0EBEF; } .WdateDiv .WinvalidDay{ color:#aaa; } .WdateDiv #dpTime{ float:left; margin-top:3px; margin-right:30px; } .WdateDiv #dpTime #dpTimeStr{ margin-left:1px; } .WdateDiv #dpTime input{ width:18px; height:20px; text-align:center; border:#ccc 1px solid; } .WdateDiv #dpTime .tB{ border-right:0px; } .WdateDiv #dpTime .tE{ border-left:0; border-right:0; } .WdateDiv #dpTime .tm{ width:7px; border-left:0; border-right:0; } .WdateDiv #dpTime #dpTimeUp{ height:10px; width:13px; border:0px; background:url(img.gif) no-repeat -32px -16px; } .WdateDiv #dpTime #dpTimeDown{ height:10px; width:13px; border:0px; background:url(img.gif) no-repeat -48px -16px; } .WdateDiv #dpQS { float:left; margin-right:3px; margin-top:3px; background:url(img.gif) no-repeat 0px -16px; width:20px; height:20px; cursor:pointer; } .WdateDiv #dpControl { text-align:right; } .WdateDiv .dpButton{ height:20px; width:45px; border:#ccc 1px solid; margin-top:2px; margin-right:1px; }
zzlydx-jiftle
trunk/zzlydx/My97DatePicker/skin/default/datepicker.css
CSS
asf20
3,726
var $lang={ errAlertMsg: "\u4E0D\u5408\u6CD5\u7684\u65E5\u671F\u683C\u5F0F\u6216\u8005\u65E5\u671F\u8D85\u51FA\u9650\u5B9A\u7BC4\u570D,\u9700\u8981\u64A4\u92B7\u55CE?", aWeekStr: ["\u5468","\u65E5","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"], aLongWeekStr:["\u5468","\u661F\u671F\u65E5","\u661F\u671F\u4E00","\u661F\u671F\u4E8C","\u661F\u671F\u4E09","\u661F\u671F\u56DB","\u661F\u671F\u4E94","\u661F\u671F\u516D"], aMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00","\u5341\u4E8C"], aLongMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00\u6708","\u5341\u4E8C\u6708"], clearStr: "\u6E05\u7A7A", todayStr: "\u4ECA\u5929", okStr: "\u78BA\u5B9A", updateStr: "\u78BA\u5B9A", timeStr: "\u6642\u9593", quickStr: "\u5FEB\u901F\u9078\u64C7", err_1: '\u6700\u5C0F\u65E5\u671F\u4E0D\u80FD\u5927\u65BC\u6700\u5927\u65E5\u671F!' }
zzlydx-jiftle
trunk/zzlydx/My97DatePicker/lang/zh-tw.js
JavaScript
asf20
1,088
var $lang={ errAlertMsg: "\u4E0D\u5408\u6CD5\u7684\u65E5\u671F\u683C\u5F0F\u6216\u8005\u65E5\u671F\u8D85\u51FA\u9650\u5B9A\u8303\u56F4,\u9700\u8981\u64A4\u9500\u5417?", aWeekStr: ["\u5468","\u65E5","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"], aLongWeekStr:["\u5468","\u661F\u671F\u65E5","\u661F\u671F\u4E00","\u661F\u671F\u4E8C","\u661F\u671F\u4E09","\u661F\u671F\u56DB","\u661F\u671F\u4E94","\u661F\u671F\u516D"], aMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00","\u5341\u4E8C"], aLongMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00\u6708","\u5341\u4E8C\u6708"], clearStr: "\u6E05\u7A7A", todayStr: "\u4ECA\u5929", okStr: "\u786E\u5B9A", updateStr: "\u786E\u5B9A", timeStr: "\u65F6\u95F4", quickStr: "\u5FEB\u901F\u9009\u62E9", err_1: '\u6700\u5C0F\u65E5\u671F\u4E0D\u80FD\u5927\u4E8E\u6700\u5927\u65E5\u671F!' }
zzlydx-jiftle
trunk/zzlydx/My97DatePicker/lang/zh-cn.js
JavaScript
asf20
1,089
var $lang={ errAlertMsg: "Invalid date or the date out of range,redo or not?", aWeekStr: ["wk", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], aLongWeekStr:["wk","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"], aMonStr: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], aLongMonStr: ["January","February","March","April","May","June","July","August","September","October","November","December"], clearStr: "Clear", todayStr: "Today", okStr: "OK", updateStr: "OK", timeStr: "Time", quickStr: "Quick Selection", err_1: 'MinDate Cannot be bigger than MaxDate!' }
zzlydx-jiftle
trunk/zzlydx/My97DatePicker/lang/en.js
JavaScript
asf20
644
.Wdate{ border:#999 1px solid; height:20px; background:#fff url(datePicker.gif) no-repeat right; } .WdateFmtErr{ font-weight:bold; color:red; }
zzlydx-jiftle
trunk/zzlydx/My97DatePicker/开发包/skin/WdatePicker.css
CSS
asf20
158
var $lang={ errAlertMsg: "Invalid date or the date out of range,redo or not?", aWeekStr: ["wk", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], aLongWeekStr:["wk","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"], aMonStr: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], aLongMonStr: ["January","February","March","April","May","June","July","August","September","October","November","December"], clearStr: "Clear", todayStr: "Today", okStr: "OK", updateStr: "OK", timeStr: "Time", quickStr: "Quick Selection", err_1: 'MinDate Cannot be bigger than MaxDate!' }
zzlydx-jiftle
trunk/zzlydx/My97DatePicker/开发包/lang/en.js
JavaScript
asf20
644
.tooltipinputerr { text-indent: 18px; border: solid 2px #eee; background: #ffff99 url(../images/exclamation.png) no-repeat right center; } .tooltipinputok { border: solid 2px green; background: url(../images/accept.png) no-repeat right center; } .tooltipshowpanel { z-index: auto; display: none; position:absolute; width: 276px; height: 35px; overflow: hidden; text-indent: 5px; line-height: 40px; font-size: 12px; font-family: Arial; background: url(../images/tooltop.gif) no-repeat left top; opacity:0.9; filter: alpha(opacity=90); }
zzlydx-jiftle
trunk/zzlydx/Scripts/jquery-tooltip/Css/Tooltip.css
CSS
asf20
592
/* S.Sams Lifexperience ----------------------------------------------------- Copyright (C) 2002 - 2008 S.Sams Lifexperience! All rights reserved Email: Cassams@gmail.com / S.Sams@msn.com WebSite: Http://lab.travelive.com.cn/ Msn: S.Sams@Msn.com Author: Sam Shen */ eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1;};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p;}('(1($){$.k.j=1(I){3 t=0;3 s=$.H({},$.k.j.E,I);$(\'R\').Q(\'<q V="7"></q>\');$(U).T(1(){$(\'.7\').u()});0.y(1(){8($(0).9(\'x\')!=v){$(0).P(1(){$(\'.7\').K({L:$.J(0)+\'r\',O:$.C(0)+\'r\'});$(\'.7\').M($(0).9(\'x\'));$(\'.7\').13("12")},1(){$(\'.7\').u()})}8($(0).9(\'l\')!=v){$(0).15(1(){$(0).c(\'d\')}).14(1(){8($(0).9(\'X\')==\'f\'){0.a=0.a.W()}3 e=z w($(0).9(\'l\'));8(e.D(0.a)){$(0).c(\'d\').h(\'i\')}11{$(0).c(\'i\').h(\'d\')}})}});8(s.m){$(\'Z\').Y(1(){3 p=f;t.y(1(){3 e=z w($(0).9(\'l\'));8(!e.D(0.a)){$(0).c(\'i\').h(\'d\');p=N}});g p})}};$.H({16:1(6){g 6.10},J:1(6){3 2=6;3 4,n=2.G;B(2.b!=A){4=2.b;n+=4.G;2=4}g n},C:1(6){3 2=6;3 4,o=2.F;B(2.b!=A){4=2.b;o+=4.F;2=4}g o+$(6).17()+5},m:f});$.k.j.E={m:f}})(S);',62,70,'this|function|go|var|oParent||object|tooltipshowpanel|if|attr|value|offsetParent|removeClass|tooltipinputerr|thisReg|true|return|addClass|tooltipinputok|tooltip|fn|reg|onsubmit|oLeft|oTop|isSubmit|div|px|opts|getthis|hide|undefined|RegExp|tip|each|new|null|while|getTop|test|defaults|offsetTop|offsetLeft|extend|options|getLeft|css|left|html|false|top|hover|append|body|jQuery|mouseover|document|class|toUpperCase|toupper|submit|form|offsetWidth|else|fast|fadeIn|blur|focus|getWidth|height'.split('|'),0,{})); (function($) { $(document).ready(function() { $('select[tip],select[reg],input[tip],input[reg],textarea[tip],textarea[reg]').tooltip(); }); })(jQuery);
zzlydx-jiftle
trunk/zzlydx/Scripts/jquery-tooltip/Js/Tooltip.pack.js
JavaScript
asf20
2,019
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <title> jQuery Tooltip + Validate </title> <script src="js/jquery.pack.js" type="text/javascript"></script> <style type="text/css"> .CreatePanel { margin: 10px; padding: 0; } .CreatePanel h1 { font-size: 25px; font-family: "微软雅黑" "幼圆" "arila"; font-weight: normal; border-bottom: 3px solid #ccc; padding: 5px; margin: 0 0 7px 0; } .BaseInfo { margin: 0 auto; width: 800px; font: 13px arial; } .BaseInfo ul { margin: 0; padding: 0; list-style: none; } .BaseInfo ul li { padding: 3px 0 3px 50px; border-bottom: dotted 1px #666; } .BaseInfo ul li label { display: block; width: 160px; float: left; font-size: 14px; font-family: "微软雅黑" "幼圆" "arila"; background: url(/images/Right.gif) no-repeat 140px center; } .BaseInfo ul li textarea, .BaseInfo ul li .setinput { width: 580px; font-size: 13px; font-family: Arial; } .BaseInfo ul li img.ShowImg { margin-left: 160px; } .BaseInfo .CheckBoxList { *margin-top: -16px; width: 580px; } .BaseInfo .CheckBoxList input { float: left; } .BaseInfo .CheckBoxList label { width: 100px; float: none; background-image: none; } .BaseInfo table td h3.orderby { font-family: Arial; font-size: 50px; color: #fff; padding: 0; margin: 10px; opacity:0.7; filter: alpha(opacity=70); } .BaseInfo table td h5 { line-height: 20px; border-bottom: dotted 1px #000; padding: 0 0 0 10px; margin: 0; font-size: 13px; color: #000; } .BaseInfo table td div.content { font-size:12px; line-height: 17px; } </style> </head> <body id="ctl00_MainBody" class="admintrips"> <form name="aspnetForm" method="post" id="aspnetForm"> <script src="js/Tooltip.mini.js" type="text/javascript"></script> <link href="css/Tooltip.css" rel="stylesheet" type="text/css" /> <div class="CreatePanel"> <h1>创建航班列表</h1> <div class="BaseInfo"> <ul> <li> <label>DropDownList</label> <select id="ctl00_ContentPlaceHolder1_ctl00__dw" reg="\d{1}" tip="设置航班号(大写) 如: CZ1321"> <option value="" selected="selected"></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="a">a</option> </select> </li> <li> <label>来回程</label> <input id="ctl00_ContentPlaceHolder1_ctl00__isoneway" type="checkbox" name="ctl00$ContentPlaceHolder1$ctl00$_isoneway" /> 将当前航段设置为去程 </li> <li> <label>航班号</label> <input name="ctl00$ContentPlaceHolder1$ctl00$_flightno" type="text" id="ctl00_ContentPlaceHolder1_ctl00__flightno" reg="\w{2}\d{4}" tip="设置航班号(大写) 如: CZ1321" toupper="true" /> (如: CZ1321) </li> <li> <label>航司(2字代码)</label> <input name="ctl00$ContentPlaceHolder1$ctl00$_airline" type="text" id="ctl00_ContentPlaceHolder1_ctl00__airline" reg="\w{2}" toupper="true" /> (注意大写) </li> <li> <label>起飞时间</label> <input name="ctl00$ContentPlaceHolder1$ctl00$_beingtime" type="text" id="ctl00_ContentPlaceHolder1_ctl00__beingtime" reg="\d{4}" tip="设置起飞时间 格式: hhmm" /> (格式: hhmm) </li> <li> <label>抵达时间</label> <input name="ctl00$ContentPlaceHolder1$ctl00$_endtime" type="text" id="ctl00_ContentPlaceHolder1_ctl00__endtime" reg="\d{4}" tip="设置抵达时间 格式: hhmm" /> (格式: hhmm) </li> <li> <label>经停点</label> <input name="ctl00$ContentPlaceHolder1$ctl00$_overstep" type="text" value="0" id="ctl00_ContentPlaceHolder1_ctl00__overstep" reg="\d{1}" /> </li> <li> <label>机型</label> <input name="ctl00$ContentPlaceHolder1$ctl00$_airnumber" type="text" id="ctl00_ContentPlaceHolder1_ctl00__airnumber" reg="\d{3}" /> (如: 737) </li> <li> <label>起飞机场</label> <input name="ctl00$ContentPlaceHolder1$ctl00$_fromairport" type="text" id="ctl00_ContentPlaceHolder1_ctl00__fromairport" /> (如: 广州白云国际机场) </li> <li> <label>抵达机场</label> <input name="ctl00$ContentPlaceHolder1$ctl00$_toairport" type="text" id="ctl00_ContentPlaceHolder1_ctl00__toairport" /> (如: 首都国际机场) </li> <li> <label>设置群组名</label> <input name="ctl00$ContentPlaceHolder1$ctl00$_groupname" type="text" id="ctl00_ContentPlaceHolder1_ctl00__groupname" /> (如: 如果存在多个回来程, 以群组名区别) </li> <li> <label>是否已售完</label> <input id="ctl00_ContentPlaceHolder1_ctl00__issaleend" type="checkbox" name="ctl00$ContentPlaceHolder1$ctl00$_issaleend" /> 设置已售完 </li> <li> <label>设置为默认选择项</label> <input id="ctl00_ContentPlaceHolder1_ctl00__isdefault" type="checkbox" name="ctl00$ContentPlaceHolder1$ctl00$_isdefault" /> 设置为默认选择项 </li> <li> <label>说明</label> <textarea name="a" rows="10" width="100%" tip="显示相关的注释说明"></textarea> </li> <li> <label>&nbsp;</label> <input type="submit" name="ctl00$ContentPlaceHolder1$ctl00$_createairsubmit" value="创建新航段" id="ctl00_ContentPlaceHolder1_ctl00__createairsubmit" class="submit" onclick="alert(document.getElementById('ctl00_ContentPlaceHolder1_ctl00__dw').value);"/> </li> </ul> </div> </div> <script language="javascript"> var s="人"; var reg=new RegExp("("+s+")","g"); var str="中华人民共和国,中华人民共和国"; var newstr=str.replace(reg,"<font color=red>$1</font>"); document.write(newstr + "<br />"); </script> </form> </body> </html>
zzlydx-jiftle
trunk/zzlydx/Scripts/jquery-tooltip/default.html
HTML
asf20
6,709
function ExtractionBirthday(oneText, twoText) { var txtparm = document.getElementById(oneText).value; if (txtparm.length == 18) { var year = txtparm.substring(6, 10); var month = txtparm.substring(10, 12); var date = txtparm.substring(12, 14); document.getElementById(twoText).value = year + "-" + month + "-" + date; } /* else { alert("输入的身份证不正确!"); document.getElementById(oneText).focus(); document.getElementById(oneText).value = ""; }*/ }
zzlydx-jiftle
trunk/zzlydx/Scripts/JScript_jiftle.js
JavaScript
asf20
555
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="zzlydx.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox> </div> </form> </body> </html>
zzlydx-jiftle
trunk/zzlydx/WebForm1.aspx
ASP.NET
asf20
623
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OnlyOneChild.aspx.cs" Inherits="zzlydx.OnlyOneChild" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="Scripts/jquery-tooltip/js/jquery.pack.js" type="text/javascript"></script> <script src="Scripts/jquery-tooltip/js/Tooltip.mini.js" type="text/javascript"></script> <link href="Scripts/jquery-tooltip/css/Tooltip.css" rel="stylesheet" type="text/css" /> <script language="javascript" type="text/javascript" src="My97DatePicker/WdatePicker.js"></script> <script language="javascript" type="text/javascript" src="Scripts/JScript_jiftle.js"></script> <style type="text/css"> .style1 { color: #FF0000; } .InputBody { background-color: #B9B9B9; } </style> </head> <body class="InputBody"> <form id="form1" runat="server" enableviewstate="true"> <div> <table> <tr> <td> <asp:Label ID="Label1" runat="server" Text="独生子女父母奖励"></asp:Label> </td> </tr> <tr> <td> <table style="width: 100%;"> <tr> <td > 姓名: </td> <td> <asp:TextBox ID="txtName" runat="server" MaxLength="32" reg="^\s*$" Tip="不能为空"></asp:TextBox> <span class="style1">*</span> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" ErrorMessage="不能为空"></asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style14"> 身份证号: </td> <td> <asp:TextBox ID="txtIdCode" runat="server" onblur="ExtractionBirthday('txtIdCode','txtBirthday');" MaxLength="18"></asp:TextBox> <span class="style1">*</span> <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="txtIdCode" ErrorMessage="不能为空"></asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style14"> 性别: </td> <td> <asp:DropDownList ID="dplSex" runat="server"> <asp:ListItem Value="0">未知</asp:ListItem> <asp:ListItem Value="1">男</asp:ListItem> <asp:ListItem Value="2">女</asp:ListItem> <asp:ListItem Value="3">未说明</asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td class="style14"> 出生日期: </td> <td> <asp:TextBox ID="txtBirthday" onClick="WdatePicker()" runat="server" ></asp:TextBox> <span class="style1">*</span> <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="txtBirthday" ErrorMessage="不能为空"></asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style14"> 户籍地: </td> <td> <asp:TextBox ID="txtLocation" runat="server" Width="173px"></asp:TextBox> </td> </tr> <tr> <td class="style14"> 户籍地编码: </td> <td> <asp:TextBox ID="txtLocationCode" runat="server" Width="173px"></asp:TextBox> </td> </tr> <tr> <td class="style14"> 配偶姓名: </td> <td> <asp:TextBox ID="txtPoName" runat="server" MaxLength="32"></asp:TextBox> </td> </tr> <tr> <td class="style14"> 配偶身份证号: </td> <td> <asp:TextBox ID="txtPoldcode" runat="server" MaxLength="18"></asp:TextBox> </td> </tr> <tr> <td class="style14"> 独生子女证编号: </td> <td> <asp:TextBox ID="txtOneChildCardCode" runat="server" MaxLength="20"></asp:TextBox> </td> </tr> <tr> <td class="style14"> 子女出生日期: </td> <td> <asp:TextBox ID="txtChildBirthday" onClick="WdatePicker()" runat="server"></asp:TextBox> <span class="style1">*</span><asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ControlToValidate="txtChildBirthday" ErrorMessage="不能为空"> </asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style14"> 子女性别: </td> <td> <asp:DropDownList ID="dplChildSex" runat="server"> <asp:ListItem Value="0">未知</asp:ListItem> <asp:ListItem Value="1">男</asp:ListItem> <asp:ListItem Value="2">女</asp:ListItem> <asp:ListItem Value="3">未说明</asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td class="style14"> 发放日期: </td> <td> <asp:TextBox ID="txtPaydate" onClick="WdatePicker()" runat="server"></asp:TextBox> </td> </tr> <tr> <td> 发放金额: </td> <td> <asp:TextBox ID="txtPaynum" runat="server" BackColor="#669999" ReadOnly="True" MaxLength="8">0</asp:TextBox> </td> </tr> <tr> <td> 是否参加养老保险补贴: </td> <td> <asp:CheckBox ID="chkIsOldInsure" runat="server" /> </td> </tr> <tr> <td> 是否落实: </td> <td> <asp:CheckBox ID="chkLushi" runat="server" /> </td> </tr> <tr> <td> 落实日期: </td> <td> <asp:TextBox ID="txtLushiDate" onClick="WdatePicker()" runat="server"></asp:TextBox> </td> </tr> <tr> <td> 未审核: </td> <td> <asp:DropDownList ID="dplShenghe" runat="server"> <asp:ListItem Value="0">未审核</asp:ListItem> <asp:ListItem Value="1">审核通过</asp:ListItem> <asp:ListItem Value="2">审核未通过</asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td> 审核人: </td> <td> <asp:TextBox ID="txtShengheRen" runat="server"></asp:TextBox> </td> </tr> <tr> <td> 审核日期: </td> <td> <asp:TextBox ID="txtShenghedate" onClick="WdatePicker()" runat="server"></asp:TextBox> </td> </tr> <tr> <td> 审核未通过原因: </td> <td> <asp:TextBox ID="txtShengheNoReason" runat="server" Width="246px"></asp:TextBox> </td> </tr> <tr> <td> 户编号: </td> <td> <asp:TextBox ID="txtfamilyCode" runat="server" MaxLength="8" Width="179px"></asp:TextBox> </td> </tr> <tr> <td> 单位名称: </td> <td> <asp:TextBox ID="txtUnitName" runat="server" Width="247px"></asp:TextBox> </td> </tr> <tr> <td> 单位性质: </td> <td> <asp:DropDownList ID="dplUnitXingzhi" runat="server"> <asp:ListItem Value="0">行政事业单位</asp:ListItem> <asp:ListItem Value="1">其他</asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td> </td> <td> <asp:Button ID="btnAdd" runat="server" Text="添加" Width="113px" OnClick="btnAdd_Click" /> &nbsp; <asp:Button ID="btnCancel" runat="server" Text="返回" Width="104px" /> </td> </tr> </table> </td> </tr> </table> </div> </form> </body> </html>
zzlydx-jiftle
trunk/zzlydx/OnlyOneChild.aspx
ASP.NET
asf20
13,192
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace zzlydx { public partial class OnlyOneChildQuery : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //rwDB db = new rwDB(); //GridView1.DataSource= db.GetDataTable("select * from dsznfmjlb"); //GridView1.DataBind(); } } }
zzlydx-jiftle
trunk/zzlydx/OnlyOneChildQuery_old.aspx.cs
C#
asf20
490
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OnlyOneChildQuery_old.aspx.cs" Inherits="zzlydx.OnlyOneChildQuery" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Horizontal" PageSize="20" ShowFooter="True" > <AlternatingRowStyle BackColor="#F7F7F7" /> <Columns> <asp:BoundField DataField="姓名" HeaderText="姓名" SortExpression="姓名" /> <asp:BoundField DataField="身份证号" HeaderText="身份证号" SortExpression="身份证号" /> <asp:BoundField DataField="性别" HeaderText="性别" SortExpression="性别" /> <asp:BoundField DataField="出生日期" HeaderText="出生日期" SortExpression="出生日期" /> <asp:BoundField DataField="户籍地" HeaderText="户籍地" SortExpression="户籍地" /> <asp:BoundField DataField="户籍地代码" HeaderText="户籍地代码" SortExpression="户籍地代码" /> <asp:BoundField DataField="配偶姓名" HeaderText="配偶姓名" SortExpression="配偶姓名" /> <asp:BoundField DataField="配偶身份证号" HeaderText="配偶身份证号" SortExpression="配偶身份证号" /> <asp:BoundField DataField="独生子女证编号" HeaderText="独生子女证编号" SortExpression="独生子女证编号" /> <asp:BoundField DataField="孩子出生日期" HeaderText="孩子出生日期" SortExpression="孩子出生日期" /> <asp:BoundField DataField="孩子性别" HeaderText="孩子性别" SortExpression="孩子性别" /> <asp:BoundField DataField="发放日期" HeaderText="发放日期" SortExpression="发放日期" /> <asp:BoundField DataField="发放日期1" HeaderText="发放日期1" SortExpression="发放日期1" /> <asp:BoundField DataField="是否参加养老保险" HeaderText="是否参加养老保险" SortExpression="是否参加养老保险" /> <asp:BoundField DataField="落实情况" HeaderText="落实情况" SortExpression="落实情况" /> <asp:BoundField DataField="落实日期" HeaderText="落实日期" SortExpression="落实日期" /> <asp:BoundField DataField="审核情况" HeaderText="审核情况" SortExpression="审核情况" /> <asp:BoundField DataField="审核人" HeaderText="审核人" SortExpression="审核人" /> <asp:BoundField DataField="审核日期" HeaderText="审核日期" SortExpression="审核日期" /> <asp:BoundField DataField="审核不通过原因" HeaderText="审核不通过原因" SortExpression="审核不通过原因" /> <asp:BoundField DataField="户编号" HeaderText="户编号" SortExpression="户编号" /> <asp:BoundField DataField="单位名称" HeaderText="单位名称" SortExpression="单位名称" /> <asp:BoundField DataField="单位性质" HeaderText="单位性质" SortExpression="单位性质" /> <asp:BoundField DataField="操作员" HeaderText="操作员" SortExpression="操作员" /> <asp:BoundField DataField="录入时间" HeaderText="录入时间" SortExpression="录入时间" /> </Columns> <FooterStyle BackColor="#B5C7DE" BorderColor="#003366" BorderStyle="Solid" BorderWidth="1px" ForeColor="#4A3C8C" /> <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" /> <PagerSettings FirstPageText="首页" LastPageText="尾页" NextPageText="下一页" PreviousPageText="上一页" /> <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" /> <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" /> <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" /> <SortedAscendingCellStyle BackColor="#F4F4FD" /> <SortedAscendingHeaderStyle BackColor="#5A4C9D" /> <SortedDescendingCellStyle BackColor="#D8D8F0" /> <SortedDescendingHeaderStyle BackColor="#3E3277" /> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT name AS 姓名, idcode AS 身份证号, sex AS 性别, birthday AS 出生日期, location AS 户籍地, locationcode AS 户籍地代码, poname AS 配偶姓名, poldcode AS 配偶身份证号, onechildcardcode AS 独生子女证编号, childbirthday AS 孩子出生日期, childsex AS 孩子性别, paydate AS 发放日期, paynum AS 发放日期, isoldinsure AS 是否参加养老保险, lushi AS 落实情况, lushidate AS 落实日期, shenghe AS 审核情况, shengheren AS 审核人, shenghedate AS 审核日期, shenghenoreason AS 审核不通过原因, familycode AS 户编号, unitname AS 单位名称, unitxingzhi AS 单位性质, username AS 操作员, inputdate AS 录入时间 FROM lydxDB.dbo.dsznfmjlb"> </asp:SqlDataSource> </div> </form> </body> </html>
zzlydx-jiftle
trunk/zzlydx/OnlyOneChildQuery_old.aspx
ASP.NET
asf20
5,612
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; namespace zzlydx { public class Global : System.Web.HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. } } }
zzlydx-jiftle
trunk/zzlydx/Global.asax.cs
C#
asf20
1,189
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace zzlydx { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void TextBox1_TextChanged(object sender, EventArgs e) { string strText = TextBox1.Text; } } }
zzlydx-jiftle
trunk/zzlydx/WebForm1.aspx.cs
C#
asf20
470
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Jiftle.Data; using System.Data; namespace zzlydx { /// <summary> /// Summary description for Table_Dsznfmjlb /// </summary> public class Table_Dsznfmjlb { public static string GetSQL_Insert(strtDsznfmjlb tmp) { string strSQL = string.Empty; strSQL = string.Format("INSERT INTO dsznfmjlb([name],[idcode],[sex],[birthday],[location] ,[locationcode],[poname],[poldcode] ,[onechildcardcode] ,[childbirthday],[childsex]" + ",[paydate],[paynum],[isoldinsure],[lushi],[lushidate],[shenghe],[shengheren],[shenghedate],[shenghenoreason],[familycode],[unitname],[unitxingzhi]" + ",[username],[inputdate])" + "VALUES" + "('" + tmp.name + "','" + tmp.idcode + "'," + tmp.sex + ",'" + tmp.birthday.ToString("yyyy-MM-dd HH:mm:ss") + "','" + tmp.location + "','" + tmp.locationcode + "','" + tmp.poname + "','" + tmp.poldcode + "','" + tmp.onechildcardcode + "','" + tmp.childbirthday.ToString("yyyy-MM-dd HH:mm:ss") + "'," + tmp.childsex + ",'" + tmp.paydate.ToString("yyyy-MM-dd HH:mm:ss") + "'," + tmp.paynum + "," + tmp.isoldinsure + "," + tmp.lushi + ",'" + tmp.lushidate.ToString("yyyy-MM-dd HH:mm:ss") + "'," + tmp.shenghe + ",'" + tmp.shengheren + "','" + tmp.shenghedate.ToString("yyyy-MM-dd HH:mm:ss") + "','" + tmp.shenghenoreason + "','" + tmp.familycode + "','" + tmp.unitname + "'," + tmp.unitxingzhi + ",'" + tmp.username + "','" + tmp.inputdate + "')"); return strSQL; } public static int GetItemCount(string idCode,DBCommand conn) { string strSQL = string.Empty; DataTable dttTmp = null; int intCount = 0; strSQL = string.Format("select count(*) As ItemCount from dsznfmjlb where idcode='{0}'",idCode); dttTmp = conn.CreateDataTable(strSQL); if (dttTmp != null && dttTmp.Rows.Count > 0) { intCount = Convert.ToInt32(dttTmp.Rows[0]["ItemCount"] .ToString()); } return intCount; } } }
zzlydx-jiftle
trunk/zzlydx/App_Code/Table/Table_Dsznfmjlb.cs
C#
asf20
2,200
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using Jiftle.Data; namespace zzlydx { /// <summary> ///rwDB 的摘要说明 /// </summary> public class rwDB { public DBCommand conn; public readonly bool bConnected = false; public rwDB() { try { string strConn = string.Empty; conn = new DBCommand(); strConn = ConfigurationManager.ConnectionStrings["ConnStr"].ToString(); conn.ConnectionString = strConn; conn.DataBaseDriverType = enmDataAccessType.DB_MSSQL; conn.Open(); bConnected = conn.Connected; } catch (System.Exception ex) { string strErr = ex.Message; bConnected = false; } } public int ExcuteSQL(string strSQL) { try { int intCount = 0; if (conn != null && conn.Connected) { intCount = conn.ExecuteSQL(strSQL); } else { conn.Open(); intCount = conn.ExecuteSQL(strSQL); } return intCount; } catch (System.Exception) { return 0; } } public DataTable GetDataTable(string strSQL) { try { DataTable dttTmp = null; if (conn != null && conn.Connected) { dttTmp = conn.CreateDataTable(strSQL); } else { conn.Open(); dttTmp = conn.CreateDataTable(strSQL); } return dttTmp; } catch (System.Exception ex) { string stErr = ex.Message; return null; } } ~rwDB() { try { if (conn != null && conn.Connected) { conn.Close(); } } catch (System.Exception) { } } } }
zzlydx-jiftle
trunk/zzlydx/App_Code/rwDB.cs
C#
asf20
2,691
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; namespace zzlydx { public class Funcs { /// <summary> /// 消息框 /// </summary> /// <param name="strTip"></param> /// <param name="pge"></param> public static void jMsgBoxInfo(string strTip, Page pge) { pge.Response.Write("<script>alert('" + strTip + "')</script>"); } /// <summary> /// 默认日期 /// </summary> /// <returns></returns> public static DateTime GetDefaultDateTime() { DateTime dtm = new DateTime(1900, 1, 1); return dtm; } /// <summary> /// 当前用户名 /// </summary> /// <param name="pge"></param> /// <returns></returns> public static string GetCurUserName(Page pge) { string strUser = string.Empty; try { strUser = pge.Session["User"].ToString(); if (strUser == "") { strUser = "admin"; } } catch (System.Exception ex) { if (strUser == "") { strUser = "admin"; } } return strUser; } /// <summary> /// 独生子女奖励标准 /// </summary> /// <returns></returns> public static double GetReward_OnlyOneChild() { return 20; } } }
zzlydx-jiftle
trunk/zzlydx/App_Code/Funcs.cs
C#
asf20
1,641
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace zzlydx { public struct strtDsznfmjlb { /// <summary> /// 姓名 /// </summary> public string name; /// <summary> /// 身份证号 /// </summary> public string idcode; /// <summary> /// 性别 /// </summary> public short sex; /// <summary> /// 出生日期 /// </summary> public DateTime birthday; /// <summary> /// 户籍地 /// </summary> public string location; /// <summary> /// 户籍地 /// </summary> public string locationcode; /// <summary> /// 配偶姓名 /// </summary> public string poname; /// <summary> /// 配偶身份证号 /// </summary> public string poldcode; /// <summary> /// 独生子女证 /// </summary> public string onechildcardcode; /// <summary> /// 孩子出生年月 /// </summary> public DateTime childbirthday; /// <summary> /// 孩子性别 /// </summary> public short childsex; /// <summary> /// 发送日期 /// </summary> public DateTime paydate; /// <summary> /// 发放金额 /// </summary> public double paynum; /// <summary> /// 是否参加养老保险补贴 /// </summary> public short isoldinsure; /// <summary> /// 是否落实 /// </summary> public short lushi; /// <summary> /// 落实日期 /// </summary> public DateTime lushidate; /// <summary> /// 是否审核 /// </summary> public short shenghe; /// <summary> /// 审核人 /// </summary> public string shengheren; /// <summary> /// 审核日期 /// </summary> public DateTime shenghedate; /// <summary> /// 审核日期 /// </summary> public string shenghenoreason; /// <summary> /// 家庭编号 /// </summary> public string familycode; /// <summary> /// 男身份证(18位)+女身份证(18位) /// </summary> public string familystaticcode; /// <summary> /// 单位名称 /// </summary> public string unitname; /// <summary> /// 单位性质 /// </summary> public short unitxingzhi; /// <summary> /// 操作员 /// </summary> public string username; /// <summary> /// 输入日期 /// </summary> public DateTime inputdate; } }
zzlydx-jiftle
trunk/zzlydx/App_Code/Typs.cs
C#
asf20
2,998
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace zzlydx { public partial class About : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } }
zzlydx-jiftle
trunk/zzlydx/About.aspx.cs
C#
asf20
327
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("zzlydx")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("www.SundayBoy.com")] [assembly: AssemblyProduct("zzlydx")] [assembly: AssemblyCopyright("Copyright © www.SundayBoy.com 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ed964b1b-7300-4669-9854-f179181fe820")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzlydx-jiftle
trunk/zzlydx/Properties/AssemblyInfo.cs
C#
asf20
1,417
<%@ Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="zzlydx.About" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> About </h2> <p> Put content here. </p> </asp:Content>
zzlydx-jiftle
trunk/zzlydx/About.aspx
ASP.NET
asf20
439
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace zzlydx { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Funcs.jMsgInfo("-0-0-0-0-",this); //Response.Redirect("~/OnlyOneChild.aspx"); //Server.Transfer("~/OnlyOneChild.aspx"); } } }
zzlydx-jiftle
trunk/zzlydx/Default.aspx.cs
C#
asf20
488
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="zzlydx.Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> </head> <body> <div> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/OnlyOneChild.aspx">录入</asp:HyperLink> <br/> <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="~/OnlyOneChildQuery.aspx">查询</asp:HyperLink> </div> </body> </html>
zzlydx-jiftle
trunk/zzlydx/Default.aspx
ASP.NET
asf20
699
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace zzlydx { public partial class OnlyOneChildQuery_1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } }
zzlydx-jiftle
trunk/zzlydx/OnlyOneChildQuery.aspx.cs
C#
asf20
339
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace zzlydx { public partial class SiteMaster : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { } } }
zzlydx-jiftle
trunk/zzlydx/Site.Master.cs
C#
asf20
338
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace zzlydx { public partial class OnlyOneChild : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { txtPaynum.Text = Funcs.GetReward_OnlyOneChild().ToString(); } } protected void btnAdd_Click(object sender, EventArgs e) { try { strtDsznfmjlb tmp = new strtDsznfmjlb(); tmp.name = txtName.Text.Trim(); tmp.idcode = txtIdCode.Text.Trim(); tmp.sex = Convert.ToInt16(dplSex.SelectedIndex); tmp.childsex = Convert.ToInt16(dplChildSex.SelectedIndex); tmp.familycode = txtfamilyCode.Text.Trim(); tmp.isoldinsure = Convert.ToInt16(chkIsOldInsure.Checked?1:0); //是否参加养老保险补贴(0 未 1 参加) tmp.locationcode = txtLocationCode.Text.Trim(); tmp.lushi = Convert.ToInt16(chkLushi.Checked ? 1 : 0); //落实 tmp.location = txtLocation.Text.Trim(); tmp.onechildcardcode = txtOneChildCardCode.Text; //独生子女证编号 tmp.paynum = Convert.ToDouble(txtPaynum.Text.Trim() == "" ? "0" :txtPaynum.Text.Trim()); //发放金额 tmp.poldcode = txtPoldcode.Text.Trim();//配偶身份证号 tmp.poname = txtPoName.Text.Trim();//配偶姓名 tmp.shenghe = Convert.ToInt16(dplShenghe.SelectedIndex);//审核 tmp.shenghenoreason = txtShengheNoReason.Text.Trim(); tmp.shengheren = txtShengheRen.Text.Trim(); tmp.unitname = txtUnitName.Text.Trim(); tmp.unitxingzhi = Convert.ToInt16(dplUnitXingzhi.SelectedIndex); tmp.username = Funcs.GetCurUserName(this); //Session["UserName"].ToString(); tmp.inputdate = DateTime.Now; //日期 if (tmp.lushi !=0) tmp.lushidate = Convert.ToDateTime(txtLushiDate.Text); else tmp.lushidate = Funcs.GetDefaultDateTime(); tmp.birthday = Convert.ToDateTime(txtBirthday.Text); tmp.childbirthday = Convert.ToDateTime(txtChildBirthday.Text); if (txtPaydate.Text.Trim() == "") tmp.paydate = Funcs.GetDefaultDateTime(); else tmp.paydate = Convert.ToDateTime(txtPaydate.Text.Trim()); if (txtShenghedate.Text.Trim() == "") tmp.shenghedate = Funcs.GetDefaultDateTime(); else tmp.shenghedate = Convert.ToDateTime(txtShenghedate.Text); rwDB db = new rwDB(); if (Table_Dsznfmjlb.GetItemCount(tmp.idcode, db.conn) == 0) { string strSQL = Table_Dsznfmjlb.GetSQL_Insert(tmp); if (db.ExcuteSQL(strSQL) == 1) Funcs.jMsgBoxInfo("录入成功!", this); else Funcs.jMsgBoxInfo("录入失败!", this); } else { Funcs.jMsgBoxInfo(tmp.name + "(" + tmp.idcode + ")已存在!", this); } } catch (System.Exception ex) { } } } }
zzlydx-jiftle
trunk/zzlydx/OnlyOneChild.aspx.cs
C#
asf20
3,685
/* * Copyright (C) 2010 Teleal GmbH, Switzerland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.teleal.cling.support.connectionmanager; import org.teleal.cling.model.action.ActionException; import org.teleal.cling.model.types.ErrorCode; /** * */ public class ConnectionManagerException extends ActionException { public ConnectionManagerException(int errorCode, String message) { super(errorCode, message); } public ConnectionManagerException(int errorCode, String message, Throwable cause) { super(errorCode, message, cause); } public ConnectionManagerException(ErrorCode errorCode, String message) { super(errorCode, message); } public ConnectionManagerException(ErrorCode errorCode) { super(errorCode); } public ConnectionManagerException(ConnectionManagerErrorCode errorCode, String message) { super(errorCode.getCode(), errorCode.getDescription() + ". " + message + "."); } public ConnectionManagerException(ConnectionManagerErrorCode errorCode) { super(errorCode.getCode(), errorCode.getDescription()); } }
zzh84615-mycode
src/org/teleal/cling/support/connectionmanager/ConnectionManagerException.java
Java
asf20
1,760
/* * Copyright (C) 2010 Teleal GmbH, Switzerland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.teleal.cling.support.connectionmanager; import org.teleal.cling.binding.annotations.UpnpAction; import org.teleal.cling.binding.annotations.UpnpInputArgument; import org.teleal.cling.binding.annotations.UpnpOutputArgument; import org.teleal.cling.binding.annotations.UpnpService; import org.teleal.cling.binding.annotations.UpnpServiceId; import org.teleal.cling.binding.annotations.UpnpServiceType; import org.teleal.cling.binding.annotations.UpnpStateVariable; import org.teleal.cling.binding.annotations.UpnpStateVariables; import org.teleal.cling.model.ServiceReference; import org.teleal.cling.model.action.ActionException; import org.teleal.cling.model.types.UnsignedIntegerFourBytes; import org.teleal.cling.model.types.csv.CSV; import org.teleal.cling.model.types.csv.CSVUnsignedIntegerFourBytes; import org.teleal.cling.support.model.ConnectionInfo; import org.teleal.cling.support.model.ProtocolInfo; import org.teleal.cling.support.model.ProtocolInfos; import java.beans.PropertyChangeSupport; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; /** * Base for connection management, implements the connection ID "0" behavior. * * @author Christian Bauer * @author Alessio Gaeta */ @UpnpService( serviceId = @UpnpServiceId("ConnectionManager"), serviceType = @UpnpServiceType(value = "ConnectionManager", version = 1), stringConvertibleTypes = {ProtocolInfo.class, ProtocolInfos.class, ServiceReference.class} ) @UpnpStateVariables({ @UpnpStateVariable(name = "SourceProtocolInfo", datatype = "string"), @UpnpStateVariable(name = "SinkProtocolInfo", datatype = "string"), @UpnpStateVariable(name = "CurrentConnectionIDs", datatype = "string"), @UpnpStateVariable(name = "A_ARG_TYPE_ConnectionStatus", allowedValuesEnum = ConnectionInfo.Status.class, sendEvents = false), @UpnpStateVariable(name = "A_ARG_TYPE_ConnectionManager", datatype = "string", sendEvents = false), @UpnpStateVariable(name = "A_ARG_TYPE_Direction", allowedValuesEnum = ConnectionInfo.Direction.class, sendEvents = false), @UpnpStateVariable(name = "A_ARG_TYPE_ProtocolInfo", datatype = "string", sendEvents = false), @UpnpStateVariable(name = "A_ARG_TYPE_ConnectionID", datatype = "i4", sendEvents = false), @UpnpStateVariable(name = "A_ARG_TYPE_AVTransportID", datatype = "i4", sendEvents = false), @UpnpStateVariable(name = "A_ARG_TYPE_RcsID", datatype = "i4", sendEvents = false) }) public class ConnectionManagerService { final private static Logger log = Logger.getLogger(ConnectionManagerService.class.getName()); final protected PropertyChangeSupport propertyChangeSupport; final protected Map<Integer, ConnectionInfo> activeConnections = new ConcurrentHashMap(); final protected ProtocolInfos sourceProtocolInfo; final protected ProtocolInfos sinkProtocolInfo; /** * Creates a default "active" connection with identifier "0". */ public ConnectionManagerService() { this(new ConnectionInfo()); } /** * Creates a default "active" connection with identifier "0". */ public ConnectionManagerService(ProtocolInfos sourceProtocolInfo, ProtocolInfos sinkProtocolInfo) { this(sourceProtocolInfo, sinkProtocolInfo, new ConnectionInfo()); } public ConnectionManagerService(ConnectionInfo... activeConnections) { this(null, new ProtocolInfos(), new ProtocolInfos(), activeConnections); } public ConnectionManagerService(ProtocolInfos sourceProtocolInfo, ProtocolInfos sinkProtocolInfo, ConnectionInfo... activeConnections) { this(null, sourceProtocolInfo, sinkProtocolInfo, activeConnections); } public ConnectionManagerService(PropertyChangeSupport propertyChangeSupport, ProtocolInfos sourceProtocolInfo, ProtocolInfos sinkProtocolInfo, ConnectionInfo... activeConnections) { this.propertyChangeSupport = propertyChangeSupport == null ? new PropertyChangeSupport(this) : propertyChangeSupport; this.sourceProtocolInfo = sourceProtocolInfo; this.sinkProtocolInfo = sinkProtocolInfo; for (ConnectionInfo activeConnection : activeConnections) { this.activeConnections.put(activeConnection.getConnectionID(), activeConnection); } } public PropertyChangeSupport getPropertyChangeSupport() { return propertyChangeSupport; } @UpnpAction(out = { @UpnpOutputArgument(name = "RcsID", getterName = "getRcsID"), @UpnpOutputArgument(name = "AVTransportID", getterName = "getAvTransportID"), @UpnpOutputArgument(name = "ProtocolInfo", getterName = "getProtocolInfo"), @UpnpOutputArgument(name = "PeerConnectionManager", stateVariable = "A_ARG_TYPE_ConnectionManager", getterName = "getPeerConnectionManager"), @UpnpOutputArgument(name = "PeerConnectionID", stateVariable = "A_ARG_TYPE_ConnectionID", getterName = "getPeerConnectionID"), @UpnpOutputArgument(name = "Direction", getterName = "getDirection"), @UpnpOutputArgument(name = "Status", stateVariable = "A_ARG_TYPE_ConnectionStatus", getterName = "getConnectionStatus") }) synchronized public ConnectionInfo getCurrentConnectionInfo(@UpnpInputArgument(name = "ConnectionID") int connectionId) throws ActionException { log.fine("Getting connection information of connection ID: " + connectionId); ConnectionInfo info; if ((info = activeConnections.get(connectionId)) == null) { throw new ConnectionManagerException( ConnectionManagerErrorCode.INVALID_CONNECTION_REFERENCE, "Non-active connection ID: " + connectionId ); } return info; } @UpnpAction(out = { @UpnpOutputArgument(name = "ConnectionIDs") }) synchronized public CSV<UnsignedIntegerFourBytes> getCurrentConnectionIDs() { CSV<UnsignedIntegerFourBytes> csv = new CSVUnsignedIntegerFourBytes(); for (Integer connectionID : activeConnections.keySet()) { csv.add(new UnsignedIntegerFourBytes(connectionID)); } log.fine("Returning current connection IDs: " + csv.size()); return csv; } @UpnpAction(out = { @UpnpOutputArgument(name = "Source", stateVariable = "SourceProtocolInfo", getterName = "getSourceProtocolInfo"), @UpnpOutputArgument(name = "Sink", stateVariable = "SinkProtocolInfo", getterName = "getSinkProtocolInfo") }) synchronized public void getProtocolInfo() throws ActionException { // NOOP } synchronized public ProtocolInfos getSourceProtocolInfo() { return sourceProtocolInfo; } synchronized public ProtocolInfos getSinkProtocolInfo() { return sinkProtocolInfo; } }
zzh84615-mycode
src/org/teleal/cling/support/connectionmanager/ConnectionManagerService.java
Java
asf20
7,769
/* * Copyright (C) 2010 Alessio Gaeta <alessio.gaeta@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.teleal.cling.support.connectionmanager.callback; import org.teleal.cling.controlpoint.ActionCallback; import org.teleal.cling.controlpoint.ControlPoint; import org.teleal.cling.model.ServiceReference; import org.teleal.cling.model.action.ActionException; import org.teleal.cling.model.action.ActionInvocation; import org.teleal.cling.model.meta.Service; import org.teleal.cling.model.types.ErrorCode; import org.teleal.cling.support.model.ConnectionInfo; import org.teleal.cling.support.model.ProtocolInfo; /** * @author Alessio Gaeta * @author Christian Bauer */ public abstract class GetCurrentConnectionInfo extends ActionCallback { public GetCurrentConnectionInfo(Service service, int connectionID) { this(service, null, connectionID); } protected GetCurrentConnectionInfo(Service service, ControlPoint controlPoint, int connectionID) { super(new ActionInvocation(service.getAction("GetCurrentConnectionInfo")), controlPoint); getActionInvocation().setInput("ConnectionID", connectionID); } @Override public void success(ActionInvocation invocation) { try { ConnectionInfo info = new ConnectionInfo( (Integer)invocation.getInput("ConnectionID").getValue(), (Integer)invocation.getOutput("RcsID").getValue(), (Integer)invocation.getOutput("AVTransportID").getValue(), new ProtocolInfo(invocation.getOutput("ProtocolInfo").toString()), new ServiceReference(invocation.getOutput("PeerConnectionManager").toString()), (Integer)invocation.getOutput("PeerConnectionID").getValue(), ConnectionInfo.Direction.valueOf(invocation.getOutput("Direction").toString()), ConnectionInfo.Status.valueOf(invocation.getOutput("Status").toString()) ); received(invocation, info); } catch (Exception ex) { invocation.setFailure( new ActionException(ErrorCode.ACTION_FAILED, "Can't parse ConnectionInfo response: " + ex, ex) ); failure(invocation, null); } } public abstract void received(ActionInvocation invocation, ConnectionInfo connectionInfo); }
zzh84615-mycode
src/org/teleal/cling/support/connectionmanager/callback/GetCurrentConnectionInfo.java
Java
asf20
3,022
/* * Copyright (C) 2010 Teleal GmbH, Switzerland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.teleal.cling.support.connectionmanager.callback; import org.teleal.cling.controlpoint.ActionCallback; import org.teleal.cling.controlpoint.ControlPoint; import org.teleal.cling.model.action.ActionInvocation; import org.teleal.cling.model.meta.Service; /** * @author Christian Bauer */ public abstract class ConnectionComplete extends ActionCallback { public ConnectionComplete(Service service, int connectionID) { this(service, null, connectionID); } protected ConnectionComplete(Service service, ControlPoint controlPoint, int connectionID) { super(new ActionInvocation(service.getAction("ConnectionComplete")), controlPoint); getActionInvocation().setInput("ConnectionID", connectionID); } }
zzh84615-mycode
src/org/teleal/cling/support/connectionmanager/callback/ConnectionComplete.java
Java
asf20
1,469