diff options
Diffstat (limited to 'guava-testlib/test/com')
33 files changed, 0 insertions, 7421 deletions
diff --git a/guava-testlib/test/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilderTest.java b/guava-testlib/test/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilderTest.java deleted file mode 100644 index 2e0d594..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilderTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2011 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import com.google.common.collect.testing.features.CollectionFeature; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestResult; - -import java.util.Collections; -import java.util.List; - -/** - * @author Max Ross - */ -public class FeatureSpecificTestSuiteBuilderTest extends TestCase { - - static boolean testWasRun; - - @Override - protected void setUp() throws Exception { - super.setUp(); - testWasRun = false; - } - - public static final class MyAbstractTester extends AbstractTester { - public void testNothing() { - testWasRun = true; - } - } - - private static final class MyTestSuiteBuilder extends - FeatureSpecificTestSuiteBuilder<MyTestSuiteBuilder, String> { - - @Override - protected List<Class<? extends AbstractTester>> getTesters() { - return Collections.<Class<? extends AbstractTester>>singletonList(MyAbstractTester.class); - } - } - - public void testLifecycle() { - final boolean setUp[] = {false}; - Runnable setUpRunnable = new Runnable() { - @Override - public void run() { - setUp[0] = true; - } - }; - - final boolean tearDown[] = {false}; - Runnable tearDownRunnable = new Runnable() { - @Override - public void run() { - tearDown[0] = true; - } - }; - - MyTestSuiteBuilder builder = new MyTestSuiteBuilder(); - Test test = builder.usingGenerator("yam").named("yam") - .withFeatures(CollectionFeature.NONE).withSetUp(setUpRunnable) - .withTearDown(tearDownRunnable).createTestSuite(); - TestResult result = new TestResult(); - test.run(result); - assertTrue(testWasRun); - assertTrue(setUp[0]); - assertTrue(tearDown[0]); - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/HelpersTest.java b/guava-testlib/test/com/google/common/collect/testing/HelpersTest.java deleted file mode 100644 index 5c1432b..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/HelpersTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2008 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import static com.google.common.collect.testing.Helpers.NullsBeforeB; -import static com.google.common.collect.testing.Helpers.testComparator; - -import junit.framework.TestCase; - -/** - * Unit test for {@link Helpers}. - * - * @author Chris Povirk - */ -public class HelpersTest extends TestCase { - public void testNullsBeforeB() { - testComparator(NullsBeforeB.INSTANCE, "a", "azzzzzz", null, "b", "c"); - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/IteratorTesterTest.java b/guava-testlib/test/com/google/common/collect/testing/IteratorTesterTest.java deleted file mode 100644 index e272ec0..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/IteratorTesterTest.java +++ /dev/null @@ -1,349 +0,0 @@ -/* - * Copyright (C) 2008 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import static com.google.common.collect.Lists.newArrayList; -import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; -import static java.util.Collections.emptyList; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * Unit test for IteratorTester. - * - * @author Mick Killianey - */ -@SuppressWarnings("serial") // No serialization is used in this test -public class IteratorTesterTest extends TestCase { - - public void testCanCatchDifferentLengthOfIteration() { - IteratorTester<Integer> tester = - new IteratorTester<Integer>(4, MODIFIABLE, newArrayList(1, 2, 3), - IteratorTester.KnownOrder.KNOWN_ORDER) { - @Override protected Iterator<Integer> newTargetIterator() { - return Lists.newArrayList(1, 2, 3, 4).iterator(); - } - }; - assertFailure(tester); - } - - public void testCanCatchDifferentContents() { - IteratorTester<Integer> tester = - new IteratorTester<Integer>(3, MODIFIABLE, newArrayList(1, 2, 3), - IteratorTester.KnownOrder.KNOWN_ORDER) { - @Override protected Iterator<Integer> newTargetIterator() { - return Lists.newArrayList(1, 3, 2).iterator(); - } - }; - assertFailure(tester); - } - - public void testCanCatchDifferentRemoveBehaviour() { - IteratorTester<Integer> tester = - new IteratorTester<Integer>(3, MODIFIABLE, newArrayList(1, 2), - IteratorTester.KnownOrder.KNOWN_ORDER) { - @Override protected Iterator<Integer> newTargetIterator() { - return ImmutableList.of(1, 2).iterator(); - } - }; - assertFailure(tester); - } - - public void testUnknownOrder() { - new IteratorTester<Integer>(3, MODIFIABLE, newArrayList(1, 2), - IteratorTester.KnownOrder.UNKNOWN_ORDER) { - @Override protected Iterator<Integer> newTargetIterator() { - return newArrayList(2, 1).iterator(); - } - }.test(); - } - - public void testUnknownOrderUnrecognizedElement() { - IteratorTester<Integer> tester = - new IteratorTester<Integer>(3, MODIFIABLE, newArrayList(1, 2, 50), - IteratorTester.KnownOrder.UNKNOWN_ORDER) { - @Override protected Iterator<Integer> newTargetIterator() { - return newArrayList(2, 1, 3).iterator(); - } - }; - assertFailure(tester); - } - - /** - * This Iterator wraps another iterator and gives it a bug found - * in JDK6. - * - * <p>This bug is this: if you create an iterator from a TreeSet - * and call next() on that iterator when hasNext() is false, so - * that next() throws a NoSuchElementException, then subsequent - * calls to remove() will incorrectly throw an IllegalStateException, - * instead of removing the last element returned. - * - * <p>See - * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6529795"> - * Sun bug 6529795</a> - */ - static class IteratorWithSunJavaBug6529795<T> implements Iterator<T> { - Iterator<T> iterator; - boolean nextThrewException; - IteratorWithSunJavaBug6529795(Iterator<T> iterator) { - this.iterator = iterator; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public T next() { - try { - return iterator.next(); - } catch (NoSuchElementException e) { - nextThrewException = true; - throw e; - } - } - - @Override - public void remove() { - if (nextThrewException) { - throw new IllegalStateException(); - } - iterator.remove(); - } - } - - public void testCanCatchSunJavaBug6529795InTargetIterator() { - try { - /* Choose 4 steps to get sequence [next, next, next, remove] */ - new IteratorTester<Integer>(4, MODIFIABLE, newArrayList(1, 2), - IteratorTester.KnownOrder.KNOWN_ORDER) { - @Override protected Iterator<Integer> newTargetIterator() { - Iterator<Integer> iterator = Lists.newArrayList(1, 2).iterator(); - return new IteratorWithSunJavaBug6529795<Integer>(iterator); - } - }.test(); - } catch (AssertionFailedError e) { - return; - } - fail("Should have caught jdk6 bug in target iterator"); - } - - public void testCanWorkAroundSunJavaBug6529795InTargetIterator() { - IteratorTester<Integer> tester = - new IteratorTester<Integer>(4, MODIFIABLE, newArrayList(1, 2), - IteratorTester.KnownOrder.KNOWN_ORDER) { - @Override protected Iterator<Integer> newTargetIterator() { - Iterator<Integer> iterator = Lists.newArrayList(1, 2).iterator(); - return new IteratorWithSunJavaBug6529795<Integer>(iterator); - } - }; - - /* - * Calling this method on an IteratorTester should avoid flagging - * the bug exposed by the preceding test. - */ - tester.ignoreSunJavaBug6529795(); - - tester.test(); - } - - private static final int STEPS = 3; - static class TesterThatCountsCalls extends IteratorTester<Integer> { - TesterThatCountsCalls() { - super(STEPS, MODIFIABLE, newArrayList(1), - IteratorTester.KnownOrder.KNOWN_ORDER); - } - int numCallsToNewTargetIterator; - int numCallsToVerify; - @Override protected Iterator<Integer> newTargetIterator() { - numCallsToNewTargetIterator++; - return Lists.newArrayList(1).iterator(); - } - @Override protected void verify(List<Integer> elements) { - numCallsToVerify++; - super.verify(elements); - } - } - - public void testVerifyGetsCalled() { - TesterThatCountsCalls tester = new TesterThatCountsCalls(); - - tester.test(); - - assertEquals("Should have verified once per stimulus executed", - tester.numCallsToVerify, - tester.numCallsToNewTargetIterator * STEPS); - } - - public void testVerifyCanThrowAssertionThatFailsTest() { - final String message = "Important info about why verify failed"; - IteratorTester<Integer> tester = - new IteratorTester<Integer>(1, MODIFIABLE, newArrayList(1, 2, 3), - IteratorTester.KnownOrder.KNOWN_ORDER) { - @Override protected Iterator<Integer> newTargetIterator() { - return Lists.newArrayList(1, 2, 3).iterator(); - } - - @Override protected void verify(List<Integer> elements) { - throw new AssertionFailedError(message); - } - }; - AssertionFailedError actual = null; - try { - tester.test(); - } catch (AssertionFailedError e) { - actual = e; - } - assertNotNull("verify() should be able to cause test failure", actual); - assertTrue("AssertionFailedError should have info about why test failed", - actual.getCause().getMessage().contains(message)); - } - - public void testMissingException() { - List<Integer> emptyList = newArrayList(); - - IteratorTester<Integer> tester = - new IteratorTester<Integer>(1, MODIFIABLE, emptyList, - IteratorTester.KnownOrder.KNOWN_ORDER) { - @Override protected Iterator<Integer> newTargetIterator() { - return new Iterator<Integer>() { - @Override - public void remove() { - // We should throw here, but we won't! - } - @Override - public Integer next() { - // We should throw here, but we won't! - return null; - } - @Override - public boolean hasNext() { - return false; - } - }; - } - }; - assertFailure(tester); - } - - public void testUnexpectedException() { - IteratorTester<Integer> tester = - new IteratorTester<Integer>(1, MODIFIABLE, newArrayList(1), - IteratorTester.KnownOrder.KNOWN_ORDER) { - @Override protected Iterator<Integer> newTargetIterator() { - return new ThrowingIterator<Integer>(new IllegalStateException()); - } - }; - assertFailure(tester); - } - - public void testSimilarException() { - List<Integer> emptyList = emptyList(); - IteratorTester<Integer> tester = - new IteratorTester<Integer>(1, MODIFIABLE, emptyList, - IteratorTester.KnownOrder.KNOWN_ORDER) { - @Override protected Iterator<Integer> newTargetIterator() { - return new Iterator<Integer>() { - @Override - public void remove() { - throw new IllegalStateException() { /* subclass */}; - } - @Override - public Integer next() { - throw new NoSuchElementException() { /* subclass */}; - } - @Override - public boolean hasNext() { - return false; - } - }; - } - }; - tester.test(); - } - - public void testMismatchedException() { - List<Integer> emptyList = emptyList(); - IteratorTester<Integer> tester = - new IteratorTester<Integer>(1, MODIFIABLE, emptyList, - IteratorTester.KnownOrder.KNOWN_ORDER) { - @Override protected Iterator<Integer> newTargetIterator() { - return new Iterator<Integer>() { - @Override - public void remove() { - // Wrong exception type. - throw new IllegalArgumentException(); - } - @Override - public Integer next() { - // Wrong exception type. - throw new UnsupportedOperationException(); - } - @Override - public boolean hasNext() { - return false; - } - }; - } - }; - assertFailure(tester); - } - - private static void assertFailure(IteratorTester<?> tester) { - try { - tester.test(); - fail(); - } catch (AssertionFailedError expected) { - } - } - - private static final class ThrowingIterator<E> implements Iterator<E> { - private final RuntimeException ex; - - private ThrowingIterator(RuntimeException ex) { - this.ex = ex; - } - - @Override - public boolean hasNext() { - // IteratorTester doesn't expect exceptions for hasNext(). - return true; - } - - @Override - public E next() { - ex.fillInStackTrace(); - throw ex; - } - - @Override - public void remove() { - ex.fillInStackTrace(); - throw ex; - } - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/MapTestSuiteBuilderTests.java b/guava-testlib/test/com/google/common/collect/testing/MapTestSuiteBuilderTests.java deleted file mode 100644 index 43b1983..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/MapTestSuiteBuilderTests.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2008 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; -import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.Feature; -import com.google.common.collect.testing.features.MapFeature; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import java.util.AbstractMap; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - * Tests {@link MapTestSuiteBuilder} by using it against maps that have various - * negative behaviors. - * - * @author George van den Driessche - */ -public final class MapTestSuiteBuilderTests extends TestCase { - private MapTestSuiteBuilderTests() {} - - public static Test suite() { - TestSuite suite = new TestSuite( - MapTestSuiteBuilderTests.class.getSimpleName()); - suite.addTest(testsForHashMapNullKeysForbidden()); - suite.addTest(testsForHashMapNullValuesForbidden()); - return suite; - } - - private abstract static class WrappedHashMapGenerator - extends TestStringMapGenerator { - @Override protected final Map<String, String> create( - Map.Entry<String, String>[] entries) { - HashMap<String, String> map = Maps.newHashMap(); - for (Map.Entry<String, String> entry : entries) { - map.put(entry.getKey(), entry.getValue()); - } - return wrap(map); - } - - abstract Map<String, String> wrap(HashMap<String, String> map); - } - - private static TestSuite wrappedHashMapTests( - WrappedHashMapGenerator generator, String name, Feature<?>... features) { - return MapTestSuiteBuilder.using(generator) - .named(name) - .withFeatures(Lists.asList( - MapFeature.GENERAL_PURPOSE, CollectionSize.ANY, features)) - .createTestSuite(); - } - - // TODO: consider being null-hostile in these tests - - private static Test testsForHashMapNullKeysForbidden() { - return wrappedHashMapTests(new WrappedHashMapGenerator() { - @Override Map<String, String> wrap(final HashMap<String, String> map) { - if (map.containsKey(null)) { - throw new NullPointerException(); - } - return new AbstractMap<String, String>() { - @Override public Set<Map.Entry<String, String>> entrySet() { - return map.entrySet(); - } - @Override public String put(String key, String value) { - checkNotNull(key); - return map.put(key, value); - } - }; - } - }, "HashMap w/out null keys", ALLOWS_NULL_VALUES); - } - - private static Test testsForHashMapNullValuesForbidden() { - return wrappedHashMapTests(new WrappedHashMapGenerator() { - @Override Map<String, String> wrap(final HashMap<String, String> map) { - if (map.containsValue(null)) { - throw new NullPointerException(); - } - return new AbstractMap<String, String>() { - @Override public Set<Map.Entry<String, String>> entrySet() { - return map.entrySet(); - } - @Override public String put(String key, String value) { - checkNotNull(value); - return map.put(key, value); - } - }; - } - }, "HashMap w/out null values", ALLOWS_NULL_KEYS); - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/MinimalCollectionTest.java b/guava-testlib/test/com/google/common/collect/testing/MinimalCollectionTest.java deleted file mode 100644 index c701b63..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/MinimalCollectionTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2009 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import junit.framework.Test; -import junit.framework.TestCase; - -import java.util.Collection; - -/** - * Unit test for {@link MinimalCollection}. - * - * @author Kevin Bourrillion - */ -public class MinimalCollectionTest extends TestCase { - public static Test suite() { - return CollectionTestSuiteBuilder - .using(new TestStringCollectionGenerator() { - @Override public Collection<String> create(String[] elements) { - // TODO: MinimalCollection should perhaps throw - for (Object element : elements) { - if (element == null) { - throw new NullPointerException(); - } - } - return MinimalCollection.of(elements); - } - }) - .named("MinimalCollection") - .withFeatures( - CollectionFeature.NONE, - CollectionSize.ANY) - .createTestSuite(); - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/MinimalIterableTest.java b/guava-testlib/test/com/google/common/collect/testing/MinimalIterableTest.java deleted file mode 100644 index 540237d..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/MinimalIterableTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2009 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import junit.framework.TestCase; - -import java.util.Collections; -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - * Unit test for {@link MinimalIterable}. - * - * @author Kevin Bourrillion - */ -public class MinimalIterableTest extends TestCase { - - public void testOf_empty() { - Iterable<String> iterable = MinimalIterable.<String>of(); - Iterator<String> iterator = iterable.iterator(); - assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail(); - } catch (NoSuchElementException expected) { - } - try { - iterable.iterator(); - fail(); - } catch (IllegalStateException expected) { - } - } - - public void testOf_one() { - Iterable<String> iterable = MinimalIterable.of("a"); - Iterator<String> iterator = iterable.iterator(); - assertTrue(iterator.hasNext()); - assertEquals("a", iterator.next()); - assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail(); - } catch (NoSuchElementException expected) { - } - try { - iterable.iterator(); - fail(); - } catch (IllegalStateException expected) { - } - } - - public void testFrom_empty() { - Iterable<String> iterable - = MinimalIterable.from(Collections.<String>emptySet()); - Iterator<String> iterator = iterable.iterator(); - assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail(); - } catch (NoSuchElementException expected) { - } - try { - iterable.iterator(); - fail(); - } catch (IllegalStateException expected) { - } - } - - public void testFrom_one() { - Iterable<String> iterable - = MinimalIterable.from(Collections.singleton("a")); - Iterator<String> iterator = iterable.iterator(); - assertTrue(iterator.hasNext()); - assertEquals("a", iterator.next()); - try { - iterator.remove(); - fail(); - } catch (UnsupportedOperationException expected) { - } - assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail(); - } catch (NoSuchElementException expected) { - } - try { - iterable.iterator(); - fail(); - } catch (IllegalStateException expected) { - } - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/MinimalSetTest.java b/guava-testlib/test/com/google/common/collect/testing/MinimalSetTest.java deleted file mode 100644 index 1d21f13..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/MinimalSetTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2009 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; - -import junit.framework.Test; -import junit.framework.TestCase; - -import java.util.Set; - -/** - * Unit test for {@link MinimalSet}. - * - * @author Regina O'Dell - */ -public class MinimalSetTest extends TestCase { - public static Test suite() { - return SetTestSuiteBuilder - .using(new TestStringSetGenerator() { - @Override protected Set<String> create(String[] elements) { - return MinimalSet.of(elements); - } - }) - .named("MinimalSet") - .withFeatures( - CollectionFeature.ALLOWS_NULL_VALUES, - CollectionFeature.NONE, - CollectionSize.ANY) - .createTestSuite(); - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/OpenJdk6ListTests.java b/guava-testlib/test/com/google/common/collect/testing/OpenJdk6ListTests.java deleted file mode 100644 index d4cc2f4..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/OpenJdk6ListTests.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2009 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import static com.google.common.collect.testing.testers.CollectionIteratorTester.getIteratorKnownOrderRemoveSupportedMethod; -import static com.google.common.collect.testing.testers.CollectionToArrayTester.getToArrayIsPlainObjectArrayMethod; -import static com.google.common.collect.testing.testers.ListAddTester.getAddSupportedNullPresentMethod; -import static com.google.common.collect.testing.testers.ListListIteratorTester.getListIteratorFullyModifiableMethod; -import static com.google.common.collect.testing.testers.ListSetTester.getSetNullSupportedMethod; -import static com.google.common.collect.testing.testers.ListSubListTester.getSubListOriginalListSetAffectsSubListLargeListMethod; -import static com.google.common.collect.testing.testers.ListSubListTester.getSubListOriginalListSetAffectsSubListMethod; -import static com.google.common.collect.testing.testers.ListSubListTester.getSubListSubListRemoveAffectsOriginalLargeListMethod; - -import com.google.common.collect.testing.testers.CollectionAddTester; -import com.google.common.collect.testing.testers.ListAddAtIndexTester; - -import junit.framework.Test; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -/** - * Tests the {@link List} implementations of {@link java.util}, suppressing - * tests that trip known OpenJDK 6 bugs. - * - * @author Kevin Bourrillion - */ -public class OpenJdk6ListTests extends TestsForListsInJavaUtil { - public static Test suite() { - return new OpenJdk6ListTests().allTests(); - } - - @Override protected Collection<Method> suppressForArraysAsList() { - return Arrays.asList( - getToArrayIsPlainObjectArrayMethod()); - } - - @Override protected Collection<Method> suppressForCopyOnWriteArrayList() { - return Arrays.asList( - getSubListOriginalListSetAffectsSubListMethod(), - getSubListOriginalListSetAffectsSubListLargeListMethod(), - getSubListSubListRemoveAffectsOriginalLargeListMethod(), - getIteratorKnownOrderRemoveSupportedMethod(), - getListIteratorFullyModifiableMethod()); - } - - @Override protected Collection<Method> suppressForCheckedList() { - return Arrays.asList( - CollectionAddTester.getAddNullSupportedMethod(), - getAddSupportedNullPresentMethod(), - ListAddAtIndexTester.getAddNullSupportedMethod(), - getSetNullSupportedMethod()); - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/OpenJdk6MapTests.java b/guava-testlib/test/com/google/common/collect/testing/OpenJdk6MapTests.java deleted file mode 100644 index a56c77a..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/OpenJdk6MapTests.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2009 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import static com.google.common.collect.testing.testers.CollectionCreationTester.getCreateWithNullUnsupportedMethod; -import static com.google.common.collect.testing.testers.MapCreationTester.getCreateWithNullKeyUnsupportedMethod; -import static com.google.common.collect.testing.testers.MapPutAllTester.getPutAllNullKeyUnsupportedMethod; -import static com.google.common.collect.testing.testers.MapPutTester.getPutNullKeyUnsupportedMethod; - -import junit.framework.Test; -import junit.framework.TestSuite; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collection; -import java.util.Map; - -/** - * Tests the {@link Map} implementations of {@link java.util}, suppressing - * tests that trip known OpenJDK 6 bugs. - * - * @author Kevin Bourrillion - */ -public class OpenJdk6MapTests extends TestsForMapsInJavaUtil { - public static Test suite() { - return new OpenJdk6MapTests().allTests(); - } - - @Override protected Collection<Method> suppressForTreeMapNatural() { - return Arrays.asList( - getPutNullKeyUnsupportedMethod(), - getPutAllNullKeyUnsupportedMethod(), - getCreateWithNullKeyUnsupportedMethod(), - getCreateWithNullUnsupportedMethod()); // for keySet - } - - @Override public Test testsForEnumMap() { - // Do nothing. - // TODO: work around the reused-entry problem - // http://bugs.sun.com/view_bug.do?bug_id=6312706 - return new TestSuite(); - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/OpenJdk6QueueTests.java b/guava-testlib/test/com/google/common/collect/testing/OpenJdk6QueueTests.java deleted file mode 100644 index 6cc1dd3..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/OpenJdk6QueueTests.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2009 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import static com.google.common.collect.testing.testers.CollectionCreationTester.getCreateWithNullUnsupportedMethod; - -import junit.framework.Test; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Queue; - -/** - * Tests the {@link Queue} implementations of {@link java.util}, suppressing - * tests that trip known OpenJDK 6 bugs. - * - * @author Kevin Bourrillion - */ -public class OpenJdk6QueueTests extends TestsForQueuesInJavaUtil { - public static Test suite() { - return new OpenJdk6QueueTests().allTests(); - } - - private static final List<Method> PQ_SUPPRESS = Arrays.asList( - getCreateWithNullUnsupportedMethod()); - - @Override protected Collection<Method> suppressForPriorityBlockingQueue() { - return PQ_SUPPRESS; - } - - @Override protected Collection<Method> suppressForPriorityQueue() { - return PQ_SUPPRESS; - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/OpenJdk6SetTests.java b/guava-testlib/test/com/google/common/collect/testing/OpenJdk6SetTests.java deleted file mode 100644 index 77aa34f..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/OpenJdk6SetTests.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2009 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import static com.google.common.collect.testing.testers.CollectionAddAllTester.getAddAllNullUnsupportedMethod; -import static com.google.common.collect.testing.testers.CollectionAddTester.getAddNullSupportedMethod; -import static com.google.common.collect.testing.testers.CollectionAddTester.getAddNullUnsupportedMethod; -import static com.google.common.collect.testing.testers.CollectionCreationTester.getCreateWithNullUnsupportedMethod; -import static com.google.common.collect.testing.testers.CollectionIteratorTester.getIteratorKnownOrderRemoveSupportedMethod; -import static com.google.common.collect.testing.testers.SetAddTester.getAddSupportedNullPresentMethod; - -import junit.framework.Test; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collection; -import java.util.Set; - -/** - * Tests the {@link Set} implementations of {@link java.util}, suppressing - * tests that trip known OpenJDK 6 bugs. - * - * @author Kevin Bourrillion - */ -public class OpenJdk6SetTests extends TestsForSetsInJavaUtil { - public static Test suite() { - return new OpenJdk6SetTests().allTests(); - } - - @Override protected Collection<Method> suppressForTreeSetNatural() { - return Arrays.asList( - getAddNullUnsupportedMethod(), - getAddAllNullUnsupportedMethod(), - getCreateWithNullUnsupportedMethod()); - } - - @Override protected Collection<Method> suppressForCopyOnWriteArraySet() { - return Arrays.asList( - getIteratorKnownOrderRemoveSupportedMethod()); - } - - @Override protected Collection<Method> suppressForCheckedSet() { - return Arrays.asList( - getAddNullSupportedMethod(), - getAddSupportedNullPresentMethod()); - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/OpenJdk6Tests.java b/guava-testlib/test/com/google/common/collect/testing/OpenJdk6Tests.java deleted file mode 100644 index ebf93ef..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/OpenJdk6Tests.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2009 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Suite of tests for OpenJdk 6 tests. The existence of this class is a hack - * because the suitebuilder won't pick up the suites directly in the other - * classes because they don't extend TestCase. Ergh. - * - * @author Kevin Bourrillion - */ -public class OpenJdk6Tests extends TestCase { - public static Test suite() { - TestSuite suite = new TestSuite(); - suite.addTest(OpenJdk6SetTests.suite()); - suite.addTest(OpenJdk6ListTests.suite()); - suite.addTest(OpenJdk6QueueTests.suite()); - suite.addTest(OpenJdk6MapTests.suite()); - return suite; - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/SafeTreeMapTest.java b/guava-testlib/test/com/google/common/collect/testing/SafeTreeMapTest.java deleted file mode 100644 index 0532fbf..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/SafeTreeMapTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (C) 2010 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import static java.util.Collections.sort; - -import com.google.common.annotations.GwtIncompatible; -import com.google.common.collect.ImmutableSortedMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Ordering; -import com.google.common.collect.testing.Helpers.NullsBeforeTwo; -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.collect.testing.features.MapFeature; -import com.google.common.testing.SerializableTester; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.NavigableMap; -import java.util.SortedMap; - -/** - * Tests for SafeTreeMap. - * - * @author Louis Wasserman - */ -public class SafeTreeMapTest extends TestCase { - public static Test suite() { - TestSuite suite = new TestSuite(); - suite.addTestSuite(SafeTreeMapTest.class); - suite.addTest( - NavigableMapTestSuiteBuilder.using(new TestStringSortedMapGenerator() { - @Override protected SortedMap<String, String> create( - Entry<String, String>[] entries) { - NavigableMap<String, String> map = - new SafeTreeMap<String, String>(Ordering.natural()); - for (Entry<String, String> entry : entries) { - map.put(entry.getKey(), entry.getValue()); - } - return map; - } - }).withFeatures(CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, - MapFeature.ALLOWS_NULL_VALUES, MapFeature.GENERAL_PURPOSE).named( - "SafeTreeMap with natural comparator").createTestSuite()); - suite.addTest(NavigableMapTestSuiteBuilder.using(new TestStringSortedMapGenerator() { - @Override protected SortedMap<String, String> create( - Entry<String, String>[] entries) { - NavigableMap<String, String> map = - new SafeTreeMap<String, String>(NullsBeforeTwo.INSTANCE); - for (Entry<String, String> entry : entries) { - map.put(entry.getKey(), entry.getValue()); - } - return map; - } - - @Override - public Iterable<Entry<String, String>> order(List<Entry<String, String>> insertionOrder) { - sort(insertionOrder, Helpers.<String, String>entryComparator(NullsBeforeTwo.INSTANCE)); - return insertionOrder; - } - }).withFeatures(CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, - MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_NULL_VALUES, - MapFeature.GENERAL_PURPOSE).named( - "SafeTreeMap with null-friendly comparator").createTestSuite()); - return suite; - } - - @GwtIncompatible("SerializableTester") - public void testViewSerialization() { - Map<String, Integer> map = - ImmutableSortedMap.of("one", 1, "two", 2, "three", 3); - SerializableTester.reserializeAndAssert(map.entrySet()); - SerializableTester.reserializeAndAssert(map.keySet()); - assertEquals(Lists.newArrayList(map.values()), - Lists.newArrayList(SerializableTester.reserialize(map.values()))); - } - - @GwtIncompatible("SerializableTester") - public static class ReserializedMapTests - extends SortedMapInterfaceTest<String, Integer> { - ReserializedMapTests() { - super(false, true, true, true, true); - } - - @Override protected SortedMap<String, Integer> makePopulatedMap() { - NavigableMap<String, Integer> map = new SafeTreeMap<String, Integer>(); - map.put("one", 1); - map.put("two", 2); - map.put("three", 3); - return SerializableTester.reserialize(map); - } - - @Override protected SortedMap<String, Integer> makeEmptyMap() - throws UnsupportedOperationException { - NavigableMap<String, Integer> map = new SafeTreeMap<String, Integer>(); - return SerializableTester.reserialize(map); - } - - @Override protected String getKeyNotInPopulatedMap() { - return "minus one"; - } - - @Override protected Integer getValueNotInPopulatedMap() { - return -1; - } - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/SafeTreeSetTest.java b/guava-testlib/test/com/google/common/collect/testing/SafeTreeSetTest.java deleted file mode 100644 index a03081b..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/SafeTreeSetTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2010 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing; - -import com.google.common.annotations.GwtIncompatible; -import com.google.common.collect.ImmutableSortedMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Ordering; -import com.google.common.collect.Sets; -import com.google.common.collect.testing.features.CollectionFeature; -import com.google.common.collect.testing.features.CollectionSize; -import com.google.common.testing.SerializableTester; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.NavigableSet; -import java.util.Set; -import java.util.SortedSet; - -public class SafeTreeSetTest extends TestCase { - public static Test suite() { - TestSuite suite = new TestSuite(); - suite.addTestSuite(SafeTreeSetTest.class); - suite.addTest( - NavigableSetTestSuiteBuilder.using(new TestStringSetGenerator() { - @Override protected Set<String> create(String[] elements) { - return new SafeTreeSet<String>(Arrays.asList(elements)); - } - - @Override public List<String> order(List<String> insertionOrder) { - return Lists.newArrayList(Sets.newTreeSet(insertionOrder)); - } - }).withFeatures(CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, - CollectionFeature.GENERAL_PURPOSE).named( - "SafeTreeSet with natural comparator").createTestSuite()); - suite.addTest(SetTestSuiteBuilder.using(new TestStringSetGenerator() { - @Override protected Set<String> create(String[] elements) { - NavigableSet<String> set = - new SafeTreeSet<String>(Ordering.natural().nullsFirst()); - set.addAll(Arrays.asList(elements)); - return set; - } - - @Override public List<String> order(List<String> insertionOrder) { - return Lists.newArrayList(Sets.newTreeSet(insertionOrder)); - } - }).withFeatures(CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, - CollectionFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES) - .named("SafeTreeSet with null-friendly comparator").createTestSuite()); - return suite; - } - - @GwtIncompatible("SerializableTester") - public void testViewSerialization() { - Map<String, Integer> map = - ImmutableSortedMap.of("one", 1, "two", 2, "three", 3); - SerializableTester.reserializeAndAssert(map.entrySet()); - SerializableTester.reserializeAndAssert(map.keySet()); - assertEquals(Lists.newArrayList(map.values()), - Lists.newArrayList(SerializableTester.reserialize(map.values()))); - } - - @GwtIncompatible("SerializableTester") - public void testEmpty_serialization() { - SortedSet<String> set = new SafeTreeSet<String>(); - SortedSet<String> copy = SerializableTester.reserializeAndAssert(set); - assertEquals(set.comparator(), copy.comparator()); - } - - @GwtIncompatible("SerializableTester") - public void testSingle_serialization() { - SortedSet<String> set = new SafeTreeSet<String>(); - set.add("e"); - SortedSet<String> copy = SerializableTester.reserializeAndAssert(set); - assertEquals(set.comparator(), copy.comparator()); - } - - @GwtIncompatible("SerializableTester") - public void testSeveral_serialization() { - SortedSet<String> set = new SafeTreeSet<String>(); - set.add("a"); - set.add("b"); - set.add("c"); - SortedSet<String> copy = SerializableTester.reserializeAndAssert(set); - assertEquals(set.comparator(), copy.comparator()); - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/features/FeatureEnumTest.java b/guava-testlib/test/com/google/common/collect/testing/features/FeatureEnumTest.java deleted file mode 100644 index 394dcd4..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/features/FeatureEnumTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2008 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing.features; - -import junit.framework.TestCase; - -import java.lang.annotation.Annotation; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.reflect.Method; - -/** - * Since annotations have some reusability issues that force copy and paste - * all over the place, it's worth having a test to ensure that all our Feature - * enums have their annotations correctly set up. - * - * @author George van den Driessche - */ -public class FeatureEnumTest extends TestCase { - private static void assertGoodTesterAnnotation( - Class<? extends Annotation> annotationClass) { - assertNotNull( - String.format("%s must be annotated with @TesterAnnotation.", - annotationClass), - annotationClass.getAnnotation(TesterAnnotation.class)); - final Retention retentionPolicy = - annotationClass.getAnnotation(Retention.class); - assertNotNull( - String.format("%s must have a @Retention annotation.", annotationClass), - retentionPolicy); - assertEquals( - String.format("%s must have RUNTIME RetentionPolicy.", annotationClass), - RetentionPolicy.RUNTIME, retentionPolicy.value()); - assertNotNull( - String.format("%s must be inherited.", annotationClass), - annotationClass.getAnnotation(Inherited.class)); - - for (String propertyName : new String[]{"value", "absent"}) { - Method method = null; - try { - method = annotationClass.getMethod(propertyName); - } catch (NoSuchMethodException e) { - fail(String.format("%s must have a property named '%s'.", - annotationClass, propertyName)); - } - final Class<?> returnType = method.getReturnType(); - assertTrue(String.format("%s.%s() must return an array.", - annotationClass, propertyName), - returnType.isArray()); - assertSame(String.format("%s.%s() must return an array of %s.", - annotationClass, propertyName, annotationClass.getDeclaringClass()), - annotationClass.getDeclaringClass(), returnType.getComponentType()); - } - } - - // This is public so that tests for Feature enums we haven't yet imagined - // can reuse it. - public static <E extends Enum<?> & Feature<?>> void assertGoodFeatureEnum( - Class<E> featureEnumClass) { - final Class<?>[] classes = featureEnumClass.getDeclaredClasses(); - for (Class<?> containedClass : classes) { - if (containedClass.getSimpleName().equals("Require")) { - if (containedClass.isAnnotation()) { - assertGoodTesterAnnotation(asAnnotation(containedClass)); - } else { - fail(String.format("Feature enum %s contains a class named " + - "'Require' but it is not an annotation.", featureEnumClass)); - } - return; - } - } - fail(String.format("Feature enum %s should contain an " + - "annotation named 'Require'.", featureEnumClass)); - } - - @SuppressWarnings("unchecked") - private static Class<? extends Annotation> asAnnotation(Class<?> clazz) { - if (clazz.isAnnotation()) { - return (Class<? extends Annotation>) clazz; - } else { - throw new IllegalArgumentException( - String.format("%s is not an annotation.", clazz)); - } - } - - public void testFeatureEnums() throws Exception { - assertGoodFeatureEnum(CollectionFeature.class); - assertGoodFeatureEnum(ListFeature.class); - assertGoodFeatureEnum(SetFeature.class); - assertGoodFeatureEnum(CollectionSize.class); - assertGoodFeatureEnum(MapFeature.class); - } -} diff --git a/guava-testlib/test/com/google/common/collect/testing/features/FeatureUtilTest.java b/guava-testlib/test/com/google/common/collect/testing/features/FeatureUtilTest.java deleted file mode 100644 index c92c75f..0000000 --- a/guava-testlib/test/com/google/common/collect/testing/features/FeatureUtilTest.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * Copyright (C) 2008 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.collect.testing.features; - -import static org.truth0.Truth.ASSERT; - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Sets; - -import junit.framework.TestCase; - -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.reflect.Method; -import java.util.Collections; -import java.util.Set; - -/** - * @author George van den Driessche - */ -// Enum values use constructors with generic varargs. -@SuppressWarnings("unchecked") -public class FeatureUtilTest extends TestCase { - interface ExampleBaseInterface { - void behave(); - } - - interface ExampleDerivedInterface extends ExampleBaseInterface { - void misbehave(); - } - - enum ExampleBaseFeature implements Feature<ExampleBaseInterface> { - BASE_FEATURE_1, - BASE_FEATURE_2; - - @Override - public Set<Feature<? super ExampleBaseInterface>> getImpliedFeatures() { - return Collections.emptySet(); - } - - @Retention(RetentionPolicy.RUNTIME) - @Inherited - @TesterAnnotation - @interface Require { - ExampleBaseFeature[] value() default {}; - ExampleBaseFeature[] absent() default {}; - } - } - - enum ExampleDerivedFeature implements Feature<ExampleDerivedInterface>{ - DERIVED_FEATURE_1, - DERIVED_FEATURE_2(ExampleBaseFeature.BASE_FEATURE_1), - DERIVED_FEATURE_3, - - COMPOUND_DERIVED_FEATURE( - DERIVED_FEATURE_1, - DERIVED_FEATURE_2, - ExampleBaseFeature.BASE_FEATURE_2); - - private Set<Feature<? super ExampleDerivedInterface>> implied; - - ExampleDerivedFeature( - Feature<? super ExampleDerivedInterface> ... implied) { - this.implied = ImmutableSet.copyOf(implied); - } - - @Override - public Set<Feature<? super ExampleDerivedInterface>> getImpliedFeatures() { - return implied; - } - - @Retention(RetentionPolicy.RUNTIME) - @Inherited - @TesterAnnotation - @interface Require { - ExampleDerivedFeature[] value() default {}; - ExampleDerivedFeature[] absent() default {}; - } - } - - @Retention(RetentionPolicy.RUNTIME) - @interface NonTesterAnnotation { - } - - @ExampleBaseFeature.Require({ExampleBaseFeature.BASE_FEATURE_1}) - private static abstract class ExampleBaseInterfaceTester extends TestCase { - protected final void doNotActuallyRunThis() { - fail("Nobody's meant to actually run this!"); - } - } - - @NonTesterAnnotation - @ExampleDerivedFeature.Require({ExampleDerivedFeature.DERIVED_FEATURE_2}) - private static class ExampleDerivedInterfaceTester - extends ExampleBaseInterfaceTester { - // Exists to test that our framework doesn't run it: - @SuppressWarnings("unused") - @ExampleDerivedFeature.Require({ - ExampleDerivedFeature.DERIVED_FEATURE_1, - ExampleDerivedFeature.DERIVED_FEATURE_2}) - public void testRequiringTwoExplicitDerivedFeatures() throws Exception { - doNotActuallyRunThis(); - } - - // Exists to test that our framework doesn't run it: - @SuppressWarnings("unused") - @ExampleDerivedFeature.Require({ - ExampleDerivedFeature.DERIVED_FEATURE_1, - ExampleDerivedFeature.DERIVED_FEATURE_3}) - public void testRequiringAllThreeDerivedFeatures() { - doNotActuallyRunThis(); - } - - // Exists to test that our framework doesn't run it: - @SuppressWarnings("unused") - @ExampleBaseFeature.Require(absent = {ExampleBaseFeature.BASE_FEATURE_1}) - public void testRequiringConflictingFeatures() throws Exception { - doNotActuallyRunThis(); - } - } - - @ExampleDerivedFeature.Require( - absent = {ExampleDerivedFeature.DERIVED_FEATURE_2}) - private static class ExampleDerivedInterfaceTester_Conflict - extends ExampleBaseInterfaceTester { - } - - public void testTestFeatureEnums() throws Exception { - // Haha! Let's test our own test rig! - FeatureEnumTest.assertGoodFeatureEnum( - FeatureUtilTest.ExampleBaseFeature.class); - FeatureEnumTest.assertGoodFeatureEnum( - FeatureUtilTest.ExampleDerivedFeature.class); - } - - public void testAddImpliedFeatures_returnsSameSetInstance() throws Exception { - Set<Feature<?>> features = Sets.<Feature<?>>newHashSet( - ExampleBaseFeature.BASE_FEATURE_1); - assertSame(features, FeatureUtil.addImpliedFeatures(features)); - } - - public void testAddImpliedFeatures_addsImpliedFeatures() throws Exception { - Set<Feature<?>> features; - - features = Sets.<Feature<?>>newHashSet( - ExampleDerivedFeature.DERIVED_FEATURE_1); - ASSERT.that(FeatureUtil.addImpliedFeatures(features)).has().item( - ExampleDerivedFeature.DERIVED_FEATURE_1); - - features = Sets.<Feature<?>>newHashSet( - ExampleDerivedFeature.DERIVED_FEATURE_2); - ASSERT.that(FeatureUtil.addImpliedFeatures(features)).has().allOf( - ExampleDerivedFeature.DERIVED_FEATURE_2, - ExampleBaseFeature.BASE_FEATURE_1); - - features = Sets.<Feature<?>>newHashSet( - ExampleDerivedFeature.COMPOUND_DERIVED_FEATURE); - ASSERT.that(FeatureUtil.addImpliedFeatures(features)).has().allOf( - ExampleDerivedFeature.COMPOUND_DERIVED_FEATURE, - ExampleDerivedFeature.DERIVED_FEATURE_1, - ExampleDerivedFeature.DERIVED_FEATURE_2, - ExampleBaseFeature.BASE_FEATURE_1, - ExampleBaseFeature.BASE_FEATURE_2); - } - - public void testImpliedFeatures_returnsNewSetInstance() throws Exception { - Set<Feature<?>> features = Sets.<Feature<?>>newHashSet( - ExampleBaseFeature.BASE_FEATURE_1); - assertNotSame(features, FeatureUtil.impliedFeatures(features)); - } - - public void testImpliedFeatures_returnsImpliedFeatures() throws Exception { - Set<Feature<?>> features; - - features = Sets.<Feature<?>>newHashSet( - ExampleDerivedFeature.DERIVED_FEATURE_1); - assertTrue(FeatureUtil.impliedFeatures(features).isEmpty()); - - features = Sets.<Feature<?>>newHashSet( - ExampleDerivedFeature.DERIVED_FEATURE_2); - ASSERT.that(FeatureUtil.impliedFeatures(features)).has().item( - ExampleBaseFeature.BASE_FEATURE_1); - - features = Sets.<Feature<?>>newHashSet( - ExampleDerivedFeature.COMPOUND_DERIVED_FEATURE); - ASSERT.that(FeatureUtil.impliedFeatures(features)).has().allOf( - ExampleDerivedFeature.DERIVED_FEATURE_1, - ExampleDerivedFeature.DERIVED_FEATURE_2, - ExampleBaseFeature.BASE_FEATURE_1, - ExampleBaseFeature.BASE_FEATURE_2); - } - - public void testBuildTesterRequirements_class() throws Exception { - assertEquals(FeatureUtil.buildTesterRequirements( - ExampleBaseInterfaceTester.class), - new TesterRequirements( - Sets.<Feature<?>>newHashSet(ExampleBaseFeature.BASE_FEATURE_1), - Collections.<Feature<?>>emptySet())); - - assertEquals(FeatureUtil.buildTesterRequirements( - ExampleDerivedInterfaceTester.class), - new TesterRequirements( - Sets.<Feature<?>>newHashSet( - ExampleBaseFeature.BASE_FEATURE_1, - ExampleDerivedFeature.DERIVED_FEATURE_2), - Collections.<Feature<?>>emptySet())); - } - - public void testBuildTesterRequirements_method() throws Exception { - assertEquals(FeatureUtil.buildTesterRequirements( - ExampleDerivedInterfaceTester.class.getMethod( - "testRequiringTwoExplicitDerivedFeatures")), - new TesterRequirements( - Sets.<Feature<?>>newHashSet( - ExampleBaseFeature.BASE_FEATURE_1, - ExampleDerivedFeature.DERIVED_FEATURE_1, - ExampleDerivedFeature.DERIVED_FEATURE_2), - Collections.<Feature<?>>emptySet())); - assertEquals(FeatureUtil.buildTesterRequirements( - ExampleDerivedInterfaceTester.class.getMethod( - "testRequiringAllThreeDerivedFeatures")), - new TesterRequirements( - Sets.<Feature<?>>newHashSet( - ExampleBaseFeature.BASE_FEATURE_1, - ExampleDerivedFeature.DERIVED_FEATURE_1, - ExampleDerivedFeature.DERIVED_FEATURE_2, - ExampleDerivedFeature.DERIVED_FEATURE_3), - Collections.<Feature<?>>emptySet())); - } - - public void testBuildTesterRequirements_classClassConflict() - throws Exception { - try { - FeatureUtil.buildTesterRequirements( - ExampleDerivedInterfaceTester_Conflict.class); - fail("Expected ConflictingRequirementsException"); - } catch (ConflictingRequirementsException e) { - ASSERT.that(e.getConflicts()).has().item( - ExampleBaseFeature.BASE_FEATURE_1); - assertEquals(ExampleDerivedInterfaceTester_Conflict.class, e.getSource()); - } - } - - public void testBuildTesterRequirements_methodClassConflict() - throws Exception { - final Method method = ExampleDerivedInterfaceTester.class - .getMethod("testRequiringConflictingFeatures"); - try { - FeatureUtil.buildTesterRequirements(method); - fail("Expected ConflictingRequirementsException"); - } catch (ConflictingRequirementsException e) { - ASSERT.that(e.getConflicts()).has().item( - ExampleBaseFeature.BASE_FEATURE_1); - assertEquals(method, e.getSource()); - } - } - - public void testBuildDeclaredTesterRequirements() throws Exception { - assertEquals(FeatureUtil.buildDeclaredTesterRequirements( - ExampleDerivedInterfaceTester.class - .getMethod("testRequiringTwoExplicitDerivedFeatures")), - new TesterRequirements(FeatureUtil.addImpliedFeatures( - Sets.<Feature<?>>newHashSet( - ExampleDerivedFeature.DERIVED_FEATURE_1, - ExampleDerivedFeature.DERIVED_FEATURE_2)), - Collections.<Feature<?>>emptySet())); - } - -} diff --git a/guava-testlib/test/com/google/common/testing/AbstractPackageSanityTestsTest.java b/guava-testlib/test/com/google/common/testing/AbstractPackageSanityTestsTest.java deleted file mode 100644 index 686e6ae..0000000 --- a/guava-testlib/test/com/google/common/testing/AbstractPackageSanityTestsTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * 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.testing; - -import static org.truth0.Truth.ASSERT; - -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableList; - -import junit.framework.TestCase; - -import java.util.Arrays; -import java.util.List; - -/** - * Unit tests for {@link AbstractPackageSanityTests}. - * - * @author Ben Yu - */ -public class AbstractPackageSanityTestsTest extends TestCase { - - private final AbstractPackageSanityTests sanityTests = new AbstractPackageSanityTests() {}; - - public void testFindClassesToTest_testClass() { - ASSERT.that(findClassesToTest(ImmutableList.of(EmptyTest.class))) - .isEmpty(); - ASSERT.that(findClassesToTest(ImmutableList.of(EmptyTests.class))) - .isEmpty(); - ASSERT.that(findClassesToTest(ImmutableList.of(EmptyTestCase.class))) - .isEmpty(); - ASSERT.that(findClassesToTest(ImmutableList.of(EmptyTestSuite.class))) - .isEmpty(); - } - - public void testFindClassesToTest_noCorrespondingTestClass() { - ASSERT.that(findClassesToTest(ImmutableList.of(Foo.class))) - .has().allOf(Foo.class).inOrder(); - ASSERT.that(findClassesToTest(ImmutableList.of(Foo.class, Foo2Test.class))) - .has().allOf(Foo.class).inOrder(); - } - - public void testFindClassesToTest_publicApiOnly() { - sanityTests.publicApiOnly(); - ASSERT.that(findClassesToTest(ImmutableList.of(Foo.class))) - .isEmpty(); - ASSERT.that(findClassesToTest(ImmutableList.of(PublicFoo.class))).has().item(PublicFoo.class); - } - - public void testFindClassesToTest_ignoreClasses() { - sanityTests.ignoreClasses(Predicates.<Object>equalTo(PublicFoo.class)); - ASSERT.that(findClassesToTest(ImmutableList.of(PublicFoo.class))) - .isEmpty(); - ASSERT.that(findClassesToTest(ImmutableList.of(Foo.class))).has().item(Foo.class); - } - - public void testFindClassesToTest_withCorrespondingTestClassButNotExplicitlyTested() { - ASSERT.that(findClassesToTest(ImmutableList.of(Foo.class, FooTest.class), "testNotThere")) - .has().allOf(Foo.class).inOrder(); - ASSERT.that(findClassesToTest(ImmutableList.of(Foo.class, FooTest.class), "testNotPublic")) - .has().allOf(Foo.class).inOrder(); - } - - public void testFindClassesToTest_withCorrespondingTestClassAndExplicitlyTested() { - ImmutableList<Class<? extends Object>> classes = ImmutableList.of(Foo.class, FooTest.class); - ASSERT.that(findClassesToTest(classes, "testPublic")) - .isEmpty(); - ASSERT.that(findClassesToTest(classes, "testNotThere", "testPublic")) - .isEmpty(); - } - - public void testFindClassesToTest_withCorrespondingTestClass_noTestName() { - ASSERT.that(findClassesToTest(ImmutableList.of(Foo.class, FooTest.class))) - .has().allOf(Foo.class).inOrder(); - } - - static class EmptyTestCase {} - - static class EmptyTest {} - - static class EmptyTests {} - - static class EmptyTestSuite {} - - static class Foo {} - - public static class PublicFoo {} - - static class FooTest { - @SuppressWarnings("unused") // accessed reflectively - public void testPublic() {} - @SuppressWarnings("unused") // accessed reflectively - void testNotPublic() {} - } - - // Shouldn't be mistaken as Foo's test - static class Foo2Test { - @SuppressWarnings("unused") // accessed reflectively - public void testPublic() {} - } - - private List<Class<?>> findClassesToTest( - Iterable<? extends Class<?>> classes, String... explicitTestNames) { - return sanityTests.findClassesToTest(classes, Arrays.asList(explicitTestNames)); - } -} diff --git a/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java b/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java deleted file mode 100644 index a215e7e..0000000 --- a/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * 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.testing; - -import com.google.common.base.CharMatcher; -import com.google.common.base.Charsets; -import com.google.common.base.Equivalence; -import com.google.common.base.Joiner; -import com.google.common.base.Optional; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import com.google.common.base.Stopwatch; -import com.google.common.base.Ticker; -import com.google.common.collect.BiMap; -import com.google.common.collect.ClassToInstanceMap; -import com.google.common.collect.Constraint; -import com.google.common.collect.ImmutableBiMap; -import com.google.common.collect.ImmutableClassToInstanceMap; -import com.google.common.collect.ImmutableCollection; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableListMultimap; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.ImmutableMultiset; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSetMultimap; -import com.google.common.collect.ImmutableSortedMap; -import com.google.common.collect.ImmutableSortedSet; -import com.google.common.collect.ImmutableTable; -import com.google.common.collect.Iterators; -import com.google.common.collect.ListMultimap; -import com.google.common.collect.MapConstraint; -import com.google.common.collect.MapDifference; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multiset; -import com.google.common.collect.PeekingIterator; -import com.google.common.collect.Range; -import com.google.common.collect.RowSortedTable; -import com.google.common.collect.SetMultimap; -import com.google.common.collect.SortedMapDifference; -import com.google.common.collect.SortedMultiset; -import com.google.common.collect.SortedSetMultimap; -import com.google.common.collect.Table; -import com.google.common.primitives.UnsignedInteger; -import com.google.common.primitives.UnsignedLong; -import com.google.common.util.concurrent.AtomicDouble; - -import junit.framework.TestCase; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.GenericDeclaration; -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.DoubleBuffer; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.nio.LongBuffer; -import java.nio.ShortBuffer; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.BitSet; -import java.util.Collection; -import java.util.Comparator; -import java.util.Currency; -import java.util.Deque; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.ListIterator; -import java.util.Locale; -import java.util.Map; -import java.util.NavigableMap; -import java.util.NavigableSet; -import java.util.PriorityQueue; -import java.util.Queue; -import java.util.Random; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.concurrent.BlockingDeque; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ConcurrentNavigableMap; -import java.util.concurrent.DelayQueue; -import java.util.concurrent.Executor; -import java.util.concurrent.PriorityBlockingQueue; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; -import java.util.regex.MatchResult; -import java.util.regex.Pattern; - -/** - * Unit test for {@link ArbitraryInstances}. - * - * @author Ben Yu - */ -public class ArbitraryInstancesTest extends TestCase { - - public void testGet_primitives() { - assertNull(ArbitraryInstances.get(void.class)); - assertNull(ArbitraryInstances.get(Void.class)); - assertEquals(Boolean.FALSE, ArbitraryInstances.get(boolean.class)); - assertEquals(Boolean.FALSE, ArbitraryInstances.get(Boolean.class)); - assertEquals(Character.valueOf('\0'), ArbitraryInstances.get(char.class)); - assertEquals(Character.valueOf('\0'), ArbitraryInstances.get(Character.class)); - assertEquals(Byte.valueOf((byte) 0), ArbitraryInstances.get(byte.class)); - assertEquals(Byte.valueOf((byte) 0), ArbitraryInstances.get(Byte.class)); - assertEquals(Short.valueOf((short) 0), ArbitraryInstances.get(short.class)); - assertEquals(Short.valueOf((short) 0), ArbitraryInstances.get(Short.class)); - assertEquals(Integer.valueOf(0), ArbitraryInstances.get(int.class)); - assertEquals(Integer.valueOf(0), ArbitraryInstances.get(Integer.class)); - assertEquals(Long.valueOf(0), ArbitraryInstances.get(long.class)); - assertEquals(Long.valueOf(0), ArbitraryInstances.get(Long.class)); - assertEquals(Float.valueOf(0), ArbitraryInstances.get(float.class)); - assertEquals(Float.valueOf(0), ArbitraryInstances.get(Float.class)); - assertEquals(Double.valueOf(0), ArbitraryInstances.get(double.class)); - assertEquals(Double.valueOf(0), ArbitraryInstances.get(Double.class)); - assertEquals(UnsignedInteger.ZERO, ArbitraryInstances.get(UnsignedInteger.class)); - assertEquals(UnsignedLong.ZERO, ArbitraryInstances.get(UnsignedLong.class)); - assertEquals(0, ArbitraryInstances.get(BigDecimal.class).intValue()); - assertEquals(0, ArbitraryInstances.get(BigInteger.class).intValue()); - assertEquals("", ArbitraryInstances.get(String.class)); - assertEquals("", ArbitraryInstances.get(CharSequence.class)); - assertEquals(TimeUnit.SECONDS, ArbitraryInstances.get(TimeUnit.class)); - assertNotNull(ArbitraryInstances.get(Object.class)); - assertEquals(0, ArbitraryInstances.get(Number.class)); - assertEquals(Charsets.UTF_8, ArbitraryInstances.get(Charset.class)); - } - - public void testGet_collections() { - assertEquals(Iterators.emptyIterator(), ArbitraryInstances.get(Iterator.class)); - assertFalse(ArbitraryInstances.get(PeekingIterator.class).hasNext()); - assertFalse(ArbitraryInstances.get(ListIterator.class).hasNext()); - assertEquals(ImmutableSet.of(), ArbitraryInstances.get(Iterable.class)); - assertEquals(ImmutableSet.of(), ArbitraryInstances.get(Set.class)); - assertEquals(ImmutableSet.of(), ArbitraryInstances.get(ImmutableSet.class)); - assertEquals(ImmutableSortedSet.of(), ArbitraryInstances.get(SortedSet.class)); - assertEquals(ImmutableSortedSet.of(), ArbitraryInstances.get(ImmutableSortedSet.class)); - assertEquals(ImmutableList.of(), ArbitraryInstances.get(Collection.class)); - assertEquals(ImmutableList.of(), ArbitraryInstances.get(ImmutableCollection.class)); - assertEquals(ImmutableList.of(), ArbitraryInstances.get(List.class)); - assertEquals(ImmutableList.of(), ArbitraryInstances.get(ImmutableList.class)); - assertEquals(ImmutableMap.of(), ArbitraryInstances.get(Map.class)); - assertEquals(ImmutableMap.of(), ArbitraryInstances.get(ImmutableMap.class)); - assertEquals(ImmutableSortedMap.of(), ArbitraryInstances.get(SortedMap.class)); - assertEquals(ImmutableSortedMap.of(), ArbitraryInstances.get(ImmutableSortedMap.class)); - assertEquals(ImmutableMultiset.of(), ArbitraryInstances.get(Multiset.class)); - assertEquals(ImmutableMultiset.of(), ArbitraryInstances.get(ImmutableMultiset.class)); - assertTrue(ArbitraryInstances.get(SortedMultiset.class).isEmpty()); - assertEquals(ImmutableMultimap.of(), ArbitraryInstances.get(Multimap.class)); - assertEquals(ImmutableMultimap.of(), ArbitraryInstances.get(ImmutableMultimap.class)); - assertTrue(ArbitraryInstances.get(SortedSetMultimap.class).isEmpty()); - assertEquals(ImmutableTable.of(), ArbitraryInstances.get(Table.class)); - assertEquals(ImmutableTable.of(), ArbitraryInstances.get(ImmutableTable.class)); - assertTrue(ArbitraryInstances.get(RowSortedTable.class).isEmpty()); - assertEquals(ImmutableBiMap.of(), ArbitraryInstances.get(BiMap.class)); - assertEquals(ImmutableBiMap.of(), ArbitraryInstances.get(ImmutableBiMap.class)); - assertTrue(ArbitraryInstances.get(ImmutableClassToInstanceMap.class).isEmpty()); - assertTrue(ArbitraryInstances.get(ClassToInstanceMap.class).isEmpty()); - assertTrue(ArbitraryInstances.get(ListMultimap.class).isEmpty()); - assertTrue(ArbitraryInstances.get(ImmutableListMultimap.class).isEmpty()); - assertTrue(ArbitraryInstances.get(SetMultimap.class).isEmpty()); - assertTrue(ArbitraryInstances.get(ImmutableSetMultimap.class).isEmpty()); - assertTrue(ArbitraryInstances.get(MapDifference.class).areEqual()); - assertTrue(ArbitraryInstances.get(SortedMapDifference.class).areEqual()); - assertEquals(Range.all(), ArbitraryInstances.get(Range.class)); - assertTrue(ArbitraryInstances.get(NavigableSet.class).isEmpty()); - assertTrue(ArbitraryInstances.get(NavigableMap.class).isEmpty()); - assertTrue(ArbitraryInstances.get(LinkedList.class).isEmpty()); - assertTrue(ArbitraryInstances.get(Deque.class).isEmpty()); - assertTrue(ArbitraryInstances.get(Queue.class).isEmpty()); - assertTrue(ArbitraryInstances.get(PriorityQueue.class).isEmpty()); - assertTrue(ArbitraryInstances.get(BitSet.class).isEmpty()); - assertTrue(ArbitraryInstances.get(TreeSet.class).isEmpty()); - assertTrue(ArbitraryInstances.get(TreeMap.class).isEmpty()); - assertFreshInstanceReturned( - LinkedList.class, Deque.class, Queue.class, PriorityQueue.class, BitSet.class, - TreeSet.class, TreeMap.class); - } - - public void testGet_misc() { - assertNotNull(ArbitraryInstances.get(CharMatcher.class)); - assertNotNull(ArbitraryInstances.get(Currency.class).getCurrencyCode()); - assertNotNull(ArbitraryInstances.get(Locale.class)); - ArbitraryInstances.get(Joiner.class).join(ImmutableList.of("a")); - ArbitraryInstances.get(Splitter.class).split("a,b"); - assertFalse(ArbitraryInstances.get(Optional.class).isPresent()); - ArbitraryInstances.get(Stopwatch.class).start(); - assertNotNull(ArbitraryInstances.get(Ticker.class)); - assertNotNull(ArbitraryInstances.get(Constraint.class)); - assertNotNull(ArbitraryInstances.get(MapConstraint.class)); - assertFreshInstanceReturned(Random.class); - assertEquals(ArbitraryInstances.get(Random.class).nextInt(), - ArbitraryInstances.get(Random.class).nextInt()); - } - - public void testGet_concurrent() { - assertTrue(ArbitraryInstances.get(BlockingDeque.class).isEmpty()); - assertTrue(ArbitraryInstances.get(BlockingQueue.class).isEmpty()); - assertTrue(ArbitraryInstances.get(DelayQueue.class).isEmpty()); - assertTrue(ArbitraryInstances.get(SynchronousQueue.class).isEmpty()); - assertTrue(ArbitraryInstances.get(PriorityBlockingQueue.class).isEmpty()); - assertTrue(ArbitraryInstances.get(ConcurrentMap.class).isEmpty()); - assertTrue(ArbitraryInstances.get(ConcurrentNavigableMap.class).isEmpty()); - ArbitraryInstances.get(Executor.class).execute(ArbitraryInstances.get(Runnable.class)); - assertNotNull(ArbitraryInstances.get(ThreadFactory.class)); - assertFreshInstanceReturned( - BlockingQueue.class, BlockingDeque.class, PriorityBlockingQueue.class, - DelayQueue.class, SynchronousQueue.class, - ConcurrentMap.class, ConcurrentNavigableMap.class, - AtomicReference.class, AtomicBoolean.class, - AtomicInteger.class, AtomicLong.class, AtomicDouble.class); - } - - @SuppressWarnings("unchecked") // functor classes have no type parameters - public void testGet_functors() { - assertEquals(0, ArbitraryInstances.get(Comparator.class).compare("abc", 123)); - assertTrue(ArbitraryInstances.get(Predicate.class).apply("abc")); - assertTrue(ArbitraryInstances.get(Equivalence.class).equivalent(1, 1)); - assertFalse(ArbitraryInstances.get(Equivalence.class).equivalent(1, 2)); - } - - public void testGet_comparable() { - @SuppressWarnings("unchecked") // The null value can compare with any Object - Comparable<Object> comparable = ArbitraryInstances.get(Comparable.class); - assertEquals(0, comparable.compareTo(comparable)); - assertTrue(comparable.compareTo("") > 0); - try { - comparable.compareTo(null); - fail(); - } catch (NullPointerException expected) {} - } - - public void testGet_array() { - assertEquals(0, ArbitraryInstances.get(int[].class).length); - assertEquals(0, ArbitraryInstances.get(Object[].class).length); - assertEquals(0, ArbitraryInstances.get(String[].class).length); - } - - public void testGet_enum() { - assertNull(ArbitraryInstances.get(EmptyEnum.class)); - assertEquals(Direction.UP, ArbitraryInstances.get(Direction.class)); - } - - public void testGet_interface() { - assertNull(ArbitraryInstances.get(SomeInterface.class)); - } - - public void testGet_runnable() { - ArbitraryInstances.get(Runnable.class).run(); - } - - public void testGet_class() { - assertNull(ArbitraryInstances.get(SomeAbstractClass.class)); - assertNull(ArbitraryInstances.get(WithPrivateConstructor.class)); - assertNull(ArbitraryInstances.get(NoDefaultConstructor.class)); - assertNull(ArbitraryInstances.get(WithExceptionalConstructor.class)); - assertNull(ArbitraryInstances.get(NonPublicClass.class)); - } - - public void testGet_mutable() { - assertEquals(0, ArbitraryInstances.get(ArrayList.class).size()); - assertEquals(0, ArbitraryInstances.get(HashMap.class).size()); - assertEquals("", ArbitraryInstances.get(Appendable.class).toString()); - assertEquals("", ArbitraryInstances.get(StringBuilder.class).toString()); - assertEquals("", ArbitraryInstances.get(StringBuffer.class).toString()); - assertFreshInstanceReturned( - ArrayList.class, HashMap.class, - Appendable.class, StringBuilder.class, StringBuffer.class, - Throwable.class, Exception.class); - } - - public void testGet_io() throws IOException { - assertEquals(-1, ArbitraryInstances.get(InputStream.class).read()); - assertEquals(-1, ArbitraryInstances.get(ByteArrayInputStream.class).read()); - assertEquals(-1, ArbitraryInstances.get(Readable.class).read(CharBuffer.allocate(1))); - assertEquals(-1, ArbitraryInstances.get(Reader.class).read()); - assertEquals(-1, ArbitraryInstances.get(StringReader.class).read()); - assertEquals(0, ArbitraryInstances.get(Buffer.class).capacity()); - assertEquals(0, ArbitraryInstances.get(CharBuffer.class).capacity()); - assertEquals(0, ArbitraryInstances.get(ByteBuffer.class).capacity()); - assertEquals(0, ArbitraryInstances.get(ShortBuffer.class).capacity()); - assertEquals(0, ArbitraryInstances.get(IntBuffer.class).capacity()); - assertEquals(0, ArbitraryInstances.get(LongBuffer.class).capacity()); - assertEquals(0, ArbitraryInstances.get(FloatBuffer.class).capacity()); - assertEquals(0, ArbitraryInstances.get(DoubleBuffer.class).capacity()); - ArbitraryInstances.get(PrintStream.class).println("test"); - ArbitraryInstances.get(PrintWriter.class).println("test"); - assertNotNull(ArbitraryInstances.get(File.class)); - assertFreshInstanceReturned( - ByteArrayOutputStream.class, OutputStream.class, - Writer.class, StringWriter.class, - PrintStream.class, PrintWriter.class); - } - - public void testGet_reflect() { - assertNotNull(ArbitraryInstances.get(Type.class)); - assertNotNull(ArbitraryInstances.get(AnnotatedElement.class)); - assertNotNull(ArbitraryInstances.get(GenericDeclaration.class)); - } - - public void testGet_regex() { - assertEquals(Pattern.compile("").pattern(), ArbitraryInstances.get(Pattern.class).pattern()); - assertEquals(0, ArbitraryInstances.get(MatchResult.class).groupCount()); - } - - private static void assertFreshInstanceReturned(Class<?>... mutableClasses) { - for (Class<?> mutableClass : mutableClasses) { - Object instance = ArbitraryInstances.get(mutableClass); - assertNotNull("Expected to return non-null for: " + mutableClass, instance); - assertNotSame("Expected to return fresh instance for: " + mutableClass, - instance, ArbitraryInstances.get(mutableClass)); - } - } - - private enum EmptyEnum {} - - private enum Direction { - UP, DOWN - } - - public interface SomeInterface {} - - public static abstract class SomeAbstractClass { - public SomeAbstractClass() {} - } - - static class NonPublicClass { - public NonPublicClass() {} - } - - private static class WithPrivateConstructor {} - - public static class NoDefaultConstructor { - public NoDefaultConstructor(@SuppressWarnings("unused") int i) {} - } - - public static class WithExceptionalConstructor { - public WithExceptionalConstructor() { - throw new RuntimeException(); - } - } -} diff --git a/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java b/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java deleted file mode 100644 index 8c55790..0000000 --- a/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java +++ /dev/null @@ -1,1164 +0,0 @@ -/* - * 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.testing; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.truth0.Truth.ASSERT; - -import com.google.common.base.Functions; -import com.google.common.collect.ImmutableList; -import com.google.common.testing.ClassSanityTester.FactoryMethodReturnsNullException; -import com.google.common.testing.ClassSanityTester.ParameterNotInstantiableException; -import com.google.common.testing.NullPointerTester.Visibility; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; -import java.util.AbstractList; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import javax.annotation.Nullable; - -/** - * Unit tests for {@link ClassSanityTester}. - * - * @author Ben Yu - */ -public class ClassSanityTesterTest extends TestCase { - - private final ClassSanityTester tester = new ClassSanityTester(); - - public void testEqualsOnReturnValues_good() throws Exception { - tester.forAllPublicStaticMethods(GoodEqualsFactory.class).testEquals(); - } - - public static class GoodEqualsFactory { - public static Object good(String a, int b, - // oneConstantOnly doesn't matter since it's not nullable and can be only 1 value. - @SuppressWarnings("unused") OneConstantEnum oneConstantOnly, - // noConstant doesn't matter since it can only be null - @SuppressWarnings("unused") @Nullable NoConstantEnum noConstant) { - return new GoodEquals(a, b); - } - // instance method ignored - public Object badIgnored() { - return new BadEquals(); - } - // primitive ignored - public int returnsInt() { - throw new UnsupportedOperationException(); - } - // void ignored - public void voidMethod() { - throw new UnsupportedOperationException(); - } - // non-public method ignored - static Object badButNotPublic() { - return new BadEquals(); - } - } - - public void testForAllPublicStaticMethods_noPublicStaticMethods() throws Exception { - try { - tester.forAllPublicStaticMethods(NoPublicStaticMethods.class).testEquals(); - } catch (AssertionFailedError expected) { - assertEquals( - "No public static methods that return java.lang.Object or subtype are found in " - + NoPublicStaticMethods.class + ".", - expected.getMessage()); - return; - } - fail(); - } - - public void testEqualsOnReturnValues_bad() throws Exception { - try { - tester.forAllPublicStaticMethods(BadEqualsFactory.class).testEquals(); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - private static class BadEqualsFactory { - /** oneConstantOnly matters now since it can be either null or the constant. */ - @SuppressWarnings("unused") // Called by reflection - public static Object bad(String a, int b, - @Nullable OneConstantEnum oneConstantOnly) { - return new GoodEquals(a, b); - } - } - - public void testNullsOnReturnValues_good() throws Exception { - tester.forAllPublicStaticMethods(GoodNullsFactory.class).testNulls(); - } - - private static class GoodNullsFactory { - @SuppressWarnings("unused") // Called by reflection - public static Object good(String s) { - return new GoodNulls(s); - } - } - - public void testNullsOnReturnValues_bad() throws Exception { - try { - tester - .forAllPublicStaticMethods(BadNullsFactory.class) - .thatReturn(Object.class) - .testNulls(); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - public void testNullsOnReturnValues_returnTypeFiltered() throws Exception { - try { - tester - .forAllPublicStaticMethods(BadNullsFactory.class) - .thatReturn(Iterable.class) - .testNulls(); - } catch (AssertionFailedError expected) { - assertEquals( - "No public static methods that return java.lang.Iterable or subtype are found in " - + BadNullsFactory.class + ".", - expected.getMessage()); - return; - } - fail(); - } - - public static class BadNullsFactory { - public static Object bad(@SuppressWarnings("unused") String a) { - return new BadNulls(); - } - } - - public void testSerializableOnReturnValues_good() throws Exception { - tester.forAllPublicStaticMethods(GoodSerializableFactory.class).testSerializable(); - } - - public static class GoodSerializableFactory { - public static Object good(Runnable r) { - return r; - } - public static Object good(AnInterface i) { - return i; - } - } - - public void testSerializableOnReturnValues_bad() throws Exception { - try { - tester.forAllPublicStaticMethods(BadSerializableFactory.class).testSerializable(); - } catch (AssertionError expected) { - return; - } - fail(); - } - - public static class BadSerializableFactory { - public static Object bad() { - return new Serializable() { - @SuppressWarnings("unused") - private final Object notSerializable = new Object(); - }; - } - } - - public void testEqualsAndSerializableOnReturnValues_equalsIsGoodButNotSerializable() - throws Exception { - try { - tester.forAllPublicStaticMethods(GoodEqualsFactory.class).testEqualsAndSerializable(); - } catch (AssertionError expected) { - return; - } - fail("should have failed"); - } - - public void testEqualsAndSerializableOnReturnValues_serializableButNotEquals() - throws Exception { - try { - tester.forAllPublicStaticMethods(GoodSerializableFactory.class).testEqualsAndSerializable(); - } catch (AssertionFailedError expected) { - return; - } - fail("should have failed"); - } - - public void testEqualsAndSerializableOnReturnValues_good() - throws Exception { - tester.forAllPublicStaticMethods(GoodEqualsAndSerialiableFactory.class) - .testEqualsAndSerializable(); - } - - public static class GoodEqualsAndSerialiableFactory { - public static Object good(AnInterface s) { - return Functions.constant(s); - } - } - - public void testEqualsForReturnValues_factoryReturnsNullButNotAnnotated() throws Exception { - try { - tester.forAllPublicStaticMethods(FactoryThatReturnsNullButNotAnnotated.class) - .testEquals(); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - public void testNullsForReturnValues_factoryReturnsNullButNotAnnotated() throws Exception { - try { - tester.forAllPublicStaticMethods(FactoryThatReturnsNullButNotAnnotated.class) - .testNulls(); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - public void testSerializableForReturnValues_factoryReturnsNullButNotAnnotated() throws Exception { - try { - tester.forAllPublicStaticMethods(FactoryThatReturnsNullButNotAnnotated.class) - .testSerializable(); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - public void testEqualsAndSerializableForReturnValues_factoryReturnsNullButNotAnnotated() - throws Exception { - try { - tester.forAllPublicStaticMethods(FactoryThatReturnsNullButNotAnnotated.class) - .testEqualsAndSerializable(); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - public static class FactoryThatReturnsNullButNotAnnotated { - public static Object bad() { - return null; - } - } - - public void testEqualsForReturnValues_factoryReturnsNullAndAnnotated() throws Exception { - tester.forAllPublicStaticMethods(FactoryThatReturnsNullAndAnnotated.class) - .testEquals(); - } - - public void testNullsForReturnValues_factoryReturnsNullAndAnnotated() throws Exception { - tester.forAllPublicStaticMethods(FactoryThatReturnsNullAndAnnotated.class) - .testNulls(); - } - - public void testSerializableForReturnValues_factoryReturnsNullAndAnnotated() throws Exception { - tester.forAllPublicStaticMethods(FactoryThatReturnsNullAndAnnotated.class) - .testSerializable(); - } - - public void testEqualsAndSerializableForReturnValues_factoryReturnsNullAndAnnotated() - throws Exception { - tester.forAllPublicStaticMethods(FactoryThatReturnsNullAndAnnotated.class) - .testEqualsAndSerializable(); - } - - public static class FactoryThatReturnsNullAndAnnotated { - @Nullable public static Object bad() { - return null; - } - } - - public void testGoodEquals() throws Exception { - tester.testEquals(GoodEquals.class); - } - - public void testEquals_interface() { - tester.testEquals(AnInterface.class); - } - - public void testEquals_abstractClass() { - tester.testEquals(AnAbstractClass.class); - } - - public void testEquals_enum() { - tester.testEquals(OneConstantEnum.class); - } - - public void testBadEquals() throws Exception { - try { - tester.testEquals(BadEquals.class); - } catch (AssertionFailedError expected) { - ASSERT.that(expected.getMessage()).contains("create(null)"); - return; - } - fail("should have failed"); - } - - public void testBadEquals_withParameterizedType() throws Exception { - try { - tester.testEquals(BadEqualsWithParameterizedType.class); - } catch (AssertionFailedError expected) { - ASSERT.that(expected.getMessage()).contains("create([[1]])"); - return; - } - fail("should have failed"); - } - - public void testGoodReferentialEqualityComparison() throws Exception { - tester.testEquals(UsesEnum.class); - tester.testEquals(UsesReferentialEquality.class); - tester.testEquals(SameListInstance.class); - } - - public void testEqualsUsingReferentialEquality() throws Exception { - assertBadUseOfReferentialEquality(SameIntegerInstance.class); - assertBadUseOfReferentialEquality(SameLongInstance.class); - assertBadUseOfReferentialEquality(SameFloatInstance.class); - assertBadUseOfReferentialEquality(SameDoubleInstance.class); - assertBadUseOfReferentialEquality(SameShortInstance.class); - assertBadUseOfReferentialEquality(SameByteInstance.class); - assertBadUseOfReferentialEquality(SameCharacterInstance.class); - assertBadUseOfReferentialEquality(SameBooleanInstance.class); - assertBadUseOfReferentialEquality(SameObjectInstance.class); - assertBadUseOfReferentialEquality(SameStringInstance.class); - assertBadUseOfReferentialEquality(SameInterfaceInstance.class); - } - - private void assertBadUseOfReferentialEquality(Class<?> cls) throws Exception { - try { - tester.testEquals(cls); - } catch (AssertionFailedError expected) { - ASSERT.that(expected.getMessage()).contains(cls.getSimpleName() + "("); - return; - } - fail("should have failed"); - } - - public void testParameterNotInstantiableForEqualsTest() throws Exception { - try { - tester.doTestEquals(ConstructorParameterNotInstantiable.class); - fail("should have failed"); - } catch (ParameterNotInstantiableException expected) {} - } - - public void testConstructorThrowsForEqualsTest() throws Exception { - try { - tester.doTestEquals(ConstructorThrows.class); - fail("should have failed"); - } catch (InvocationTargetException expected) {} - } - - public void testFactoryMethodReturnsNullForEqualsTest() throws Exception { - try { - tester.doTestEquals(FactoryMethodReturnsNullAndAnnotated.class); - fail("should have failed"); - } catch (FactoryMethodReturnsNullException expected) {} - } - - public void testFactoryMethodReturnsNullButNotAnnotatedInEqualsTest() throws Exception { - try { - tester.testEquals(FactoryMethodReturnsNullButNotAnnotated.class); - } catch (AssertionFailedError expected) { - return; - } - fail("should have failed"); - } - - public void testNoEqualsChecksOnEnum() throws Exception { - tester.testEquals(OneConstantEnum.class); - tester.testEquals(NoConstantEnum.class); - tester.testEquals(TimeUnit.class); - } - - public void testNoEqualsChecksOnInterface() throws Exception { - tester.testEquals(Runnable.class); - } - - public void testNoEqualsChecksOnAnnotation() throws Exception { - tester.testEquals(Nullable.class); - } - - public void testGoodNulls() throws Exception { - tester.testNulls(GoodNulls.class); - } - - public void testNoNullCheckNeededDespitNotInstantiable() throws Exception { - tester.doTestNulls(NoNullCheckNeededDespitNotInstantiable.class, Visibility.PACKAGE); - } - - public void testNulls_interface() { - tester.testNulls(AnInterface.class); - } - - public void testNulls_abstractClass() { - tester.testNulls(AnAbstractClass.class); - } - - public void testNulls_enum() throws Exception { - tester.testNulls(OneConstantEnum.class); - tester.testNulls(NoConstantEnum.class); - tester.testNulls(TimeUnit.class); - } - - public void testEnumFailsToCheckNull() throws Exception { - try { - tester.testNulls(EnumFailsToCheckNull.class); - } catch (AssertionFailedError expected) { - return; - } - fail("should have failed"); - } - - public void testNoNullChecksOnInterface() throws Exception { - tester.testNulls(Runnable.class); - } - - public void testNoNullChecksOnAnnotation() throws Exception { - tester.testNulls(Nullable.class); - } - - public void testBadNulls() throws Exception { - try { - tester.testNulls(BadNulls.class); - } catch (AssertionFailedError expected) { - return; - } - fail("should have failed"); - } - - public void testInstantiate_factoryMethodReturnsNullButNotAnnotated() throws Exception { - try { - tester.instantiate(FactoryMethodReturnsNullButNotAnnotated.class); - } catch (AssertionFailedError expected) { - ASSERT.that(expected.getMessage()).contains("@Nullable"); - return; - } - fail("should have failed"); - } - - public void testInstantiate_factoryMethodReturnsNullAndAnnotated() throws Exception { - try { - tester.instantiate(FactoryMethodReturnsNullAndAnnotated.class); - fail("should have failed"); - } catch (FactoryMethodReturnsNullException expected) {} - } - - public void testInstantiate_factoryMethodAcceptsNull() throws Exception { - assertNull(tester.instantiate(FactoryMethodAcceptsNull.class).name); - } - - public void testInstantiate_factoryMethodDoesNotAcceptNull() throws Exception { - assertNotNull(tester.instantiate(FactoryMethodDoesNotAcceptNull.class).name); - } - - public void testInstantiate_constructorAcceptsNull() throws Exception { - assertNull(tester.instantiate(ConstructorAcceptsNull.class).name); - } - - public void testInstantiate_constructorDoesNotAcceptNull() throws Exception { - assertNotNull(tester.instantiate(ConstructorDoesNotAcceptNull.class).name); - } - - public void testInstantiate_notInstantiable() throws Exception { - assertNull(tester.instantiate(NotInstantiable.class)); - } - - public void testInstantiate_noConstantEnum() throws Exception { - assertNull(tester.instantiate(NoConstantEnum.class)); - } - - public void testInstantiate_oneConstantEnum() throws Exception { - assertEquals(OneConstantEnum.A, tester.instantiate(OneConstantEnum.class)); - } - - public void testInstantiate_interface() throws Exception { - assertNull(tester.instantiate(Runnable.class)); - } - - public void testInstantiate_abstractClass() throws Exception { - assertNull(tester.instantiate(AbstractList.class)); - } - - public void testInstantiate_annotation() throws Exception { - assertNull(tester.instantiate(Nullable.class)); - } - - public void testInstantiate_setDefault() throws Exception { - NotInstantiable x = new NotInstantiable(); - tester.setDefault(NotInstantiable.class, x); - assertNotNull(tester.instantiate(ConstructorParameterNotInstantiable.class)); - } - - public void testInstantiate_setSampleInstances() throws Exception { - NotInstantiable x = new NotInstantiable(); - tester.setSampleInstances(NotInstantiable.class, ImmutableList.of(x)); - assertNotNull(tester.instantiate(ConstructorParameterNotInstantiable.class)); - } - - public void testInstantiate_setSampleInstances_empty() throws Exception { - tester.setSampleInstances(NotInstantiable.class, ImmutableList.<NotInstantiable>of()); - try { - tester.instantiate(ConstructorParameterNotInstantiable.class); - fail(); - } catch (ParameterNotInstantiableException expected) {} - } - - public void testInstantiate_constructorThrows() throws Exception { - try { - tester.instantiate(ConstructorThrows.class); - fail(); - } catch (InvocationTargetException expected) {} - } - - public void testInstantiate_factoryMethodThrows() throws Exception { - try { - tester.instantiate(FactoryMethodThrows.class); - fail(); - } catch (InvocationTargetException expected) {} - } - - public void testInstantiate_constructorParameterNotInstantiable() throws Exception { - try { - tester.instantiate(ConstructorParameterNotInstantiable.class); - fail(); - } catch (ParameterNotInstantiableException expected) {} - } - - public void testInstantiate_factoryMethodParameterNotInstantiable() throws Exception { - try { - tester.instantiate(FactoryMethodParameterNotInstantiable.class); - fail(); - } catch (ParameterNotInstantiableException expected) {} - } - - public void testInstantiate_instantiableFactoryMethodChosen() throws Exception { - assertEquals("good", tester.instantiate(InstantiableFactoryMethodChosen.class).name); - } - - public void testInterfaceProxySerializable() throws Exception { - SerializableTester.reserializeAndAssert(tester.instantiate(HasAnInterface.class)); - } - - public void testReturnValuesFromAnotherPackageIgnoredForNullTests() throws Exception { - new ClassSanityTester().forAllPublicStaticMethods(JdkObjectFactory.class).testNulls(); - } - - /** String doesn't check nulls as we expect. But the framework should ignore. */ - private static class JdkObjectFactory { - @SuppressWarnings("unused") // Called by reflection - public static Object create() { - return new ArrayList<String>(); - } - } - - static class HasAnInterface implements Serializable { - private final AnInterface i; - - public HasAnInterface(AnInterface i) { - this.i = i; - } - - @Override public boolean equals(@Nullable Object obj) { - if (obj instanceof HasAnInterface) { - HasAnInterface that = (HasAnInterface) obj; - return i.equals(that.i); - } else { - return false; - } - } - - @Override public int hashCode() { - return i.hashCode(); - } - } - - static class InstantiableFactoryMethodChosen { - final String name; - - private InstantiableFactoryMethodChosen(String name) { - this.name = name; - } - - public InstantiableFactoryMethodChosen(NotInstantiable x) { - checkNotNull(x); - this.name = "x1"; - } - - public static InstantiableFactoryMethodChosen create(NotInstantiable x) { - return new InstantiableFactoryMethodChosen(x); - } - - public static InstantiableFactoryMethodChosen create(String s) { - checkNotNull(s); - return new InstantiableFactoryMethodChosen("good"); - } - } - - public void testInstantiate_instantiableConstructorChosen() throws Exception { - assertEquals("good", tester.instantiate(InstantiableConstructorChosen.class).name); - } - - static class InstantiableConstructorChosen { - final String name; - - public InstantiableConstructorChosen(String name) { - checkNotNull(name); - this.name = "good"; - } - - public InstantiableConstructorChosen(NotInstantiable x) { - checkNotNull(x); - this.name = "x1"; - } - - public static InstantiableFactoryMethodChosen create(NotInstantiable x) { - return new InstantiableFactoryMethodChosen(x); - } - } - - static class GoodEquals { - - private final String a; - private final int b; - - private GoodEquals(String a, int b) { - this.a = checkNotNull(a); - this.b = b; - } - - // ignored by testEquals() - GoodEquals(@SuppressWarnings("unused") NotInstantiable x) { - this.a = "x"; - this.b = -1; - } - - // will keep trying - public GoodEquals(@SuppressWarnings("unused") NotInstantiable x, int b) { - this.a = "x"; - this.b = b; - } - - // keep trying - @SuppressWarnings("unused") - static GoodEquals create(int a, int b) { - throw new RuntimeException(); - } - - // keep trying - @SuppressWarnings("unused") - @Nullable public static GoodEquals createMayReturnNull(int a, int b) { - return null; - } - - // Good! - static GoodEquals create(String a, int b) { - return new GoodEquals(a, b); - } - - @Override public boolean equals(@Nullable Object obj) { - if (obj instanceof GoodEquals) { - GoodEquals that = (GoodEquals) obj; - return a.equals(that.a) && b == that.b; - } else { - return false; - } - } - - @Override public int hashCode() { - return 0; - } - } - - static class BadEquals { - - public BadEquals() {} // ignored by testEquals() since it has less parameters. - - public static BadEquals create(@SuppressWarnings("unused") @Nullable String s) { - return new BadEquals(); - } - - @Override public boolean equals(@Nullable Object obj) { - return obj instanceof BadEquals; - } - - @Override public int hashCode() { - return 0; - } - } - - static class SameIntegerInstance { - private final Integer i; - - public SameIntegerInstance(Integer i) { - this.i = checkNotNull(i); - } - - @Override public int hashCode() { - return i.hashCode(); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof SameIntegerInstance) { - SameIntegerInstance that = (SameIntegerInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameLongInstance { - private final Long i; - - public SameLongInstance(Long i) { - this.i = checkNotNull(i); - } - - @Override public int hashCode() { - return i.hashCode(); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof SameLongInstance) { - SameLongInstance that = (SameLongInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameFloatInstance { - private final Float i; - - public SameFloatInstance(Float i) { - this.i = checkNotNull(i); - } - - @Override public int hashCode() { - return i.hashCode(); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof SameFloatInstance) { - SameFloatInstance that = (SameFloatInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameDoubleInstance { - private final Double i; - - public SameDoubleInstance(Double i) { - this.i = checkNotNull(i); - } - - @Override public int hashCode() { - return i.hashCode(); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof SameDoubleInstance) { - SameDoubleInstance that = (SameDoubleInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameShortInstance { - private final Short i; - - public SameShortInstance(Short i) { - this.i = checkNotNull(i); - } - - @Override public int hashCode() { - return i.hashCode(); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof SameShortInstance) { - SameShortInstance that = (SameShortInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameByteInstance { - private final Byte i; - - public SameByteInstance(Byte i) { - this.i = checkNotNull(i); - } - - @Override public int hashCode() { - return i.hashCode(); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof SameByteInstance) { - SameByteInstance that = (SameByteInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameCharacterInstance { - private final Character i; - - public SameCharacterInstance(Character i) { - this.i = checkNotNull(i); - } - - @Override public int hashCode() { - return i.hashCode(); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof SameCharacterInstance) { - SameCharacterInstance that = (SameCharacterInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameBooleanInstance { - private final Boolean i; - - public SameBooleanInstance(Boolean i) { - this.i = checkNotNull(i); - } - - @Override public int hashCode() { - return i.hashCode(); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof SameBooleanInstance) { - SameBooleanInstance that = (SameBooleanInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameStringInstance { - private final String s; - - public SameStringInstance(String s) { - this.s = checkNotNull(s); - } - - @Override public int hashCode() { - return s.hashCode(); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof SameStringInstance) { - SameStringInstance that = (SameStringInstance) obj; - return s == that.s; - } - return false; - } - } - - static class SameObjectInstance { - private final Object s; - - public SameObjectInstance(Object s) { - this.s = checkNotNull(s); - } - - @Override public int hashCode() { - return s.hashCode(); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof SameObjectInstance) { - SameObjectInstance that = (SameObjectInstance) obj; - return s == that.s; - } - return false; - } - } - - static class SameInterfaceInstance { - private final Runnable s; - - public SameInterfaceInstance(Runnable s) { - this.s = checkNotNull(s); - } - - @Override public int hashCode() { - return s.hashCode(); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof SameInterfaceInstance) { - SameInterfaceInstance that = (SameInterfaceInstance) obj; - return s == that.s; - } - return false; - } - } - - static class SameListInstance { - private final List<?> s; - - public SameListInstance(List<?> s) { - this.s = checkNotNull(s); - } - - @Override public int hashCode() { - return System.identityHashCode(s); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof SameListInstance) { - SameListInstance that = (SameListInstance) obj; - return s == that.s; - } - return false; - } - } - - static class UsesReferentialEquality { - private final ReferentialEquality s; - - public UsesReferentialEquality(ReferentialEquality s) { - this.s = checkNotNull(s); - } - - @Override public int hashCode() { - return s.hashCode(); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof UsesReferentialEquality) { - UsesReferentialEquality that = (UsesReferentialEquality) obj; - return s == that.s; - } - return false; - } - } - - static class UsesEnum { - private final TimeUnit s; - - public UsesEnum(TimeUnit s) { - this.s = checkNotNull(s); - } - - @Override public int hashCode() { - return s.hashCode(); - } - - @Override public boolean equals(Object obj) { - if (obj instanceof UsesEnum) { - UsesEnum that = (UsesEnum) obj; - return s == that.s; - } - return false; - } - } - - public static class ReferentialEquality { - public ReferentialEquality() {} - } - - static class BadEqualsWithParameterizedType { - - // ignored by testEquals() since it has less parameters. - public BadEqualsWithParameterizedType() {} - - public static BadEqualsWithParameterizedType create( - @SuppressWarnings("unused") ImmutableList<Iterable<? extends String>> s) { - return new BadEqualsWithParameterizedType(); - } - - @Override public boolean equals(@Nullable Object obj) { - return obj instanceof BadEqualsWithParameterizedType; - } - - @Override public int hashCode() { - return 0; - } - } - - static class GoodNulls { - public GoodNulls(String s) { - checkNotNull(s); - } - - public void rejectNull(String s) { - checkNotNull(s); - } - } - - public static class BadNulls { - public void failsToRejectNull(@SuppressWarnings("unused") String s) {} - } - - public static class NoNullCheckNeededDespitNotInstantiable { - - public NoNullCheckNeededDespitNotInstantiable(NotInstantiable x) { - checkNotNull(x); - } - - @SuppressWarnings("unused") // reflected - void primitiveOnly(int i) {} - - @SuppressWarnings("unused") //reflected - void nullableOnly(@Nullable String s) {} - public void noParameter() {} - - @SuppressWarnings("unused") //reflected - void primitiveAndNullable(@Nullable String s, int i) {} - } - - static class FactoryMethodReturnsNullButNotAnnotated { - private FactoryMethodReturnsNullButNotAnnotated() {} - - static FactoryMethodReturnsNullButNotAnnotated returnsNull() { - return null; - } - } - - static class FactoryMethodReturnsNullAndAnnotated { - private FactoryMethodReturnsNullAndAnnotated() {} - - @Nullable public static FactoryMethodReturnsNullAndAnnotated returnsNull() { - return null; - } - } - - static class FactoryMethodAcceptsNull { - - final String name; - - private FactoryMethodAcceptsNull(String name) { - this.name = name; - } - - static FactoryMethodAcceptsNull create(@Nullable String name) { - return new FactoryMethodAcceptsNull(name); - } - } - - static class FactoryMethodDoesNotAcceptNull { - - final String name; - - private FactoryMethodDoesNotAcceptNull(String name) { - this.name = checkNotNull(name); - } - - public static FactoryMethodDoesNotAcceptNull create(String name) { - return new FactoryMethodDoesNotAcceptNull(name); - } - } - - static class ConstructorAcceptsNull { - - final String name; - - public ConstructorAcceptsNull(@Nullable String name) { - this.name = name; - } - } - - static class ConstructorDoesNotAcceptNull { - - final String name; - - ConstructorDoesNotAcceptNull(String name) { - this.name = checkNotNull(name); - } - } - - static class ConstructorParameterNotInstantiable { - public ConstructorParameterNotInstantiable(@SuppressWarnings("unused") NotInstantiable x) {} - } - - static class FactoryMethodParameterNotInstantiable { - - private FactoryMethodParameterNotInstantiable() {} - - static FactoryMethodParameterNotInstantiable create( - @SuppressWarnings("unused") NotInstantiable x) { - return new FactoryMethodParameterNotInstantiable(); - } - } - - static class ConstructorThrows { - public ConstructorThrows() { - throw new RuntimeException(); - } - } - - static class FactoryMethodThrows { - private FactoryMethodThrows() {} - - public static FactoryMethodThrows create() { - throw new RuntimeException(); - } - } - - static class NotInstantiable { - private NotInstantiable() {} - } - - private enum NoConstantEnum {} - - private enum OneConstantEnum { - A - } - - private enum EnumFailsToCheckNull { - A; - - @SuppressWarnings("unused") - public void failToCheckNull(String s) {} - } - - private interface AnInterface {} - - private static abstract class AnAbstractClass { - @SuppressWarnings("unused") - public AnAbstractClass(String s) {} - - @SuppressWarnings("unused") - public void failsToCheckNull(String s) {} - } - - private static class NoPublicStaticMethods { - static String notPublic() { - return ""; - } - } -} diff --git a/guava-testlib/test/com/google/common/testing/EqualsTesterTest.java b/guava-testlib/test/com/google/common/testing/EqualsTesterTest.java deleted file mode 100644 index e2ec18a..0000000 --- a/guava-testlib/test/com/google/common/testing/EqualsTesterTest.java +++ /dev/null @@ -1,438 +0,0 @@ -/* - * Copyright (C) 2007 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.testing; - -import com.google.common.annotations.GwtCompatible; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Sets; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import java.util.Set; - -/** - * Unit tests for {@link EqualsTester}. - * - * @author Jim McMaster - */ -@GwtCompatible -public class EqualsTesterTest extends TestCase { - private ValidTestObject reference; - private EqualsTester equalsTester; - private ValidTestObject equalObject1; - private ValidTestObject equalObject2; - private ValidTestObject notEqualObject1; - private ValidTestObject notEqualObject2; - - @Override - public void setUp() throws Exception { - super.setUp(); - reference = new ValidTestObject(1, 2); - equalsTester = new EqualsTester(); - equalObject1 = new ValidTestObject(1, 2); - equalObject2 = new ValidTestObject(1, 2); - notEqualObject1 = new ValidTestObject(0, 2); - notEqualObject2 = new ValidTestObject(1, 0); - } - - /** - * Test null reference yields error - */ - public void testAddNullReference() { - try { - equalsTester.addEqualityGroup((Object) null); - fail("Should fail on null reference"); - } catch (NullPointerException e) {} - } - - /** - * Test equalObjects after adding multiple instances at once with a null - */ - public void testAddTwoEqualObjectsAtOnceWithNull() { - try { - equalsTester.addEqualityGroup(reference, equalObject1, null); - fail("Should fail on null equal object"); - } catch (NullPointerException e) {} - } - - /** - * Test adding null equal object yields error - */ - public void testAddNullEqualObject() { - try { - equalsTester.addEqualityGroup(reference, (Object[]) null); - fail("Should fail on null equal object"); - } catch (NullPointerException e) {} - } - - /** - * Test adding objects only by addEqualityGroup, with no reference object - * specified in the constructor. - */ - public void testAddEqualObjectWithOArgConstructor() { - equalsTester.addEqualityGroup(equalObject1, notEqualObject1); - try { - equalsTester.testEquals(); - } catch (AssertionFailedError e) { - assertErrorMessage( - e, - equalObject1 + " [group 1, item 1] must be equal to " - + notEqualObject1 + " [group 1, item 2]"); - return; - } - fail("Should get not equal to equal object error"); - } - - /** - * Test EqualsTester with no equals or not equals objects. This checks - * proper handling of null, incompatible class and reflexive tests - */ - public void testTestEqualsEmptyLists() { - equalsTester.addEqualityGroup(reference); - equalsTester.testEquals(); - } - - /** - * Test EqualsTester after populating equalObjects. This checks proper - * handling of equality and verifies hashCode for valid objects - */ - public void testTestEqualsEqualsObjects() { - equalsTester.addEqualityGroup(reference, equalObject1, equalObject2); - equalsTester.testEquals(); - } - - /** - * Test proper handling of case where an object is not equal to itself - */ - public void testNonreflexiveEquals() { - Object obj = new NonReflexiveObject(); - equalsTester.addEqualityGroup(obj); - try { - equalsTester.testEquals(); - } catch (AssertionFailedError e) { - assertErrorMessage( - e, obj + " must be equal to itself"); - return; - } - fail("Should get non-reflexive error"); - } - - /** - * Test proper handling where an object tests equal to null - */ - public void testInvalidEqualsNull() { - Object obj = new InvalidEqualsNullObject(); - equalsTester.addEqualityGroup(obj); - try { - equalsTester.testEquals(); - } catch (AssertionFailedError e) { - assertErrorMessage( - e, obj + " must be unequal to null"); - return; - } - fail("Should get equal to null error"); - } - - /** - * Test proper handling where an object incorrectly tests for an - * incompatible class - */ - public void testInvalidEqualsIncompatibleClass() { - Object obj = new InvalidEqualsIncompatibleClassObject(); - equalsTester.addEqualityGroup(obj); - try { - equalsTester.testEquals(); - } catch (AssertionFailedError e) { - assertErrorMessage( - e, - obj - + " must be unequal to an arbitrary object of another class"); - return; - } - fail("Should get equal to incompatible class error"); - } - - /** - * Test proper handling where an object is not equal to one the user has - * said should be equal - */ - public void testInvalidNotEqualsEqualObject() { - equalsTester.addEqualityGroup(reference, notEqualObject1); - try { - equalsTester.testEquals(); - } catch (AssertionFailedError e) { - assertErrorMessage(e, reference.toString() + " [group 1, item 1]"); - assertErrorMessage(e, notEqualObject1.toString() + " [group 1, item 2]"); - return; - } - fail("Should get not equal to equal object error"); - } - - /** - * Test for an invalid hashCode method, i.e., one that returns different - * value for objects that are equal according to the equals method - */ - public void testInvalidHashCode() { - Object a = new InvalidHashCodeObject(1, 2); - Object b = new InvalidHashCodeObject(1, 2); - equalsTester.addEqualityGroup(a, b); - try { - equalsTester.testEquals(); - } catch (AssertionFailedError e) { - assertErrorMessage( - e, "the hash (" + a.hashCode() + ") of " + a - + " [group 1, item 1] must be equal to the hash (" + b.hashCode() + ") of " + b); - return; - } - fail("Should get invalid hashCode error"); - } - - public void testNullEqualityGroup() { - EqualsTester tester = new EqualsTester(); - try { - tester.addEqualityGroup((Object[]) null); - fail(); - } catch (NullPointerException e) {} - } - - public void testNullObjectInEqualityGroup() { - EqualsTester tester = new EqualsTester(); - try { - tester.addEqualityGroup(1, null, 3); - fail(); - } catch (NullPointerException e) { - assertErrorMessage(e, "at index 1"); - } - } - - public void testSymmetryBroken() { - EqualsTester tester = new EqualsTester() - .addEqualityGroup(named("foo").addPeers("bar"), named("bar")); - try { - tester.testEquals(); - } catch (AssertionFailedError e) { - assertErrorMessage( - e, - "bar [group 1, item 2] must be equal to foo [group 1, item 1]"); - return; - } - fail("should failed because symmetry is broken"); - } - - public void testTransitivityBrokenInEqualityGroup() { - EqualsTester tester = new EqualsTester() - .addEqualityGroup( - named("foo").addPeers("bar", "baz"), - named("bar").addPeers("foo"), - named("baz").addPeers("foo")); - try { - tester.testEquals(); - } catch (AssertionFailedError e) { - assertErrorMessage( - e, - "bar [group 1, item 2] must be equal to baz [group 1, item 3]"); - return; - } - fail("should failed because transitivity is broken"); - } - - public void testUnequalObjectsInEqualityGroup() { - EqualsTester tester = new EqualsTester() - .addEqualityGroup(named("foo"), named("bar")); - try { - tester.testEquals(); - } catch (AssertionFailedError e) { - assertErrorMessage( - e, - "foo [group 1, item 1] must be equal to bar [group 1, item 2]"); - return; - } - fail("should failed because of unequal objects in the same equality group"); - } - - public void testTransitivityBrokenAcrossEqualityGroups() { - EqualsTester tester = new EqualsTester() - .addEqualityGroup( - named("foo").addPeers("bar"), - named("bar").addPeers("foo", "x")) - .addEqualityGroup( - named("baz").addPeers("x"), - named("x").addPeers("baz", "bar")); - try { - tester.testEquals(); - } catch (AssertionFailedError e) { - assertErrorMessage( - e, - "bar [group 1, item 2] must be unequal to x [group 2, item 2]"); - return; - } - fail("should failed because transitivity is broken"); - } - - public void testEqualityGroups() { - new EqualsTester() - .addEqualityGroup( - named("foo").addPeers("bar"), named("bar").addPeers("foo")) - .addEqualityGroup(named("baz"), named("baz")) - .testEquals(); - } - - private static void assertErrorMessage(Throwable e, String message) { - // TODO(kevinb): use a Truth assertion here - if (!e.getMessage().contains(message)) { - fail("expected <" + e.getMessage() + "> to contain <" + message + ">"); - } - } - - /** - * Test class with valid equals and hashCode methods. Testers created - * with instances of this class should always pass. - */ - private static class ValidTestObject { - private int aspect1; - private int aspect2; - - ValidTestObject(int aspect1, int aspect2) { - this.aspect1 = aspect1; - this.aspect2 = aspect2; - } - - @Override public boolean equals(Object o) { - if (!(o instanceof ValidTestObject)) { - return false; - } - ValidTestObject other = (ValidTestObject) o; - if (aspect1 != other.aspect1) { - return false; - } - if (aspect2 != other.aspect2) { - return false; - } - return true; - } - - @Override public int hashCode() { - int result = 17; - result = 37 * result + aspect1; - result = 37 * result + aspect2; - return result; - } - } - - /** Test class with invalid hashCode method. */ - private static class InvalidHashCodeObject { - private int aspect1; - private int aspect2; - - InvalidHashCodeObject(int aspect1, int aspect2) { - this.aspect1 = aspect1; - this.aspect2 = aspect2; - } - - @Override public boolean equals(Object o) { - if (!(o instanceof InvalidHashCodeObject)) { - return false; - } - InvalidHashCodeObject other = (InvalidHashCodeObject) o; - if (aspect1 != other.aspect1) { - return false; - } - if (aspect2 != other.aspect2) { - return false; - } - return true; - } - } - - /** Test class that violates reflexitivity. It is not equal to itself */ - private static class NonReflexiveObject{ - - @Override public boolean equals(Object o) { - return false; - } - - @Override public int hashCode() { - return super.hashCode(); - } - } - - /** Test class that returns true if the test object is null */ - private static class InvalidEqualsNullObject{ - - @Override public boolean equals(Object o) { - return o == this || o == null; - } - - @Override public int hashCode() { - return 0; - } - } - - /** - * Test class that returns true even if the test object is of the wrong class - */ - private static class InvalidEqualsIncompatibleClassObject{ - - @Override public boolean equals(Object o) { - if (o == null) { - return false; - } - return true; - } - - @Override public int hashCode() { - return 0; - } - } - - private static NamedObject named(String name) { - return new NamedObject(name); - } - - private static class NamedObject { - private final Set<String> peerNames = Sets.newHashSet(); - - private final String name; - - NamedObject(String name) { - this.name = Preconditions.checkNotNull(name); - } - - NamedObject addPeers(String... names) { - peerNames.addAll(ImmutableList.copyOf(names)); - return this; - } - - @Override public boolean equals(Object obj) { - if (obj instanceof NamedObject) { - NamedObject that = (NamedObject) obj; - return name.equals(that.name) || peerNames.contains(that.name); - } - return false; - } - - @Override public int hashCode() { - return 0; - } - - @Override public String toString() { - return name; - } - } -} diff --git a/guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java b/guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java deleted file mode 100644 index 14ce0e8..0000000 --- a/guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (C) 2011 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.testing; - -import static com.google.common.base.Preconditions.checkState; -import static org.truth0.Truth.ASSERT; - -import com.google.common.annotations.GwtCompatible; -import com.google.common.base.Equivalence; -import com.google.common.base.Objects; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableTable; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * Tests for {@link EquivalenceTester}. - * - * @author Gregory Kick - */ -@GwtCompatible -public class EquivalenceTesterTest extends TestCase { - private EquivalenceTester<Object> tester; - private MockEquivalence equivalenceMock; - - @Override public void setUp() throws Exception { - super.setUp(); - this.equivalenceMock = new MockEquivalence(); - this.tester = EquivalenceTester.of(equivalenceMock); - } - - /** Test null reference yields error */ - public void testOf_NullPointerException() { - try { - EquivalenceTester.of(null); - fail("Should fail on null reference"); - } catch (NullPointerException expected) {} - } - - public void testTest_NoData() { - tester.test(); - } - - public void testTest() { - Object group1Item1 = new TestObject(1, 1); - Object group1Item2 = new TestObject(1, 2); - Object group2Item1 = new TestObject(2, 1); - Object group2Item2 = new TestObject(2, 2); - - equivalenceMock.expectEquivalent(group1Item1, group1Item2); - equivalenceMock.expectDistinct(group1Item1, group2Item1); - equivalenceMock.expectDistinct(group1Item1, group2Item2); - equivalenceMock.expectEquivalent(group1Item2, group1Item1); - equivalenceMock.expectDistinct(group1Item2, group2Item1); - equivalenceMock.expectDistinct(group1Item2, group2Item2); - equivalenceMock.expectDistinct(group2Item1, group1Item1); - equivalenceMock.expectDistinct(group2Item1, group1Item2); - equivalenceMock.expectEquivalent(group2Item1, group2Item2); - equivalenceMock.expectDistinct(group2Item2, group1Item1); - equivalenceMock.expectDistinct(group2Item2, group1Item2); - equivalenceMock.expectEquivalent(group2Item2, group2Item1); - - equivalenceMock.expectHash(group1Item1, 1); - equivalenceMock.expectHash(group1Item2, 1); - equivalenceMock.expectHash(group2Item1, 2); - equivalenceMock.expectHash(group2Item2, 2); - - equivalenceMock.replay(); - - tester.addEquivalenceGroup(group1Item1, group1Item2) - .addEquivalenceGroup(group2Item1, group2Item2) - .test(); - } - - public void testTest_symmetric() { - Object group1Item1 = new TestObject(1, 1); - Object group1Item2 = new TestObject(1, 2); - - equivalenceMock.expectEquivalent(group1Item1, group1Item2); - equivalenceMock.expectDistinct(group1Item2, group1Item1); - - equivalenceMock.expectHash(group1Item1, 1); - equivalenceMock.expectHash(group1Item2, 1); - - equivalenceMock.replay(); - - try { - tester.addEquivalenceGroup(group1Item1, group1Item2).test(); - } catch (AssertionFailedError expected) { - ASSERT.that(expected.getMessage()).contains( - "TestObject{group=1, item=2} [group 1, item 2] must be equivalent to " - + "TestObject{group=1, item=1} [group 1, item 1]"); - return; - } - fail(); - } - - public void testTest_trasitive() { - Object group1Item1 = new TestObject(1, 1); - Object group1Item2 = new TestObject(1, 2); - Object group1Item3 = new TestObject(1, 3); - - equivalenceMock.expectEquivalent(group1Item1, group1Item2); - equivalenceMock.expectEquivalent(group1Item1, group1Item3); - equivalenceMock.expectEquivalent(group1Item2, group1Item1); - equivalenceMock.expectDistinct(group1Item2, group1Item3); - equivalenceMock.expectEquivalent(group1Item3, group1Item1); - equivalenceMock.expectEquivalent(group1Item3, group1Item2); - - equivalenceMock.expectHash(group1Item1, 1); - equivalenceMock.expectHash(group1Item2, 1); - equivalenceMock.expectHash(group1Item3, 1); - - equivalenceMock.replay(); - - try { - tester.addEquivalenceGroup(group1Item1, group1Item2, group1Item3).test(); - } catch (AssertionFailedError expected) { - ASSERT.that(expected.getMessage()).contains( - "TestObject{group=1, item=2} [group 1, item 2] must be equivalent to " - + "TestObject{group=1, item=3} [group 1, item 3]"); - return; - } - fail(); - } - - public void testTest_inequivalence() { - Object group1Item1 = new TestObject(1, 1); - Object group2Item1 = new TestObject(2, 1); - - equivalenceMock.expectEquivalent(group1Item1, group2Item1); - equivalenceMock.expectDistinct(group2Item1, group1Item1); - - equivalenceMock.expectHash(group1Item1, 1); - equivalenceMock.expectHash(group2Item1, 2); - - equivalenceMock.replay(); - - try { - tester.addEquivalenceGroup(group1Item1).addEquivalenceGroup(group2Item1).test(); - } catch (AssertionFailedError expected) { - ASSERT.that(expected.getMessage()).contains( - "TestObject{group=1, item=1} [group 1, item 1] must be inequivalent to " - + "TestObject{group=2, item=1} [group 2, item 1]"); - return; - } - fail(); - } - - public void testTest_hash() { - Object group1Item1 = new TestObject(1, 1); - Object group1Item2 = new TestObject(1, 2); - - equivalenceMock.expectEquivalent(group1Item1, group1Item2); - equivalenceMock.expectEquivalent(group1Item2, group1Item1); - - equivalenceMock.expectHash(group1Item1, 1); - equivalenceMock.expectHash(group1Item2, 2); - - equivalenceMock.replay(); - - try { - tester.addEquivalenceGroup(group1Item1, group1Item2).test(); - } catch (AssertionFailedError expected) { - String expectedMessage = - "the hash (1) of TestObject{group=1, item=1} [group 1, item 1] must be " - + "equal to the hash (2) of TestObject{group=1, item=2} [group 1, item 2]"; - if (!expected.getMessage().contains(expectedMessage)) { - fail("<" + expected.getMessage() + "> expected to contain <" + expectedMessage + ">"); - } - return; - } - fail(); - } - - /** An object with a friendly {@link #toString()}. */ - private static final class TestObject { - final int group; - final int item; - - TestObject(int group , int item) { - this.group = group; - this.item = item; - } - - @Override public String toString() { - return Objects.toStringHelper("TestObject") - .add("group", group) - .add("item", item) - .toString(); - } - } - - private static final class MockEquivalence extends Equivalence<Object> { - final ImmutableTable.Builder<Object, Object, Boolean> equivalentExpectationsBuilder = - ImmutableTable.builder(); - final ImmutableMap.Builder<Object, Integer> hashExpectationsBuilder = - ImmutableMap.builder(); - ImmutableTable<Object, Object, Boolean> equivalentExpectations; - ImmutableMap<Object, Integer> hashExpectations; - - void expectEquivalent(Object a, Object b) { - checkRecording(); - equivalentExpectationsBuilder.put(a, b, true); - } - - void expectDistinct(Object a, Object b) { - checkRecording(); - equivalentExpectationsBuilder.put(a, b, false); - } - - void expectHash(Object object, int hash) { - checkRecording(); - hashExpectationsBuilder.put(object, hash); - } - - void replay() { - checkRecording(); - equivalentExpectations = equivalentExpectationsBuilder.build(); - hashExpectations = hashExpectationsBuilder.build(); - } - - @Override protected boolean doEquivalent(Object a, Object b) { - return equivalentExpectations.get(a, b); - } - - @Override protected int doHash(Object object) { - return hashExpectations.get(object); - } - - void checkRecording() { - checkState(equivalentExpectations == null && hashExpectations == null); - } - } -} diff --git a/guava-testlib/test/com/google/common/testing/FakeTickerTest.java b/guava-testlib/test/com/google/common/testing/FakeTickerTest.java deleted file mode 100644 index 5bf7ecd..0000000 --- a/guava-testlib/test/com/google/common/testing/FakeTickerTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (C) 2008 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.testing; - -import com.google.common.annotations.GwtCompatible; -import com.google.common.annotations.GwtIncompatible; - -import junit.framework.TestCase; - -import java.util.EnumSet; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -/** - * Unit test for {@link FakeTicker}. - * - * @author Jige Yu - */ -@GwtCompatible(emulated = true) -public class FakeTickerTest extends TestCase { - - @GwtIncompatible("NullPointerTester") - public void testNullPointerExceptions() { - NullPointerTester tester = new NullPointerTester(); - tester.testAllPublicInstanceMethods(new FakeTicker()); - } - - public void testAdvance() { - FakeTicker ticker = new FakeTicker(); - assertEquals(0, ticker.read()); - assertSame(ticker, ticker.advance(10)); - assertEquals(10, ticker.read()); - ticker.advance(1, TimeUnit.MILLISECONDS); - assertEquals(1000010L, ticker.read()); - } - - public void testAutoIncrementStep_returnsSameInstance() { - FakeTicker ticker = new FakeTicker(); - assertSame(ticker, ticker.setAutoIncrementStep(10, TimeUnit.NANOSECONDS)); - } - - public void testAutoIncrementStep_nanos() { - FakeTicker ticker = new FakeTicker().setAutoIncrementStep(10, TimeUnit.NANOSECONDS); - assertEquals(0, ticker.read()); - assertEquals(10, ticker.read()); - assertEquals(20, ticker.read()); - } - - public void testAutoIncrementStep_millis() { - FakeTicker ticker = new FakeTicker().setAutoIncrementStep(1, TimeUnit.MILLISECONDS); - assertEquals(0, ticker.read()); - assertEquals(1000000, ticker.read()); - assertEquals(2000000, ticker.read()); - } - - public void testAutoIncrementStep_seconds() { - FakeTicker ticker = new FakeTicker().setAutoIncrementStep(3, TimeUnit.SECONDS); - assertEquals(0, ticker.read()); - assertEquals(3000000000L, ticker.read()); - assertEquals(6000000000L, ticker.read()); - } - - public void testAutoIncrementStep_resetToZero() { - FakeTicker ticker = new FakeTicker().setAutoIncrementStep(10, TimeUnit.NANOSECONDS); - assertEquals(0, ticker.read()); - assertEquals(10, ticker.read()); - assertEquals(20, ticker.read()); - - for (TimeUnit timeUnit : EnumSet.allOf(TimeUnit.class)) { - ticker.setAutoIncrementStep(0, timeUnit); - assertEquals( - "Expected no auto-increment when setting autoIncrementStep to 0 " + timeUnit, - 30, ticker.read()); - } - } - - public void testAutoIncrement_negative() { - FakeTicker ticker = new FakeTicker(); - try { - ticker.setAutoIncrementStep(-1, TimeUnit.NANOSECONDS); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - } - - @GwtIncompatible("concurrency") - - public void testConcurrentAdvance() throws Exception { - final FakeTicker ticker = new FakeTicker(); - - int numberOfThreads = 64; - runConcurrentTest(numberOfThreads, - new Callable<Void>() { - @Override - public Void call() throws Exception { - // adds two nanoseconds to the ticker - ticker.advance(1L); - Thread.sleep(10); - ticker.advance(1L); - return null; - } - }); - - assertEquals(numberOfThreads * 2, ticker.read()); - } - - @GwtIncompatible("concurrency") - - public void testConcurrentAutoIncrementStep() throws Exception { - int incrementByNanos = 3; - final FakeTicker ticker = - new FakeTicker().setAutoIncrementStep(incrementByNanos, TimeUnit.NANOSECONDS); - - int numberOfThreads = 64; - runConcurrentTest(numberOfThreads, - new Callable<Void>() { - @Override - public Void call() throws Exception { - ticker.read(); - return null; - } - }); - - assertEquals(incrementByNanos * numberOfThreads, ticker.read()); - } - - /** - * Runs {@code callable} concurrently {@code numberOfThreads} times. - */ - @GwtIncompatible("concurrency") - private void runConcurrentTest(int numberOfThreads, final Callable<Void> callable) - throws Exception { - ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads); - final CountDownLatch startLatch = new CountDownLatch(numberOfThreads); - final CountDownLatch doneLatch = new CountDownLatch(numberOfThreads); - for (int i = numberOfThreads; i > 0; i--) { - executorService.submit(new Callable<Void>() { - @Override - public Void call() throws Exception { - startLatch.countDown(); - startLatch.await(); - callable.call(); - doneLatch.countDown(); - return null; - } - }); - } - doneLatch.await(); - } -} diff --git a/guava-testlib/test/com/google/common/testing/FreshValueGeneratorTest.java b/guava-testlib/test/com/google/common/testing/FreshValueGeneratorTest.java deleted file mode 100644 index 642e3d4..0000000 --- a/guava-testlib/test/com/google/common/testing/FreshValueGeneratorTest.java +++ /dev/null @@ -1,742 +0,0 @@ -/* - * 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.testing; - -import com.google.common.base.CharMatcher; -import com.google.common.base.Equivalence; -import com.google.common.base.Function; -import com.google.common.base.Joiner; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import com.google.common.base.Ticker; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.HashBiMap; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.HashMultiset; -import com.google.common.collect.ImmutableBiMap; -import com.google.common.collect.ImmutableCollection; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableListMultimap; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.ImmutableMultiset; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSetMultimap; -import com.google.common.collect.ImmutableSortedMap; -import com.google.common.collect.ImmutableSortedMultiset; -import com.google.common.collect.ImmutableSortedSet; -import com.google.common.collect.ImmutableTable; -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.LinkedHashMultiset; -import com.google.common.collect.ListMultimap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multiset; -import com.google.common.collect.Ordering; -import com.google.common.collect.RowSortedTable; -import com.google.common.collect.SetMultimap; -import com.google.common.collect.Sets; -import com.google.common.collect.SortedMultiset; -import com.google.common.collect.Table; -import com.google.common.collect.TreeBasedTable; -import com.google.common.collect.TreeMultiset; -import com.google.common.primitives.UnsignedInteger; -import com.google.common.primitives.UnsignedLong; -import com.google.common.reflect.TypeToken; - -import junit.framework.TestCase; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.DoubleBuffer; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.nio.LongBuffer; -import java.nio.ShortBuffer; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.Currency; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.NavigableMap; -import java.util.NavigableSet; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.TimeUnit; -import java.util.regex.MatchResult; -import java.util.regex.Pattern; - -/** - * Tests for {@link FreshValueGenerator}. - * - * @author Ben Yu - */ -public class FreshValueGeneratorTest extends TestCase { - - public void testFreshInstance() { - assertFreshInstances( - String.class, CharSequence.class, - Appendable.class, StringBuffer.class, StringBuilder.class, - Pattern.class, MatchResult.class, - Number.class, int.class, Integer.class, - long.class, Long.class, - short.class, Short.class, - byte.class, Byte.class, - boolean.class, Boolean.class, - char.class, Character.class, - int[].class, Object[].class, - UnsignedInteger.class, UnsignedLong.class, - BigInteger.class, BigDecimal.class, - Throwable.class, Error.class, Exception.class, RuntimeException.class, - Charset.class, Locale.class, Currency.class, - List.class, Map.Entry.class, - Object.class, - Equivalence.class, Predicate.class, Function.class, - Comparable.class, Comparator.class, Ordering.class, - Class.class, Type.class, TypeToken.class, - TimeUnit.class, Ticker.class, - Joiner.class, Splitter.class, CharMatcher.class, - InputStream.class, ByteArrayInputStream.class, - Reader.class, Readable.class, StringReader.class, - OutputStream.class, ByteArrayOutputStream.class, - Writer.class, StringWriter.class, File.class, - Buffer.class, ByteBuffer.class, CharBuffer.class, - ShortBuffer.class, IntBuffer.class, LongBuffer.class, - FloatBuffer.class, DoubleBuffer.class, - String[].class, Object[].class, int[].class); - } - - public void testStringArray() { - FreshValueGenerator generator = new FreshValueGenerator(); - String[] a1 = generator.generate(String[].class); - String[] a2 = generator.generate(String[].class); - assertFalse(a1[0].equals(a2[0])); - } - - public void testPrimitiveArray() { - FreshValueGenerator generator = new FreshValueGenerator(); - int[] a1 = generator.generate(int[].class); - int[] a2 = generator.generate(int[].class); - assertTrue(a1[0] != a2[0]); - } - - public void testImmutableList() { - assertFreshInstance(new TypeToken<ImmutableList<String>>() {}); - assertValueAndTypeEquals(ImmutableList.of(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<ImmutableList<String>>() {})); - assertValueAndTypeEquals(ImmutableList.of(new FreshValueGenerator().generate(int.class)), - new FreshValueGenerator().generate(new TypeToken<ImmutableList<Integer>>() {})); - assertValueAndTypeEquals(ImmutableList.of(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<ImmutableList<?>>() {})); - assertValueAndTypeEquals(ImmutableList.of(), - new FreshValueGenerator().generate(new TypeToken<ImmutableList<EmptyEnum>>() {})); - } - - public void testImmutableSet() { - assertFreshInstance(new TypeToken<ImmutableSet<String>>() {}); - assertValueAndTypeEquals(ImmutableSet.of(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<ImmutableSet<String>>() {})); - assertValueAndTypeEquals(ImmutableSet.of(new FreshValueGenerator().generate(Number.class)), - new FreshValueGenerator().generate(new TypeToken<ImmutableSet<Number>>() {})); - assertValueAndTypeEquals(ImmutableSet.of(new FreshValueGenerator().generate(Number.class)), - new FreshValueGenerator().generate(new TypeToken<ImmutableSet<? extends Number>>() {})); - assertValueAndTypeEquals(ImmutableSet.of(), - new FreshValueGenerator().generate(new TypeToken<ImmutableSet<EmptyEnum>>() {})); - } - - public void testImmutableSortedSet() { - assertFreshInstance(new TypeToken<ImmutableSortedSet<String>>() {}); - assertValueAndTypeEquals( - ImmutableSortedSet.of(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<ImmutableSortedSet<String>>() {})); - assertValueAndTypeEquals(ImmutableSortedSet.of(), - new FreshValueGenerator().generate(new TypeToken<ImmutableSortedSet<EmptyEnum>>() {})); - } - - public void testImmutableMultiset() { - assertFreshInstance(new TypeToken<ImmutableSortedSet<String>>() {}); - assertValueAndTypeEquals(ImmutableMultiset.of(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<ImmutableMultiset<String>>() {})); - assertValueAndTypeEquals(ImmutableMultiset.of(new FreshValueGenerator().generate(Number.class)), - new FreshValueGenerator().generate(new TypeToken<ImmutableMultiset<Number>>() {})); - assertValueAndTypeEquals(ImmutableMultiset.of(), - new FreshValueGenerator().generate(new TypeToken<ImmutableMultiset<EmptyEnum>>() {})); - } - - public void testImmutableCollection() { - assertFreshInstance(new TypeToken<ImmutableCollection<String>>() {}); - assertValueAndTypeEquals(ImmutableList.of(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<ImmutableCollection<String>>() {})); - assertValueAndTypeEquals(ImmutableList.of(), - new FreshValueGenerator().generate(new TypeToken<ImmutableCollection<EmptyEnum>>() {})); - } - - public void testImmutableMap() { - assertFreshInstance(new TypeToken<ImmutableMap<String, Integer>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - assertValueAndTypeEquals( - ImmutableMap.of(generator.generate(String.class), generator.generate(int.class)), - new FreshValueGenerator().generate(new TypeToken<ImmutableMap<String, Integer>>() {})); - assertValueAndTypeEquals(ImmutableMap.of(), - new FreshValueGenerator().generate(new TypeToken<ImmutableMap<EmptyEnum, String>>() {})); - } - - public void testImmutableSortedMap() { - assertFreshInstance(new TypeToken<ImmutableSortedMap<String, Integer>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - assertValueAndTypeEquals( - ImmutableSortedMap.of(generator.generate(String.class), generator.generate(int.class)), - new FreshValueGenerator().generate( - new TypeToken<ImmutableSortedMap<String, Integer>>() {})); - assertValueAndTypeEquals(ImmutableSortedMap.of(), - new FreshValueGenerator().generate( - new TypeToken<ImmutableSortedMap<EmptyEnum, String>>() {})); - } - - public void testImmutableMultimap() { - assertFreshInstance(new TypeToken<ImmutableMultimap<String, Integer>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - assertValueAndTypeEquals( - ImmutableMultimap.of(generator.generate(String.class), generator.generate(int.class)), - new FreshValueGenerator().generate(new TypeToken<ImmutableMultimap<String, Integer>>() {})); - assertValueAndTypeEquals(ImmutableMultimap.of(), - new FreshValueGenerator().generate( - new TypeToken<ImmutableMultimap<EmptyEnum, String>>() {})); - } - - public void testImmutableListMultimap() { - assertFreshInstance(new TypeToken<ImmutableListMultimap<String, Integer>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - assertValueAndTypeEquals( - ImmutableListMultimap.of(generator.generate(String.class), generator.generate(int.class)), - new FreshValueGenerator().generate( - new TypeToken<ImmutableListMultimap<String, Integer>>() {})); - assertValueAndTypeEquals(ImmutableListMultimap.of(), - new FreshValueGenerator().generate( - new TypeToken<ImmutableListMultimap<EmptyEnum, String>>() {})); - } - - public void testImmutableSetMultimap() { - assertFreshInstance(new TypeToken<ImmutableSetMultimap<String, Integer>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - assertValueAndTypeEquals( - ImmutableSetMultimap.of(generator.generate(String.class), generator.generate(int.class)), - new FreshValueGenerator().generate( - new TypeToken<ImmutableSetMultimap<String, Integer>>() {})); - assertValueAndTypeEquals(ImmutableSetMultimap.of(), - new FreshValueGenerator().generate( - new TypeToken<ImmutableSetMultimap<EmptyEnum, String>>() {})); - } - - public void testImmutableBiMap() { - assertFreshInstance(new TypeToken<ImmutableBiMap<String, Integer>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - assertValueAndTypeEquals( - ImmutableBiMap.of(generator.generate(String.class), generator.generate(int.class)), - new FreshValueGenerator().generate( - new TypeToken<ImmutableBiMap<String, Integer>>() {})); - assertValueAndTypeEquals(ImmutableBiMap.of(), - new FreshValueGenerator().generate( - new TypeToken<ImmutableBiMap<EmptyEnum, String>>() {})); - } - - public void testImmutableTable() { - assertFreshInstance(new TypeToken<ImmutableTable<String, Integer, ImmutableList<String>>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - assertValueAndTypeEquals( - ImmutableTable.of( - generator.generate(String.class), generator.generate(int.class), - generator.generate(new TypeToken<ImmutableList<String>>() {})), - new FreshValueGenerator().generate( - new TypeToken<ImmutableTable<String, Integer, ImmutableList<String>>>() {})); - assertValueAndTypeEquals(ImmutableTable.of(), - new FreshValueGenerator().generate( - new TypeToken<ImmutableTable<EmptyEnum, String, Integer>>() {})); - } - - public void testList() { - assertFreshInstance(new TypeToken<List<String>>() {}); - assertValueAndTypeEquals(Lists.newArrayList(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<List<String>>() {})); - assertValueAndTypeEquals(Lists.newArrayList(new FreshValueGenerator().generate(int.class)), - new FreshValueGenerator().generate(new TypeToken<List<Integer>>() {})); - assertValueAndTypeEquals(Lists.newArrayList(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<List<?>>() {})); - assertFreshInstance(new TypeToken<List<EmptyEnum>>() {}); - } - - public void testArrayList() { - assertFreshInstance(new TypeToken<ArrayList<String>>() {}); - assertValueAndTypeEquals(Lists.newArrayList(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<ArrayList<String>>() {})); - assertValueAndTypeEquals(Lists.newArrayList(new FreshValueGenerator().generate(int.class)), - new FreshValueGenerator().generate(new TypeToken<ArrayList<Integer>>() {})); - assertValueAndTypeEquals(Lists.newArrayList(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<ArrayList<?>>() {})); - assertNotNull(new FreshValueGenerator().generate(new TypeToken<ArrayList<EmptyEnum>>() {})); - } - - public void testLinkedList() { - assertFreshInstance(new TypeToken<LinkedList<String>>() {}); - assertValueAndTypeEquals(newLinkedList(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<LinkedList<String>>() {})); - assertNotNull(new FreshValueGenerator().generate(new TypeToken<LinkedList<EmptyEnum>>() {})); - } - - public void testSet() { - assertFreshInstance(new TypeToken<Set<String>>() {}); - assertValueAndTypeEquals( - newLinkedHashSet(new FreshValueGenerator().generate(Number.class)), - new FreshValueGenerator().generate(new TypeToken<Set<? extends Number>>() {})); - assertFreshInstance(new TypeToken<Set<EmptyEnum>>() {}); - } - - public void testHashSet() { - assertFreshInstance(new TypeToken<HashSet<String>>() {}); - assertValueAndTypeEquals( - newLinkedHashSet(new FreshValueGenerator().generate(Number.class)), - new FreshValueGenerator().generate(new TypeToken<HashSet<? extends Number>>() {})); - } - - public void testLinkedHashSet() { - assertFreshInstance(new TypeToken<LinkedHashSet<String>>() {}); - assertValueAndTypeEquals( - newLinkedHashSet(new FreshValueGenerator().generate(Number.class)), - new FreshValueGenerator().generate(new TypeToken<LinkedHashSet<? extends Number>>() {})); - assertNotNull(new FreshValueGenerator().generate(new TypeToken<LinkedHashSet<EmptyEnum>>() {})); - } - - public void testTreeSet() { - assertFreshInstance(new TypeToken<TreeSet<String>>() {}); - TreeSet<String> expected = Sets.newTreeSet(); - expected.add(new FreshValueGenerator().generate(String.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<TreeSet<? extends CharSequence>>() {})); - assertNotNull(new FreshValueGenerator().generate(new TypeToken<TreeSet<EmptyEnum>>() {})); - } - - public void testSortedSet() { - assertFreshInstance(new TypeToken<SortedSet<String>>() {}); - TreeSet<String> expected = Sets.newTreeSet(); - expected.add(new FreshValueGenerator().generate(String.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<SortedSet<String>>() {})); - assertFreshInstance(new TypeToken<SortedSet<EmptyEnum>>() {}); - } - - public void testNavigableSet() { - assertFreshInstance(new TypeToken<NavigableSet<String>>() {}); - TreeSet<String> expected = Sets.newTreeSet(); - expected.add(new FreshValueGenerator().generate(String.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<NavigableSet<String>>() {})); - assertFreshInstance(new TypeToken<NavigableSet<EmptyEnum>>() {}); - } - - public void testMultiset() { - assertFreshInstance(new TypeToken<Multiset<String>>() {}); - Multiset<String> expected = HashMultiset.create(); - expected.add(new FreshValueGenerator().generate(String.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<Multiset<String>>() {})); - assertFreshInstance(new TypeToken<Multiset<EmptyEnum>>() {}); - } - - public void testSortedMultiset() { - assertFreshInstance(new TypeToken<SortedMultiset<String>>() {}); - SortedMultiset<String> expected = TreeMultiset.create(); - expected.add(new FreshValueGenerator().generate(String.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<SortedMultiset<String>>() {})); - assertFreshInstance(new TypeToken<Multiset<EmptyEnum>>() {}); - } - - public void testHashMultiset() { - assertFreshInstance(new TypeToken<HashMultiset<String>>() {}); - HashMultiset<String> expected = HashMultiset.create(); - expected.add(new FreshValueGenerator().generate(String.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<HashMultiset<String>>() {})); - } - - public void testLinkedHashMultiset() { - assertFreshInstance(new TypeToken<LinkedHashMultiset<String>>() {}); - LinkedHashMultiset<String> expected = LinkedHashMultiset.create(); - expected.add(new FreshValueGenerator().generate(String.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<LinkedHashMultiset<String>>() {})); - } - - public void testTreeMultiset() { - assertFreshInstance(new TypeToken<TreeMultiset<String>>() {}); - TreeMultiset<String> expected = TreeMultiset.create(); - expected.add(new FreshValueGenerator().generate(String.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<TreeMultiset<String>>() {})); - } - - public void testImmutableSortedMultiset() { - assertFreshInstance(new TypeToken<ImmutableSortedMultiset<String>>() {}); - assertValueAndTypeEquals( - ImmutableSortedMultiset.of(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<ImmutableSortedMultiset<String>>() {})); - assertFreshInstance(new TypeToken<Multiset<EmptyEnum>>() {}); - } - - public void testCollection() { - assertFreshInstance(new TypeToken<Collection<String>>() {}); - assertValueAndTypeEquals(Lists.newArrayList(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<Collection<String>>() {})); - assertFreshInstance(new TypeToken<Collection<EmptyEnum>>() {}); - } - - public void testIterable() { - assertFreshInstance(new TypeToken<Iterable<String>>() {}); - assertValueAndTypeEquals(Lists.newArrayList(new FreshValueGenerator().generate(String.class)), - new FreshValueGenerator().generate(new TypeToken<Iterable<String>>() {})); - assertFreshInstance(new TypeToken<Iterable<EmptyEnum>>() {}); - } - - public void testMap() { - assertFreshInstance(new TypeToken<Map<String, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - Map<String, Integer> expected = Maps.newLinkedHashMap(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<Map<String, Integer>>() {})); - assertFreshInstance(new TypeToken<Map<EmptyEnum, String>>() {}); - } - - public void testHashMap() { - assertFreshInstance(new TypeToken<HashMap<String, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - HashMap<String, Integer> expected = Maps.newLinkedHashMap(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<HashMap<String, Integer>>() {})); - assertNotNull( - new FreshValueGenerator().generate(new TypeToken<HashMap<EmptyEnum, Integer>>() {})); - } - - public void testLinkedHashMap() { - assertFreshInstance(new TypeToken<LinkedHashMap<String, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - LinkedHashMap<String, Integer> expected = Maps.newLinkedHashMap(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<LinkedHashMap<String, Integer>>() {})); - assertNotNull( - new FreshValueGenerator().generate(new TypeToken<LinkedHashMap<EmptyEnum, String>>() {})); - } - - public void testTreeMap() { - assertFreshInstance(new TypeToken<TreeMap<String, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - TreeMap<String, Integer> expected = Maps.newTreeMap(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<TreeMap<String, Integer>>() {})); - assertNotNull(new FreshValueGenerator().generate(new TypeToken<LinkedHashSet<EmptyEnum>>() {})); - } - - public void testSortedMap() { - assertFreshInstance(new TypeToken<SortedMap<?, String>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - TreeMap<String, Integer> expected = Maps.newTreeMap(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate( - new TypeToken<SortedMap<String, Integer>>() {})); - assertFreshInstance(new TypeToken<SortedMap<EmptyEnum, String>>() {}); - } - - public void testNavigableMap() { - assertFreshInstance(new TypeToken<NavigableMap<?, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - TreeMap<String, Integer> expected = Maps.newTreeMap(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate( - new TypeToken<NavigableMap<String, Integer>>() {})); - assertFreshInstance(new TypeToken<NavigableMap<EmptyEnum, String>>() {}); - } - - public void testConcurrentMap() { - assertFreshInstance(new TypeToken<ConcurrentMap<String, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - ConcurrentMap<String, Integer> expected = Maps.newConcurrentMap(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<ConcurrentMap<String, Integer>>() {})); - assertFreshInstance(new TypeToken<ConcurrentMap<EmptyEnum, String>>() {}); - } - - public void testMultimap() { - assertFreshInstance(new TypeToken<Multimap<String, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - Multimap<String, Integer> expected = ArrayListMultimap.create(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<Multimap<String, Integer>>() {})); - assertFreshInstance(new TypeToken<Multimap<EmptyEnum, String>>() {}); - } - - public void testHashMultimap() { - assertFreshInstance(new TypeToken<HashMultimap<String, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - HashMultimap<String, Integer> expected = HashMultimap.create(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate(new TypeToken<HashMultimap<String, Integer>>() {})); - } - - public void testLinkedHashMultimap() { - assertFreshInstance(new TypeToken<LinkedHashMultimap<String, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - LinkedHashMultimap<String, Integer> expected = LinkedHashMultimap.create(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate( - new TypeToken<LinkedHashMultimap<String, Integer>>() {})); - } - - public void testListMultimap() { - assertFreshInstance(new TypeToken<ListMultimap<String, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - ListMultimap<String, Integer> expected = ArrayListMultimap.create(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate( - new TypeToken<ListMultimap<String, Integer>>() {})); - assertFreshInstance(new TypeToken<ListMultimap<EmptyEnum, String>>() {}); - } - - public void testArrayListMultimap() { - assertFreshInstance(new TypeToken<ArrayListMultimap<String, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - ArrayListMultimap<String, Integer> expected = ArrayListMultimap.create(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate( - new TypeToken<ArrayListMultimap<String, Integer>>() {})); - } - - public void testSetMultimap() { - assertFreshInstance(new TypeToken<SetMultimap<String, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - SetMultimap<String, Integer> expected = LinkedHashMultimap.create(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate( - new TypeToken<SetMultimap<String, Integer>>() {})); - assertFreshInstance(new TypeToken<SetMultimap<EmptyEnum, String>>() {}); - } - - public void testBiMap() { - assertFreshInstance(new TypeToken<BiMap<String, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - BiMap<String, Integer> expected = HashBiMap.create(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate( - new TypeToken<BiMap<String, Integer>>() {})); - assertFreshInstance(new TypeToken<BiMap<EmptyEnum, String>>() {}); - } - - public void testHashBiMap() { - assertFreshInstance(new TypeToken<HashBiMap<String, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - HashBiMap<String, Integer> expected = HashBiMap.create(); - expected.put(generator.generate(String.class), generator.generate(int.class)); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate( - new TypeToken<HashBiMap<String, Integer>>() {})); - } - - public void testTable() { - assertFreshInstance(new TypeToken<Table<String, ?, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - Table<String, Integer, List<String>> expected = HashBasedTable.create(); - expected.put(generator.generate(String.class), generator.generate(int.class), - generator.generate(new TypeToken<List<String>>() {})); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate( - new TypeToken<Table<String, Integer, List<String>>>() {})); - assertFreshInstance(new TypeToken<Table<EmptyEnum, String, Integer>>() {}); - } - - public void testHashBasedTable() { - assertFreshInstance(new TypeToken<HashBasedTable<String, ?, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - HashBasedTable<String, Integer, List<String>> expected = HashBasedTable.create(); - expected.put(generator.generate(String.class), generator.generate(int.class), - generator.generate(new TypeToken<List<String>>() {})); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate( - new TypeToken<HashBasedTable<String, Integer, List<String>>>() {})); - } - - public void testRowSortedTable() { - assertFreshInstance(new TypeToken<RowSortedTable<String, ?, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - RowSortedTable<String, Integer, List<String>> expected = TreeBasedTable.create(); - expected.put(generator.generate(String.class), generator.generate(int.class), - generator.generate(new TypeToken<List<String>>() {})); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate( - new TypeToken<RowSortedTable<String, Integer, List<String>>>() {})); - assertFreshInstance(new TypeToken<RowSortedTable<EmptyEnum, String, Integer>>() {}); - } - - public void testTreeBasedTable() { - assertFreshInstance(new TypeToken<TreeBasedTable<String, ?, ?>>() {}); - FreshValueGenerator generator = new FreshValueGenerator(); - TreeBasedTable<String, Integer, List<String>> expected = TreeBasedTable.create(); - expected.put(generator.generate(String.class), generator.generate(int.class), - generator.generate(new TypeToken<List<String>>() {})); - assertValueAndTypeEquals(expected, - new FreshValueGenerator().generate( - new TypeToken<TreeBasedTable<String, Integer, List<String>>>() {})); - } - - public void testObject() { - assertEquals(new FreshValueGenerator().generate(String.class), - new FreshValueGenerator().generate(Object.class)); - } - - public void testEnums() { - assertEqualInstance(EmptyEnum.class, null); - assertEqualInstance(OneConstantEnum.class, OneConstantEnum.CONSTANT1); - assertFreshInstance(TwoConstantEnum.class); - } - - public void testAddSampleInstances_twoInstances() { - FreshValueGenerator generator = new FreshValueGenerator(); - generator.addSampleInstances(String.class, ImmutableList.of("a", "b")); - assertEquals("a", generator.generate(String.class)); - assertEquals("b", generator.generate(String.class)); - assertEquals("a", generator.generate(String.class)); - } - - public void testAddSampleInstances_oneInstance() { - FreshValueGenerator generator = new FreshValueGenerator(); - generator.addSampleInstances(String.class, ImmutableList.of("a")); - assertEquals("a", generator.generate(String.class)); - assertEquals("a", generator.generate(String.class)); - } - - public void testAddSampleInstances_noInstance() { - FreshValueGenerator generator = new FreshValueGenerator(); - generator.addSampleInstances(String.class, ImmutableList.<String>of()); - assertEquals(new FreshValueGenerator().generate(String.class), - generator.generate(String.class)); - } - - public void testFreshCurrency() { - FreshValueGenerator generator = new FreshValueGenerator(); - // repeat a few times to make sure we don't stumble upon a bad Locale - assertNotNull(generator.generate(Currency.class)); - assertNotNull(generator.generate(Currency.class)); - assertNotNull(generator.generate(Currency.class)); - } - - public void testNulls() throws Exception { - new ClassSanityTester() - .setDefault(Method.class, FreshValueGeneratorTest.class.getDeclaredMethod("testNulls")) - .testNulls(FreshValueGenerator.class); - } - - private static void assertFreshInstances(Class<?>... types) { - for (Class<?> type : types) { - assertFreshInstance(type); - } - } - - private static <T> void assertFreshInstance(TypeToken<T> type) { - FreshValueGenerator generator = new FreshValueGenerator(); - T value1 = generator.generate(type); - T value2 = generator.generate(type); - assertNotNull("Null returned for " + type, value1); - assertFalse("Equal instance " + value1 + " returned for " + type, value1.equals(value2)); - } - - private static <T> void assertFreshInstance(Class<T> type) { - assertFreshInstance(TypeToken.of(type)); - } - - private static <T> void assertEqualInstance(Class<T> type, T value) { - FreshValueGenerator generator = new FreshValueGenerator(); - assertEquals(value, generator.generate(type)); - assertEquals(value, generator.generate(type)); - } - - private enum EmptyEnum {} - - private enum OneConstantEnum { - CONSTANT1 - } - - private enum TwoConstantEnum { - CONSTANT1, CONSTANT2 - } - - private static void assertValueAndTypeEquals(Object expected, Object actual) { - assertEquals(expected, actual); - assertEquals(expected.getClass(), actual.getClass()); - } - - private static <E> LinkedHashSet<E> newLinkedHashSet(E element) { - LinkedHashSet<E> set = Sets.newLinkedHashSet(); - set.add(element); - return set; - } - - private static <E> LinkedList<E> newLinkedList(E element) { - LinkedList<E> list = Lists.newLinkedList(); - list.add(element); - return list; - } -} diff --git a/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java b/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java deleted file mode 100644 index 117186f..0000000 --- a/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Copyright (C) 2011 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.testing; - -import com.google.common.testing.GcFinalization.FinalizationPredicate; -import com.google.common.util.concurrent.SettableFuture; - -import junit.framework.TestCase; - -import java.lang.ref.WeakReference; -import java.util.WeakHashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Tests for {@link GcFinalization}. - * - * @author Martin Buchholz - * @author mike nonemacher - */ - -public class GcFinalizationTest extends TestCase { - - //---------------------------------------------------------------- - // Ordinary tests of successful method execution - //---------------------------------------------------------------- - - public void testAwait_CountDownLatch() { - final CountDownLatch latch = new CountDownLatch(1); - Object x = new Object() { - @Override protected void finalize() { latch.countDown(); } - }; - x = null; // Hint to the JIT that x is unreachable - GcFinalization.await(latch); - assertEquals(0, latch.getCount()); - } - - public void testAwaitDone_Future() { - final SettableFuture<Void> future = SettableFuture.create(); - Object x = new Object() { - @Override protected void finalize() { future.set(null); } - }; - x = null; // Hint to the JIT that x is unreachable - GcFinalization.awaitDone(future); - assertTrue(future.isDone()); - assertFalse(future.isCancelled()); - } - - public void testAwaitDone_Future_Cancel() { - final SettableFuture<Void> future = SettableFuture.create(); - Object x = new Object() { - @Override protected void finalize() { future.cancel(false); } - }; - x = null; // Hint to the JIT that x is unreachable - GcFinalization.awaitDone(future); - assertTrue(future.isDone()); - assertTrue(future.isCancelled()); - } - - public void testAwaitClear() { - final WeakReference<Object> ref = new WeakReference<Object>(new Object()); - GcFinalization.awaitClear(ref); - assertNull(ref.get()); - } - - public void testAwaitDone_FinalizationPredicate() { - final WeakHashMap<Object, Object> map = new WeakHashMap<Object, Object>(); - map.put(new Object(), Boolean.TRUE); - GcFinalization.awaitDone(new FinalizationPredicate() { - public boolean isDone() { - return map.isEmpty(); - } - }); - assertTrue(map.isEmpty()); - } - - //---------------------------------------------------------------- - // Test that interrupts result in RuntimeException, not InterruptedException. - // Trickier than it looks, because runFinalization swallows interrupts. - //---------------------------------------------------------------- - - class Interruptenator extends Thread { - final AtomicBoolean shutdown; - Interruptenator(final Thread interruptee) { - this(interruptee, new AtomicBoolean(false)); - } - Interruptenator(final Thread interruptee, - final AtomicBoolean shutdown) { - super(new Runnable() { - public void run() { - while (!shutdown.get()) { - interruptee.interrupt(); - Thread.yield(); - }}}); - this.shutdown = shutdown; - start(); - } - void shutdown() { - shutdown.set(true); - while (this.isAlive()) { - Thread.yield(); - } - } - } - - void assertWrapsInterruptedException(RuntimeException e) { - assertTrue(e.getMessage().contains("Unexpected interrupt")); - assertTrue(e.getCause() instanceof InterruptedException); - } - - public void testAwait_CountDownLatch_Interrupted() { - Interruptenator interruptenator = new Interruptenator(Thread.currentThread()); - try { - final CountDownLatch latch = new CountDownLatch(1); - try { - GcFinalization.await(latch); - fail("should throw"); - } catch (RuntimeException expected) { - assertWrapsInterruptedException(expected); - } - } finally { - interruptenator.shutdown(); - Thread.interrupted(); - } - } - - public void testAwaitDone_Future_Interrupted_Interrupted() { - Interruptenator interruptenator = new Interruptenator(Thread.currentThread()); - try { - final SettableFuture<Void> future = SettableFuture.create(); - try { - GcFinalization.awaitDone(future); - fail("should throw"); - } catch (RuntimeException expected) { - assertWrapsInterruptedException(expected); - } - } finally { - interruptenator.shutdown(); - Thread.interrupted(); - } - } - - public void testAwaitClear_Interrupted() { - Interruptenator interruptenator = new Interruptenator(Thread.currentThread()); - try { - final WeakReference<Object> ref = new WeakReference<Object>(Boolean.TRUE); - try { - GcFinalization.awaitClear(ref); - fail("should throw"); - } catch (RuntimeException expected) { - assertWrapsInterruptedException(expected); - } - } finally { - interruptenator.shutdown(); - Thread.interrupted(); - } - } - - public void testAwaitDone_FinalizationPredicate_Interrupted() { - Interruptenator interruptenator = new Interruptenator(Thread.currentThread()); - try { - try { - GcFinalization.awaitDone(new FinalizationPredicate() { - public boolean isDone() { - return false; - } - }); - fail("should throw"); - } catch (RuntimeException expected) { - assertWrapsInterruptedException(expected); - } - } finally { - interruptenator.shutdown(); - Thread.interrupted(); - } - } - - /** - * awaitFullGc() is not quite as reliable a way to ensure calling of a - * specific finalize method as the more direct await* methods, but should be - * reliable enough in practice to avoid flakiness of this test. (And if it - * isn't, we'd like to know about it first!) - */ - public void testAwaitFullGc() { - final CountDownLatch finalizerRan = new CountDownLatch(1); - final WeakReference<Object> ref = new WeakReference<Object>( - new Object() { - @Override protected void finalize() { finalizerRan.countDown(); } - }); - - // Don't copy this into your own test! - // Use e.g. awaitClear or await(CountDownLatch) instead. - GcFinalization.awaitFullGc(); - - // If this test turns out to be flaky, add a second call to awaitFullGc() - // GcFinalization.awaitFullGc(); - - assertEquals(0, finalizerRan.getCount()); - assertNull(ref.get()); - } - -} diff --git a/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java b/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java deleted file mode 100644 index ef70b67..0000000 --- a/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java +++ /dev/null @@ -1,1221 +0,0 @@ -/* - * Copyright (C) 2005 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.testing; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.truth0.Truth.ASSERT; - -import com.google.common.base.Function; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.ImmutableMultiset; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSortedSet; -import com.google.common.collect.ImmutableTable; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multiset; -import com.google.common.collect.Table; -import com.google.common.reflect.TypeToken; -import com.google.common.testing.NullPointerTester.Visibility; -import com.google.common.testing.anotherpackage.SomeClassThatDoesNotUseNullable; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedSet; - -import javax.annotation.Nullable; - -/** - * Unit test for {@link NullPointerTester}. - * - * @author Kevin Bourrillion - * @author Mick Killianey - */ -public class NullPointerTesterTest extends TestCase { - - /** Non-NPE RuntimeException. */ - public static class FooException extends RuntimeException { - private static final long serialVersionUID = 1L; - } - - /** - * Class for testing all permutations of static/non-static one-argument - * methods using methodParameter(). - */ - @SuppressWarnings("unused") // used by reflection - public static class OneArg { - - public static void staticOneArgCorrectlyThrowsNpe(String s) { - checkNotNull(s); // expect NPE here on null - } - public static void staticOneArgThrowsOtherThanNpe(String s) { - throw new FooException(); // should catch as failure - } - public static void staticOneArgShouldThrowNpeButDoesnt(String s) { - // should catch as failure - } - public static void - staticOneArgNullableCorrectlyDoesNotThrowNPE(@Nullable String s) { - // null? no problem - } - public static void - staticOneArgNullableCorrectlyThrowsOtherThanNPE(@Nullable String s) { - throw new FooException(); // ok, as long as it's not NullPointerException - } - public static void - staticOneArgNullableThrowsNPE(@Nullable String s) { - checkNotNull(s); // doesn't check if you said you'd accept null, but you don't - } - - public void oneArgCorrectlyThrowsNpe(String s) { - checkNotNull(s); // expect NPE here on null - } - public void oneArgThrowsOtherThanNpe(String s) { - throw new FooException(); // should catch as failure - } - public void oneArgShouldThrowNpeButDoesnt(String s) { - // should catch as failure - } - public void oneArgNullableCorrectlyDoesNotThrowNPE(@Nullable String s) { - // null? no problem - } - public void oneArgNullableCorrectlyThrowsOtherThanNPE(@Nullable String s) { - throw new FooException(); // ok, as long as it's not NullPointerException - } - public void oneArgNullableThrowsNPE(@Nullable String s) { - checkNotNull(s); // doesn't check if you said you'd accept null, but you don't - } - } - - private static final String[] STATIC_ONE_ARG_METHODS_SHOULD_PASS = { - "staticOneArgCorrectlyThrowsNpe", - "staticOneArgNullableCorrectlyDoesNotThrowNPE", - "staticOneArgNullableCorrectlyThrowsOtherThanNPE", - "staticOneArgNullableThrowsNPE", - }; - private static final String[] STATIC_ONE_ARG_METHODS_SHOULD_FAIL = { - "staticOneArgThrowsOtherThanNpe", - "staticOneArgShouldThrowNpeButDoesnt", - }; - private static final String[] NONSTATIC_ONE_ARG_METHODS_SHOULD_PASS = { - "oneArgCorrectlyThrowsNpe", - "oneArgNullableCorrectlyDoesNotThrowNPE", - "oneArgNullableCorrectlyThrowsOtherThanNPE", - "oneArgNullableThrowsNPE", - }; - private static final String[] NONSTATIC_ONE_ARG_METHODS_SHOULD_FAIL = { - "oneArgThrowsOtherThanNpe", - "oneArgShouldThrowNpeButDoesnt", - }; - - public void testStaticOneArgMethodsThatShouldPass() throws Exception { - for (String methodName : STATIC_ONE_ARG_METHODS_SHOULD_PASS) { - Method method = OneArg.class.getMethod(methodName, String.class); - try { - new NullPointerTester().testMethodParameter(new OneArg(), method, 0); - } catch (AssertionFailedError unexpected) { - fail("Should not have flagged method " + methodName); - } - } - } - - public void testStaticOneArgMethodsThatShouldFail() throws Exception { - for (String methodName : STATIC_ONE_ARG_METHODS_SHOULD_FAIL) { - Method method = OneArg.class.getMethod(methodName, String.class); - boolean foundProblem = false; - try { - new NullPointerTester().testMethodParameter(new OneArg(), method, 0); - } catch (AssertionFailedError expected) { - foundProblem = true; - } - assertTrue("Should report error in method " + methodName, foundProblem); - } - } - - public void testNonStaticOneArgMethodsThatShouldPass() throws Exception { - OneArg foo = new OneArg(); - for (String methodName : NONSTATIC_ONE_ARG_METHODS_SHOULD_PASS) { - Method method = OneArg.class.getMethod(methodName, String.class); - try { - new NullPointerTester().testMethodParameter(foo, method, 0); - } catch (AssertionFailedError unexpected) { - fail("Should not have flagged method " + methodName); - } - } - } - - public void testNonStaticOneArgMethodsThatShouldFail() throws Exception { - OneArg foo = new OneArg(); - for (String methodName : NONSTATIC_ONE_ARG_METHODS_SHOULD_FAIL) { - Method method = OneArg.class.getMethod(methodName, String.class); - boolean foundProblem = false; - try { - new NullPointerTester().testMethodParameter(foo, method, 0); - } catch (AssertionFailedError expected) { - foundProblem = true; - } - assertTrue("Should report error in method " + methodName, foundProblem); - } - } - - /** - * Class for testing all permutations of nullable/non-nullable two-argument - * methods using testMethod(). - * - * normalNormal: two params, neither is Nullable - * nullableNormal: only first param is Nullable - * normalNullable: only second param is Nullable - * nullableNullable: both params are Nullable - */ - public static class TwoArg { - /** Action to take on a null param. */ - public enum Action { - THROW_A_NPE { - @Override public void act() { - throw new NullPointerException(); - } - }, - THROW_OTHER { - @Override public void act() { - throw new FooException(); - } - }, - JUST_RETURN { - @Override public void act() {} - }; - - public abstract void act(); - } - Action actionWhenFirstParamIsNull; - Action actionWhenSecondParamIsNull; - - public TwoArg( - Action actionWhenFirstParamIsNull, - Action actionWhenSecondParamIsNull) { - this.actionWhenFirstParamIsNull = actionWhenFirstParamIsNull; - this.actionWhenSecondParamIsNull = actionWhenSecondParamIsNull; - } - - /** Method that decides how to react to parameters. */ - public void reactToNullParameters(Object first, Object second) { - if (first == null) { - actionWhenFirstParamIsNull.act(); - } - if (second == null) { - actionWhenSecondParamIsNull.act(); - } - } - - /** Two-arg method with no Nullable params. */ - public void normalNormal(String first, Integer second) { - reactToNullParameters(first, second); - } - - /** Two-arg method with the second param Nullable. */ - public void normalNullable(String first, @Nullable Integer second) { - reactToNullParameters(first, second); - } - - /** Two-arg method with the first param Nullable. */ - public void nullableNormal(@Nullable String first, Integer second) { - reactToNullParameters(first, second); - } - - /** Two-arg method with the both params Nullable. */ - public void nullableNullable( - @Nullable String first, @Nullable Integer second) { - reactToNullParameters(first, second); - } - - /** To provide sanity during debugging. */ - @Override public String toString() { - return String.format("Bar(%s, %s)", - actionWhenFirstParamIsNull, actionWhenSecondParamIsNull); - } - } - - public void verifyBarPass(Method method, TwoArg bar) { - try { - new NullPointerTester().testMethod(bar, method); - } catch (AssertionFailedError incorrectError) { - String errorMessage = String.format( - "Should not have flagged method %s for %s", method.getName(), bar); - assertNull(errorMessage, incorrectError); - } - } - - public void verifyBarFail(Method method, TwoArg bar) { - try { - new NullPointerTester().testMethod(bar, method); - } catch (AssertionFailedError expected) { - return; // good...we wanted a failure - } - String errorMessage = String.format( - "Should have flagged method %s for %s", method.getName(), bar); - fail(errorMessage); - } - - public void testTwoArgNormalNormal() throws Exception { - Method method = TwoArg.class.getMethod( - "normalNormal", String.class, Integer.class); - for (TwoArg.Action first : TwoArg.Action.values()) { - for (TwoArg.Action second : TwoArg.Action.values()) { - TwoArg bar = new TwoArg(first, second); - if (first.equals(TwoArg.Action.THROW_A_NPE) - && second.equals(TwoArg.Action.THROW_A_NPE)) { - verifyBarPass(method, bar); // require both params to throw NPE - } else { - verifyBarFail(method, bar); - } - } - } - } - - public void testTwoArgNormalNullable() throws Exception { - Method method = TwoArg.class.getMethod( - "normalNullable", String.class, Integer.class); - for (TwoArg.Action first : TwoArg.Action.values()) { - for (TwoArg.Action second : TwoArg.Action.values()) { - TwoArg bar = new TwoArg(first, second); - if (first.equals(TwoArg.Action.THROW_A_NPE)) { - verifyBarPass(method, bar); // only pass if 1st param throws NPE - } else { - verifyBarFail(method, bar); - } - } - } - } - - public void testTwoArgNullableNormal() throws Exception { - Method method = TwoArg.class.getMethod( - "nullableNormal", String.class, Integer.class); - for (TwoArg.Action first : TwoArg.Action.values()) { - for (TwoArg.Action second : TwoArg.Action.values()) { - TwoArg bar = new TwoArg(first, second); - if (second.equals(TwoArg.Action.THROW_A_NPE)) { - verifyBarPass(method, bar); // only pass if 2nd param throws NPE - } else { - verifyBarFail(method, bar); - } - } - } - } - - public void testTwoArgNullableNullable() throws Exception { - Method method = TwoArg.class.getMethod( - "nullableNullable", String.class, Integer.class); - for (TwoArg.Action first : TwoArg.Action.values()) { - for (TwoArg.Action second : TwoArg.Action.values()) { - TwoArg bar = new TwoArg(first, second); - verifyBarPass(method, bar); // All args nullable: anything goes! - } - } - } - - /* - * This next part consists of several sample classes that provide - * demonstrations of conditions that cause NullPointerTester - * to succeed/fail. - */ - - /** Lots of well-behaved methods. */ - @SuppressWarnings("unused") // used by reflection - private static class PassObject extends SomeClassThatDoesNotUseNullable { - public static void doThrow(Object arg) { - if (arg == null) { - throw new FooException(); - } - } - public void noArg() {} - public void oneArg(String s) { checkNotNull(s); } - void packagePrivateOneArg(String s) { checkNotNull(s); } - protected void protectedOneArg(String s) { checkNotNull(s); } - public void oneNullableArg(@Nullable String s) {} - public void oneNullableArgThrows(@Nullable String s) { doThrow(s); } - - public void twoArg(String s, Integer i) { checkNotNull(s); i.intValue(); } - public void twoMixedArgs(String s, @Nullable Integer i) { checkNotNull(s); } - public void twoMixedArgsThrows(String s, @Nullable Integer i) { - checkNotNull(s); doThrow(i); - } - public void twoMixedArgs(@Nullable Integer i, String s) { checkNotNull(s); } - public void twoMixedArgsThrows(@Nullable Integer i, String s) { - checkNotNull(s); doThrow(i); - } - public void twoNullableArgs(@Nullable String s, - @javax.annotation.Nullable Integer i) {} - public void twoNullableArgsThrowsFirstArg( - @Nullable String s, @Nullable Integer i) { - doThrow(s); - } - public void twoNullableArgsThrowsSecondArg( - @Nullable String s, @Nullable Integer i) { - doThrow(i); - } - public static void staticOneArg(String s) { checkNotNull(s); } - public static void staticOneNullableArg(@Nullable String s) {} - public static void staticOneNullableArgThrows(@Nullable String s) { - doThrow(s); - } - } - - public void testGoodClass() { - shouldPass(new PassObject()); - } - - private static class FailOneArgDoesntThrowNPE extends PassObject { - @Override public void oneArg(String s) { - // Fail: missing NPE for s - } - } - - public void testFailOneArgDoesntThrowNpe() { - shouldFail(new FailOneArgDoesntThrowNPE()); - } - - private static class FailOneArgThrowsWrongType extends PassObject { - @Override public void oneArg(String s) { - doThrow(s); // Fail: throwing non-NPE exception for null s - } - } - - public void testFailOneArgThrowsWrongType() { - shouldFail(new FailOneArgThrowsWrongType()); - } - - private static class PassOneNullableArgThrowsNPE extends PassObject { - @Override public void oneNullableArg(@Nullable String s) { - checkNotNull(s); // ok to throw NPE - } - } - - public void testPassOneNullableArgThrowsNPE() { - shouldPass(new PassOneNullableArgThrowsNPE()); - } - - private static class FailTwoArgsFirstArgDoesntThrowNPE extends PassObject { - @Override public void twoArg(String s, Integer i) { - // Fail: missing NPE for s - i.intValue(); - } - } - - public void testFailTwoArgsFirstArgDoesntThrowNPE() { - shouldFail(new FailTwoArgsFirstArgDoesntThrowNPE()); - } - - private static class FailTwoArgsFirstArgThrowsWrongType extends PassObject { - @Override public void twoArg(String s, Integer i) { - doThrow(s); // Fail: throwing non-NPE exception for null s - i.intValue(); - } - } - - public void testFailTwoArgsFirstArgThrowsWrongType() { - shouldFail(new FailTwoArgsFirstArgThrowsWrongType()); - } - - private static class FailTwoArgsSecondArgDoesntThrowNPE extends PassObject { - @Override public void twoArg(String s, Integer i) { - checkNotNull(s); - // Fail: missing NPE for i - } - } - - public void testFailTwoArgsSecondArgDoesntThrowNPE() { - shouldFail(new FailTwoArgsSecondArgDoesntThrowNPE()); - } - - private static class FailTwoArgsSecondArgThrowsWrongType extends PassObject { - @Override public void twoArg(String s, Integer i) { - checkNotNull(s); - doThrow(i); // Fail: throwing non-NPE exception for null i - } - } - - public void testFailTwoArgsSecondArgThrowsWrongType() { - shouldFail(new FailTwoArgsSecondArgThrowsWrongType()); - } - - private static class FailTwoMixedArgsFirstArgDoesntThrowNPE - extends PassObject { - @Override public void twoMixedArgs(String s, @Nullable Integer i) { - // Fail: missing NPE for s - } - } - - public void testFailTwoMixedArgsFirstArgDoesntThrowNPE() { - shouldFail(new FailTwoMixedArgsFirstArgDoesntThrowNPE()); - } - - private static class FailTwoMixedArgsFirstArgThrowsWrongType - extends PassObject { - @Override public void twoMixedArgs(String s, @Nullable Integer i) { - doThrow(s); // Fail: throwing non-NPE exception for null s - } - } - - public void testFailTwoMixedArgsFirstArgThrowsWrongType() { - shouldFail(new FailTwoMixedArgsFirstArgThrowsWrongType()); - } - - private static class PassTwoMixedArgsNullableArgThrowsNPE extends PassObject { - @Override public void twoMixedArgs(String s, @Nullable Integer i) { - checkNotNull(s); - i.intValue(); // ok to throw NPE? - } - } - - public void testPassTwoMixedArgsNullableArgThrowsNPE() { - shouldPass(new PassTwoMixedArgsNullableArgThrowsNPE()); - } - - private static class PassTwoMixedArgSecondNullableArgThrowsOther - extends PassObject { - @Override public void twoMixedArgs(String s, @Nullable Integer i) { - checkNotNull(s); - doThrow(i); // ok to throw non-NPE exception for null i - } - } - - public void testPassTwoMixedArgSecondNullableArgThrowsOther() { - shouldPass(new PassTwoMixedArgSecondNullableArgThrowsOther()); - } - - private static class FailTwoMixedArgsSecondArgDoesntThrowNPE - extends PassObject { - @Override public void twoMixedArgs(@Nullable Integer i, String s) { - // Fail: missing NPE for null s - } - } - - public void testFailTwoMixedArgsSecondArgDoesntThrowNPE() { - shouldFail(new FailTwoMixedArgsSecondArgDoesntThrowNPE()); - } - - private static class FailTwoMixedArgsSecondArgThrowsWrongType - extends PassObject { - @Override public void twoMixedArgs(@Nullable Integer i, String s) { - doThrow(s); // Fail: throwing non-NPE exception for null s - } - } - - public void testFailTwoMixedArgsSecondArgThrowsWrongType() { - shouldFail(new FailTwoMixedArgsSecondArgThrowsWrongType()); - } - - private static class PassTwoNullableArgsFirstThrowsNPE extends PassObject { - @Override public void twoNullableArgs( - @Nullable String s, @Nullable Integer i) { - checkNotNull(s); // ok to throw NPE? - } - } - - public void testPassTwoNullableArgsFirstThrowsNPE() { - shouldPass(new PassTwoNullableArgsFirstThrowsNPE()); - } - - private static class PassTwoNullableArgsFirstThrowsOther extends PassObject { - @Override public void twoNullableArgs( - @Nullable String s, @Nullable Integer i) { - doThrow(s); // ok to throw non-NPE exception for null s - } - } - - public void testPassTwoNullableArgsFirstThrowsOther() { - shouldPass(new PassTwoNullableArgsFirstThrowsOther()); - } - - private static class PassTwoNullableArgsSecondThrowsNPE extends PassObject { - @Override public void twoNullableArgs( - @Nullable String s, @Nullable Integer i) { - i.intValue(); // ok to throw NPE? - } - } - - public void testPassTwoNullableArgsSecondThrowsNPE() { - shouldPass(new PassTwoNullableArgsSecondThrowsNPE()); - } - - private static class PassTwoNullableArgsSecondThrowsOther extends PassObject { - @Override public void twoNullableArgs( - @Nullable String s, @Nullable Integer i) { - doThrow(i); // ok to throw non-NPE exception for null i - } - } - - public void testPassTwoNullableArgsSecondThrowsOther() { - shouldPass(new PassTwoNullableArgsSecondThrowsOther()); - } - - private static class PassTwoNullableArgsNeitherThrowsAnything - extends PassObject { - @Override public void twoNullableArgs( - @Nullable String s, @Nullable Integer i) { - // ok to do nothing - } - } - - public void testPassTwoNullableArgsNeitherThrowsAnything() { - shouldPass(new PassTwoNullableArgsNeitherThrowsAnything()); - } - - @SuppressWarnings("unused") // for NullPointerTester - private static abstract class BaseClassThatFailsToThrow { - public void oneArg(String s) {} - } - - private static class SubclassWithBadSuperclass - extends BaseClassThatFailsToThrow {} - - public void testSubclassWithBadSuperclass() { - shouldFail(new SubclassWithBadSuperclass()); - } - - @SuppressWarnings("unused") // for NullPointerTester - private static abstract class BaseClassThatFailsToThrowForPackagePrivate { - void packagePrivateOneArg(String s) {} - } - - private static class SubclassWithBadSuperclassForPackagePrivate - extends BaseClassThatFailsToThrowForPackagePrivate {} - - public void testSubclassWithBadSuperclassForPackagePrivateMethod() { - shouldFail( - new SubclassWithBadSuperclassForPackagePrivate(), Visibility.PACKAGE); - } - - @SuppressWarnings("unused") // for NullPointerTester - private static abstract class BaseClassThatFailsToThrowForProtected { - protected void protectedOneArg(String s) {} - } - - private static class SubclassWithBadSuperclassForProtected - extends BaseClassThatFailsToThrowForProtected {} - - public void testSubclassWithBadSuperclassForPackageProtectedMethod() { - shouldFail( - new SubclassWithBadSuperclassForProtected(), Visibility.PROTECTED); - } - - private static class SubclassThatOverridesBadSuperclassMethod - extends BaseClassThatFailsToThrow { - @Override public void oneArg(@Nullable String s) {} - } - - public void testSubclassThatOverridesBadSuperclassMethod() { - shouldPass(new SubclassThatOverridesBadSuperclassMethod()); - } - - @SuppressWarnings("unused") // for NullPointerTester - private static class SubclassOverridesTheWrongMethod - extends BaseClassThatFailsToThrow { - public void oneArg(@Nullable CharSequence s) {} - } - - public void testSubclassOverridesTheWrongMethod() { - shouldFail(new SubclassOverridesTheWrongMethod()); - } - - @SuppressWarnings("unused") // for NullPointerTester - private static class ClassThatFailsToThrowForStatic { - static void staticOneArg(String s) {} - } - - public void testClassThatFailsToThrowForStatic() { - shouldFail(ClassThatFailsToThrowForStatic.class); - } - - private static class SubclassThatFailsToThrowForStatic - extends ClassThatFailsToThrowForStatic {} - - public void testSubclassThatFailsToThrowForStatic() { - shouldFail(SubclassThatFailsToThrowForStatic.class); - } - - private static class SubclassThatTriesToOverrideBadStaticMethod - extends ClassThatFailsToThrowForStatic { - static void staticOneArg(@Nullable String s) {} - } - - public void testSubclassThatTriesToOverrideBadStaticMethod() { - shouldFail(SubclassThatTriesToOverrideBadStaticMethod.class); - } - - private static final class HardToCreate { - private HardToCreate(HardToCreate x) {} - } - - @SuppressWarnings("unused") // used by reflection - private static class CanCreateDefault { - public void foo(@Nullable HardToCreate ignored, String required) { - checkNotNull(required); - } - } - - public void testCanCreateDefault() { - shouldPass(new CanCreateDefault()); - } - - @SuppressWarnings("unused") // used by reflection - private static class CannotCreateDefault { - public void foo(HardToCreate ignored, String required) { - checkNotNull(ignored); - checkNotNull(required); - } - } - - public void testCannotCreateDefault() { - shouldFail(new CannotCreateDefault()); - } - - private static void shouldPass(Object instance, Visibility visibility) { - new NullPointerTester().testInstanceMethods(instance, visibility); - } - - private static void shouldPass(Object instance) { - shouldPass(instance, Visibility.PACKAGE); - shouldPass(instance, Visibility.PROTECTED); - shouldPass(instance, Visibility.PUBLIC); - } - - // TODO(cpovirk): eliminate surprising Object/Class overloading of shouldFail - - private static void shouldFail(Object instance, Visibility visibility) { - try { - new NullPointerTester().testInstanceMethods(instance, visibility); - } catch (AssertionFailedError expected) { - return; - } - fail("Should detect problem in " + instance.getClass().getSimpleName()); - } - - private static void shouldFail(Object instance) { - shouldFail(instance, Visibility.PACKAGE); - shouldFail(instance, Visibility.PROTECTED); - shouldFail(instance, Visibility.PUBLIC); - } - - private static void shouldFail(Class<?> cls, Visibility visibility) { - try { - new NullPointerTester().testStaticMethods(cls, visibility); - } catch (AssertionFailedError expected) { - return; - } - fail("Should detect problem in " + cls.getSimpleName()); - } - - private static void shouldFail(Class<?> cls) { - shouldFail(cls, Visibility.PACKAGE); - } - - @SuppressWarnings("unused") // used by reflection - private static class PrivateClassWithPrivateConstructor { - private PrivateClassWithPrivateConstructor(@Nullable Integer argument) {} - } - - public void testPrivateClass() { - NullPointerTester tester = new NullPointerTester(); - for (Constructor<?> constructor - : PrivateClassWithPrivateConstructor.class.getDeclaredConstructors()) { - tester.testConstructor(constructor); - } - } - - private interface Foo<T> { - void doSomething(T bar, Integer baz); - } - - private static class StringFoo implements Foo<String> { - - @Override public void doSomething(String bar, Integer baz) { - checkNotNull(bar); - checkNotNull(baz); - } - } - - public void testBridgeMethodIgnored() { - new NullPointerTester().testAllPublicInstanceMethods(new StringFoo()); - } - - private static abstract class DefaultValueChecker { - - private final Map<Integer, Object> arguments = Maps.newHashMap(); - - final DefaultValueChecker runTester() { - new NullPointerTester() - .testInstanceMethods(this, Visibility.PACKAGE); - return this; - } - - final void assertNonNullValues(Object... expectedValues) { - assertEquals(expectedValues.length, arguments.size()); - for (int i = 0; i < expectedValues.length; i++) { - assertEquals("Default value for parameter #" + i, - expectedValues[i], arguments.get(i)); - } - } - - final Object getDefaultParameterValue(int position) { - return arguments.get(position); - } - - final void calledWith(Object... args) { - for (int i = 0; i < args.length; i++) { - if (args[i] != null) { - arguments.put(i, args[i]); - } - } - for (Object arg : args) { - checkNotNull(arg); // to fulfill null check - } - } - } - - private enum Gender { - MALE, FEMALE - } - - private static class AllDefaultValuesChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkDefaultValuesForTheseTypes( - Gender gender, - Integer integer, int i, - String string, CharSequence charSequence, - List<String> list, - ImmutableList<Integer> immutableList, - Map<String, Integer> map, - ImmutableMap<String, String> immutableMap, - Set<String> set, - ImmutableSet<Integer> immutableSet, - SortedSet<Number> sortedSet, - ImmutableSortedSet<Number> immutableSortedSet, - Multiset<String> multiset, - ImmutableMultiset<Integer> immutableMultiset, - Multimap<String, Integer> multimap, - ImmutableMultimap<String, Integer> immutableMultimap, - Table<String, Integer, Exception> table, - ImmutableTable<Integer, String, Exception> immutableTable) { - calledWith( - gender, - integer, i, - string, charSequence, - list, immutableList, - map, immutableMap, - set, immutableSet, - sortedSet, immutableSortedSet, - multiset, immutableMultiset, - multimap, immutableMultimap, - table, immutableTable); - } - - final void check() { - runTester().assertNonNullValues( - Gender.MALE, - Integer.valueOf(0), 0, - "", "", - ImmutableList.of(), ImmutableList.of(), - ImmutableMap.of(), ImmutableMap.of(), - ImmutableSet.of(), ImmutableSet.of(), - ImmutableSortedSet.of(), ImmutableSortedSet.of(), - ImmutableMultiset.of(), ImmutableMultiset.of(), - ImmutableMultimap.of(), ImmutableMultimap.of(), - ImmutableTable.of(), ImmutableTable.of()); - } - } - - public void testDefaultValues() { - new AllDefaultValuesChecker().check(); - } - - private static class ObjectArrayDefaultValueChecker - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(Object[] array, String s) { - calledWith(array, s); - } - - void check() { - runTester(); - Object[] defaultArray = (Object[]) getDefaultParameterValue(0); - assertEquals(0, defaultArray.length); - } - } - - public void testObjectArrayDefaultValue() { - new ObjectArrayDefaultValueChecker().check(); - } - - private static class StringArrayDefaultValueChecker - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(String[] array, String s) { - calledWith(array, s); - } - - void check() { - runTester(); - String[] defaultArray = (String[]) getDefaultParameterValue(0); - assertEquals(0, defaultArray.length); - } - } - - public void testStringArrayDefaultValue() { - new StringArrayDefaultValueChecker().check(); - } - - private static class IntArrayDefaultValueChecker - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(int[] array, String s) { - calledWith(array, s); - } - - void check() { - runTester(); - int[] defaultArray = (int[]) getDefaultParameterValue(0); - assertEquals(0, defaultArray.length); - } - } - - public void testIntArrayDefaultValue() { - new IntArrayDefaultValueChecker().check(); - } - - private enum EmptyEnum {} - - private static class EmptyEnumDefaultValueChecker - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(EmptyEnum object, String s) { - calledWith(object, s); - } - - void check() { - try { - runTester(); - } catch (AssertionError expected) { - return; - } - fail("Should have failed because enum has no constant"); - } - } - - public void testEmptyEnumDefaultValue() { - new EmptyEnumDefaultValueChecker().check(); - } - - private static class GenericClassTypeDefaultValueChecker - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(Class<? extends List<?>> cls, String s) { - calledWith(cls, s); - } - - void check() { - runTester(); - Class<?> defaultClass = (Class<?>) getDefaultParameterValue(0); - assertEquals(List.class, defaultClass); - } - } - - public void testGenericClassDefaultValue() { - new GenericClassTypeDefaultValueChecker().check(); - } - - private static class NonGenericClassTypeDefaultValueChecker - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(@SuppressWarnings("rawtypes") Class cls, String s) { - calledWith(cls, s); - } - - void check() { - runTester(); - Class<?> defaultClass = (Class<?>) getDefaultParameterValue(0); - assertEquals(Object.class, defaultClass); - } - } - - public void testNonGenericClassDefaultValue() { - new NonGenericClassTypeDefaultValueChecker().check(); - } - - private static class GenericTypeTokenDefaultValueChecker - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray( - TypeToken<? extends List<? super Number>> type, String s) { - calledWith(type, s); - } - - void check() { - runTester(); - TypeToken<?> defaultType = (TypeToken<?>) getDefaultParameterValue(0); - assertTrue(new TypeToken<List<? super Number>>() {} - .isAssignableFrom(defaultType)); - } - } - - public void testGenericTypeTokenDefaultValue() { - new GenericTypeTokenDefaultValueChecker().check(); - } - - private static class NonGenericTypeTokenDefaultValueChecker - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray( - @SuppressWarnings("rawtypes") TypeToken type, String s) { - calledWith(type, s); - } - - void check() { - runTester(); - TypeToken<?> defaultType = (TypeToken<?>) getDefaultParameterValue(0); - assertEquals(new TypeToken<Object>() {}, defaultType); - } - } - - public void testNonGenericTypeTokenDefaultValue() { - new NonGenericTypeTokenDefaultValueChecker().check(); - } - - private interface FromTo<F, T> extends Function<F, T> {} - - private static class GenericInterfaceDefaultValueChecker - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(FromTo<String, Integer> f, String s) { - calledWith(f, s); - } - - void check() { - runTester(); - FromTo<?, ?> defaultFunction = (FromTo<?, ?>) getDefaultParameterValue(0); - assertEquals(0, defaultFunction.apply(null)); - } - } - - public void testGenericInterfaceDefaultValue() { - new GenericInterfaceDefaultValueChecker().check(); - } - - private interface NullRejectingFromTo<F, T> extends Function<F, T> { - @Override public abstract T apply(F from); - } - - private static class NullRejectingInterfaceDefaultValueChecker - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(NullRejectingFromTo<String, Integer> f, String s) { - calledWith(f, s); - } - - void check() { - runTester(); - NullRejectingFromTo<?, ?> defaultFunction = (NullRejectingFromTo<?, ?>) - getDefaultParameterValue(0); - assertNotNull(defaultFunction); - try { - defaultFunction.apply(null); - fail("Proxy Should have rejected null"); - } catch (NullPointerException expected) {} - } - } - - public void testNullRejectingInterfaceDefaultValue() { - new NullRejectingInterfaceDefaultValueChecker().check(); - } - - private static class MultipleInterfacesDefaultValueChecker - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public <T extends FromTo<String, Integer> & Supplier<Long>> void checkArray( - T f, String s) { - calledWith(f, s); - } - - void check() { - runTester(); - FromTo<?, ?> defaultFunction = (FromTo<?, ?>) getDefaultParameterValue(0); - assertEquals(0, defaultFunction.apply(null)); - Supplier<?> defaultSupplier = (Supplier<?>) defaultFunction; - assertEquals(Long.valueOf(0), defaultSupplier.get()); - } - } - - public void testMultipleInterfacesDefaultValue() { - new MultipleInterfacesDefaultValueChecker().check(); - } - - private static class GenericInterface2DefaultValueChecker - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(FromTo<String, FromTo<Integer, String>> f, String s) { - calledWith(f, s); - } - - void check() { - runTester(); - FromTo<?, ?> defaultFunction = (FromTo<?, ?>) getDefaultParameterValue(0); - FromTo<?, ?> returnValue = (FromTo<?, ?>) defaultFunction.apply(null); - assertEquals("", returnValue.apply(null)); - } - } - - public void tesGenericInterfaceReturnedByGenericMethod() { - new GenericInterface2DefaultValueChecker().check(); - } - - private static abstract class AbstractGenericDefaultValueChecker<T> - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkGeneric(T value, String s) { - calledWith(value, s); - } - } - - private static class GenericDefaultValueResolvedToStringChecker - extends AbstractGenericDefaultValueChecker<String> { - void check() { - runTester(); - assertEquals("", getDefaultParameterValue(0)); - } - } - - public void testGenericTypeResolvedForDefaultValue() { - new GenericDefaultValueResolvedToStringChecker().check(); - } - - private static abstract - class AbstractGenericDefaultValueForPackagePrivateMethodChecker<T> - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - void checkGeneric(T value, String s) { - calledWith(value, s); - } - } - - private static - class DefaultValueForPackagePrivateMethodResolvedToStringChecker - extends AbstractGenericDefaultValueForPackagePrivateMethodChecker<String> - { - void check() { - runTester(); - assertEquals("", getDefaultParameterValue(0)); - } - } - - public void testDefaultValueResolvedForPackagePrivateMethod() { - new DefaultValueForPackagePrivateMethodResolvedToStringChecker().check(); - } - - private static class VisibilityMethods { - - @SuppressWarnings("unused") // Called by reflection - private void privateMethod() {} - - @SuppressWarnings("unused") // Called by reflection - void packagePrivateMethod() {} - - @SuppressWarnings("unused") // Called by reflection - protected void protectedMethod() {} - - @SuppressWarnings("unused") // Called by reflection - public void publicMethod() {} - } - - public void testVisibility_public() throws Exception { - assertFalse(Visibility.PUBLIC.isVisible( - VisibilityMethods.class.getDeclaredMethod("privateMethod"))); - assertFalse(Visibility.PUBLIC.isVisible( - VisibilityMethods.class.getDeclaredMethod("packagePrivateMethod"))); - assertFalse(Visibility.PUBLIC.isVisible( - VisibilityMethods.class.getDeclaredMethod("protectedMethod"))); - assertTrue(Visibility.PUBLIC.isVisible( - VisibilityMethods.class.getDeclaredMethod("publicMethod"))); - } - - public void testVisibility_protected() throws Exception { - assertFalse(Visibility.PROTECTED.isVisible( - VisibilityMethods.class.getDeclaredMethod("privateMethod"))); - assertFalse(Visibility.PROTECTED.isVisible( - VisibilityMethods.class.getDeclaredMethod("packagePrivateMethod"))); - assertTrue(Visibility.PROTECTED.isVisible( - VisibilityMethods.class.getDeclaredMethod("protectedMethod"))); - assertTrue(Visibility.PROTECTED.isVisible( - VisibilityMethods.class.getDeclaredMethod("publicMethod"))); - } - - public void testVisibility_package() throws Exception { - assertFalse(Visibility.PACKAGE.isVisible( - VisibilityMethods.class.getDeclaredMethod("privateMethod"))); - assertTrue(Visibility.PACKAGE.isVisible( - VisibilityMethods.class.getDeclaredMethod("packagePrivateMethod"))); - assertTrue(Visibility.PACKAGE.isVisible( - VisibilityMethods.class.getDeclaredMethod("protectedMethod"))); - assertTrue(Visibility.PACKAGE.isVisible( - VisibilityMethods.class.getDeclaredMethod("publicMethod"))); - } - - private class Inner { - public Inner(String s) { - checkNotNull(s); - } - } - - public void testNonStaticInnerClass() { - try { - new NullPointerTester().testAllPublicConstructors(Inner.class); - fail(); - } catch (IllegalArgumentException expected) { - ASSERT.that(expected.getMessage()).contains("inner class"); - } - } - - /* - * - * TODO(kevinb): This is only a very small start. - * Must come back and finish. - * - */ - -} diff --git a/guava-testlib/test/com/google/common/testing/PackageSanityTests.java b/guava-testlib/test/com/google/common/testing/PackageSanityTests.java deleted file mode 100644 index a5b329c..0000000 --- a/guava-testlib/test/com/google/common/testing/PackageSanityTests.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * 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.testing; - -/** - * Test nulls for the entire package. - */ - -public class PackageSanityTests extends AbstractPackageSanityTests {} diff --git a/guava-testlib/test/com/google/common/testing/RelationshipTesterTest.java b/guava-testlib/test/com/google/common/testing/RelationshipTesterTest.java deleted file mode 100644 index 3c68f09..0000000 --- a/guava-testlib/test/com/google/common/testing/RelationshipTesterTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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.testing; - -import com.google.common.testing.RelationshipTester.ItemReporter; -import com.google.common.testing.RelationshipTester.RelationshipAssertion; - -import junit.framework.TestCase; - -/** - * Tests for {@link RelationshipTester}. - * - * @author Ben Yu - */ -public class RelationshipTesterTest extends TestCase { - - public void testNulls(){ - new ClassSanityTester() - .setDefault(RelationshipAssertion.class, new RelationshipAssertion<Object>() { - @Override void assertRelated(Object item, Object related) {} - @Override void assertUnrelated(Object item, Object unrelated) {} - }) - .setDefault(ItemReporter.class, new ItemReporter()) - .testNulls(RelationshipTester.class); - } -} diff --git a/guava-testlib/test/com/google/common/testing/SerializableTesterTest.java b/guava-testlib/test/com/google/common/testing/SerializableTesterTest.java deleted file mode 100644 index d62860b..0000000 --- a/guava-testlib/test/com/google/common/testing/SerializableTesterTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2009 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.testing; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import java.io.Serializable; - -/** - * Tests for {@link SerializableTester}. - * - * @author Nick Kralevich - */ -public class SerializableTesterTest extends TestCase { - public void testStringAssertions() { - String original = "hello world"; - String copy = SerializableTester.reserializeAndAssert(original); - assertEquals(original, copy); - assertNotSame(original, copy); - } - - public void testClassWhichDoesNotImplementEquals() { - ClassWhichDoesNotImplementEquals orig = - new ClassWhichDoesNotImplementEquals(); - boolean errorNotThrown = false; - try { - SerializableTester.reserializeAndAssert(orig); - errorNotThrown = true; - } catch (AssertionFailedError error) { - // expected - assertContains("must be equal to", error.getMessage()); - } - assertFalse(errorNotThrown); - } - - public void testClassWhichIsAlwaysEqualButHasDifferentHashcodes() { - ClassWhichIsAlwaysEqualButHasDifferentHashcodes orig = - new ClassWhichIsAlwaysEqualButHasDifferentHashcodes(); - boolean errorNotThrown = false; - try { - SerializableTester.reserializeAndAssert(orig); - errorNotThrown = true; - } catch (AssertionFailedError error) { - // expected - assertContains("must be equal to the hash", error.getMessage()); - } - assertFalse(errorNotThrown); - } - - public void testObjectWhichIsEqualButChangesClass() { - ObjectWhichIsEqualButChangesClass orig = - new ObjectWhichIsEqualButChangesClass(); - boolean errorNotThrown = false; - try { - SerializableTester.reserializeAndAssert(orig); - errorNotThrown = true; - } catch (AssertionFailedError error) { - // expected - assertContains("expected:<class ", error.getMessage()); - } - assertFalse(errorNotThrown); - } - - private static class ClassWhichDoesNotImplementEquals - implements Serializable { - private static final long serialVersionUID = 1L; - } - - private static class ClassWhichIsAlwaysEqualButHasDifferentHashcodes - implements Serializable { - private static final long serialVersionUID = 2L; - - @Override - public boolean equals(Object other) { - return (other instanceof ClassWhichIsAlwaysEqualButHasDifferentHashcodes); - } - } - - private static class ObjectWhichIsEqualButChangesClass - implements Serializable { - private static final long serialVersionUID = 1L; - - @Override - public boolean equals(Object other) { - return (other instanceof ObjectWhichIsEqualButChangesClass - || other instanceof OtherForm); - } - - @Override - public int hashCode() { - return 1; - } - - private Object writeReplace() { - return new OtherForm(); - } - - private static class OtherForm implements Serializable { - @Override - public boolean equals(Object other) { - return (other instanceof ObjectWhichIsEqualButChangesClass - || other instanceof OtherForm); - } - - @Override - public int hashCode() { - return 1; - } - } - } - - private static void assertContains(String expectedSubstring, String actual) { - // TODO(kevinb): use a Truth assertion here - if (!actual.contains(expectedSubstring)) { - fail("expected <" + actual + "> to contain <" + expectedSubstring + ">"); - } - } -} diff --git a/guava-testlib/test/com/google/common/testing/TearDownStackTest.java b/guava-testlib/test/com/google/common/testing/TearDownStackTest.java deleted file mode 100644 index 8a0a8f3..0000000 --- a/guava-testlib/test/com/google/common/testing/TearDownStackTest.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * 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.testing; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import com.google.common.annotations.GwtCompatible; - -import junit.framework.TestCase; - -import org.junit.Test; - -/** - * @author Luiz-Otavio "Z" Zorzella - */ -@GwtCompatible -public class TearDownStackTest extends TestCase { - - private TearDownStack tearDownStack = new TearDownStack(); - - @Test - public void testSingleTearDown() throws Exception { - final TearDownStack stack = buildTearDownStack(); - - final SimpleTearDown tearDown = new SimpleTearDown(); - stack.addTearDown(tearDown); - - assertEquals(false, tearDown.ran); - - stack.runTearDown(); - - assertEquals("tearDown should have run", true, tearDown.ran); - } - - @Test - public void testMultipleTearDownsHappenInOrder() throws Exception { - final TearDownStack stack = buildTearDownStack(); - - final SimpleTearDown tearDownOne = new SimpleTearDown(); - stack.addTearDown(tearDownOne); - - final Callback callback = new Callback() { - @Override - public void run() { - assertEquals("tearDownTwo should have been run before tearDownOne", - false, tearDownOne.ran); - } - }; - - final SimpleTearDown tearDownTwo = new SimpleTearDown(callback); - stack.addTearDown(tearDownTwo); - - assertEquals(false, tearDownOne.ran); - assertEquals(false, tearDownTwo.ran); - - stack.runTearDown(); - - assertEquals("tearDownOne should have run", true, tearDownOne.ran); - assertEquals("tearDownTwo should have run", true, tearDownTwo.ran); - } - - @Test - public void testThrowingTearDown() throws Exception { - final TearDownStack stack = buildTearDownStack(); - - final ThrowingTearDown tearDownOne = new ThrowingTearDown("one"); - stack.addTearDown(tearDownOne); - - final ThrowingTearDown tearDownTwo = new ThrowingTearDown("two"); - stack.addTearDown(tearDownTwo); - - assertEquals(false, tearDownOne.ran); - assertEquals(false, tearDownTwo.ran); - - try { - stack.runTearDown(); - fail("runTearDown should have thrown an exception"); - } catch (ClusterException expected) { - assertEquals("two", expected.getCause().getMessage()); - } catch (RuntimeException e) { - throw new RuntimeException( - "A ClusterException should have been thrown, rather than a " + e.getClass().getName(), e); - } - - assertEquals(true, tearDownOne.ran); - assertEquals(true, tearDownTwo.ran); - } - - @Override public final void runBare() throws Throwable { - try { - setUp(); - runTest(); - } finally { - tearDown(); - } - } - - @Override protected void tearDown() { - tearDownStack.runTearDown(); - } - - /** - * Builds a {@link TearDownStack} that makes sure it's clear by the end of - * this test. - */ - private TearDownStack buildTearDownStack() { - final TearDownStack result = new TearDownStack(); - tearDownStack.addTearDown(new TearDown() { - - @Override - public void tearDown() throws Exception { - assertEquals( - "The test should have cleared the stack (say, by virtue of running runTearDown)", - 0, result.stack.size()); - } - }); - return result; - } - - private static final class ThrowingTearDown implements TearDown { - - private final String id; - boolean ran = false; - - ThrowingTearDown(String id) { - this.id = id; - } - - @Override - public void tearDown() throws Exception { - ran = true; - throw new RuntimeException(id); - } - } - - private static final class SimpleTearDown implements TearDown { - - boolean ran = false; - Callback callback = null; - - public SimpleTearDown() {} - - public SimpleTearDown(Callback callback) { - this.callback = callback; - } - - @Override - public void tearDown() throws Exception { - if (callback != null) { - callback.run(); - } - ran = true; - } - } - - private interface Callback { - void run(); - } -} diff --git a/guava-testlib/test/com/google/common/testing/TestLogHandlerTest.java b/guava-testlib/test/com/google/common/testing/TestLogHandlerTest.java deleted file mode 100644 index f193e1f..0000000 --- a/guava-testlib/test/com/google/common/testing/TestLogHandlerTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2008 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.testing; - -import junit.framework.TestCase; - -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.Logger; - -/** - * Unit test for {@link TestLogHandler}. - * - * @author kevinb - */ -public class TestLogHandlerTest extends TestCase { - - private TestLogHandler handler; - private TearDownStack stack = new TearDownStack(); - - @Override protected void setUp() throws Exception { - super.setUp(); - - handler = new TestLogHandler(); - - // You could also apply it higher up the Logger hierarchy than this - ExampleClassUnderTest.logger.addHandler(handler); - - ExampleClassUnderTest.logger.setUseParentHandlers(false); // optional - - stack.addTearDown(new TearDown() { - @Override - public void tearDown() throws Exception { - ExampleClassUnderTest.logger.setUseParentHandlers(true); - ExampleClassUnderTest.logger.removeHandler(handler); - } - }); - } - - public void test() throws Exception { - assertTrue(handler.getStoredLogRecords().isEmpty()); - ExampleClassUnderTest.foo(); - LogRecord record = handler.getStoredLogRecords().iterator().next(); - assertEquals(Level.INFO, record.getLevel()); - assertEquals("message", record.getMessage()); - assertSame(EXCEPTION, record.getThrown()); - } - - public void testConcurrentModification() throws Exception { - // Tests for the absence of a bug where logging while iterating over the - // stored log records causes a ConcurrentModificationException - assertTrue(handler.getStoredLogRecords().isEmpty()); - ExampleClassUnderTest.foo(); - ExampleClassUnderTest.foo(); - for (LogRecord record : handler.getStoredLogRecords()) { - ExampleClassUnderTest.foo(); - } - } - - @Override public final void runBare() throws Throwable { - try { - setUp(); - runTest(); - } finally { - tearDown(); - } - } - - @Override protected void tearDown() { - stack.runTearDown(); - } - - static final Exception EXCEPTION = new Exception(); - - static class ExampleClassUnderTest { - static final Logger logger - = Logger.getLogger(ExampleClassUnderTest.class.getName()); - - static void foo() { - logger.log(Level.INFO, "message", EXCEPTION); - } - } -} diff --git a/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java b/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java deleted file mode 100644 index f9016d1..0000000 --- a/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java +++ /dev/null @@ -1,453 +0,0 @@ -/* - * 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.testing.anotherpackage; - -import static org.truth0.Truth.ASSERT; - -import com.google.common.base.Equivalence; -import com.google.common.base.Function; -import com.google.common.base.Functions; -import com.google.common.base.Joiner; -import com.google.common.base.Predicate; -import com.google.common.collect.Ordering; -import com.google.common.primitives.UnsignedInteger; -import com.google.common.primitives.UnsignedLong; -import com.google.common.testing.ForwardingWrapperTester; -import com.google.common.testing.NullPointerTester; - -import junit.framework.TestCase; - -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; -import java.util.regex.Pattern; - -/** - * Tests for {@link ForwardingWrapperTester}. Live in a different package to detect reflection - * access issues, if any. - * - * @author Ben Yu - */ -public class ForwardingWrapperTesterTest extends TestCase { - - private final ForwardingWrapperTester tester = new ForwardingWrapperTester(); - - public void testGoodForwarder() { - tester.testForwarding(Arithmetic.class, - new Function<Arithmetic, Arithmetic>() { - @Override public Arithmetic apply(Arithmetic arithmetic) { - return new ForwardingArithmetic(arithmetic); - } - }); - tester.testForwarding(ParameterTypesDifferent.class, - new Function<ParameterTypesDifferent, ParameterTypesDifferent>() { - @Override public ParameterTypesDifferent apply(ParameterTypesDifferent delegate) { - return new ParameterTypesDifferentForwarder(delegate); - } - }); - } - - public void testVoidMethodForwarding() { - tester.testForwarding(Runnable.class, - new Function<Runnable, Runnable>() { - @Override public Runnable apply(final Runnable runnable) { - return new ForwardingRunnable(runnable); - } - }); - } - - public void testToStringForwarding() { - tester.testForwarding(Runnable.class, - new Function<Runnable, Runnable>() { - @Override public Runnable apply(final Runnable runnable) { - return new ForwardingRunnable(runnable) { - @Override public String toString() { - return runnable.toString(); - } - }; - } - }); - } - - public void testFailsToForwardToString() { - assertFailure(Runnable.class, new Function<Runnable, Runnable>() { - @Override public Runnable apply(final Runnable runnable) { - return new ForwardingRunnable(runnable) { - @Override public String toString() { - return ""; - } - }; - } - }, "toString()"); - } - - public void testFailsToForwardHashCode() { - tester.includingEquals(); - assertFailure(Runnable.class, new Function<Runnable, Runnable>() { - @Override public Runnable apply(final Runnable runnable) { - return new ForwardingRunnable(runnable) { - @Override public boolean equals(Object o) { - if (o instanceof ForwardingRunnable) { - ForwardingRunnable that = (ForwardingRunnable) o; - return runnable.equals(that.runnable); - } - return false; - } - }; - } - }, "Runnable"); - } - - public void testEqualsAndHashCodeForwarded() { - tester.includingEquals(); - tester.testForwarding(Runnable.class, new Function<Runnable, Runnable>() { - @Override public Runnable apply(final Runnable runnable) { - return new ForwardingRunnable(runnable) { - @Override public boolean equals(Object o) { - if (o instanceof ForwardingRunnable) { - ForwardingRunnable that = (ForwardingRunnable) o; - return runnable.equals(that.runnable); - } - return false; - } - @Override public int hashCode() { - return runnable.hashCode(); - } - }; - } - }); - } - - public void testFailsToForwardEquals() { - tester.includingEquals(); - assertFailure(Runnable.class, new Function<Runnable, Runnable>() { - @Override public Runnable apply(final Runnable runnable) { - return new ForwardingRunnable(runnable) { - @Override public int hashCode() { - return runnable.hashCode(); - } - }; - } - }, "Runnable"); - } - - public void testFailsToForward() { - assertFailure(Runnable.class, - new Function<Runnable, Runnable>() { - @Override public Runnable apply(Runnable runnable) { - return new ForwardingRunnable(runnable) { - @Override public void run() {} - }; - } - }, "run()", "Failed to forward"); - } - - public void testRedundantForwarding() { - assertFailure(Runnable.class, - new Function<Runnable, Runnable>() { - @Override public Runnable apply(final Runnable runnable) { - return new Runnable() { - @Override public void run() { - runnable.run(); - runnable.run(); - } - }; - } - }, "run()", "invoked more than once"); - } - - public void testFailsToForwardParameters() { - assertFailure(Adder.class, new Function<Adder, Adder>() { - @Override public Adder apply(Adder adder) { - return new FailsToForwardParameters(adder); - } - }, "add(", "Parameter #0"); - } - - public void testForwardsToTheWrongMethod() { - assertFailure(Arithmetic.class, new Function<Arithmetic, Arithmetic>() { - @Override public Arithmetic apply(Arithmetic adder) { - return new ForwardsToTheWrongMethod(adder); - } - }, "minus"); - } - - public void testFailsToForwardReturnValue() { - assertFailure(Adder.class, new Function<Adder, Adder>() { - @Override public Adder apply(Adder adder) { - return new FailsToForwardReturnValue(adder); - } - }, "add(", "Return value"); - } - - public void testFailsToPropagateException() { - assertFailure(Adder.class, new Function<Adder, Adder>() { - @Override public Adder apply(Adder adder) { - return new FailsToPropagageException(adder); - } - }, "add(", "exception"); - } - - public void testNotInterfaceType() { - try { - new ForwardingWrapperTester().testForwarding(String.class, Functions.<String>identity()); - fail(); - } catch (IllegalArgumentException expected) {} - } - - public void testNulls() { - new NullPointerTester() - .setDefault(Class.class, Runnable.class) - .testAllPublicInstanceMethods(new ForwardingWrapperTester()); - } - - private <T> void assertFailure( - Class<T> interfaceType, Function<T, ? extends T> wrapperFunction, - String... expectedMessages) { - try { - tester.testForwarding(interfaceType, wrapperFunction); - } catch (AssertionError expected) { - for (String message : expectedMessages) { - ASSERT.that(expected.getMessage()).contains(message); - } - return; - } - fail("expected failure not reported"); - } - - private class ForwardingRunnable implements Runnable { - - private final Runnable runnable; - - ForwardingRunnable(Runnable runnable) { - this.runnable = runnable; - } - - @Override public void run() { - runnable.run(); - } - - @Override public String toString() { - return runnable.toString(); - } - } - - private interface Adder { - int add(int a, int b); - } - - private static class ForwardingArithmetic implements Arithmetic { - private final Arithmetic arithmetic; - - public ForwardingArithmetic(Arithmetic arithmetic) { - this.arithmetic = arithmetic; - } - - @Override public int add(int a, int b) { - return arithmetic.add(a, b); - } - - @Override public int minus(int a, int b) { - return arithmetic.minus(a, b); - } - - @Override public String toString() { - return arithmetic.toString(); - } - } - - private static class FailsToForwardParameters implements Adder { - private final Adder adder; - - FailsToForwardParameters(Adder adder) { - this.adder = adder; - } - - @Override public int add(int a, int b) { - return adder.add(b, a); - } - - @Override public String toString() { - return adder.toString(); - } - } - - private static class FailsToForwardReturnValue implements Adder { - private final Adder adder; - - FailsToForwardReturnValue(Adder adder) { - this.adder = adder; - } - - @Override public int add(int a, int b) { - return adder.add(a, b) + 1; - } - - @Override public String toString() { - return adder.toString(); - } - } - - private static class FailsToPropagageException implements Adder { - private final Adder adder; - - FailsToPropagageException(Adder adder) { - this.adder = adder; - } - - @Override public int add(int a, int b) { - try { - return adder.add(a, b); - } catch (Exception e) { - // swallow! - return 0; - } - } - - @Override public String toString() { - return adder.toString(); - } - } - - public interface Arithmetic extends Adder { - int minus(int a, int b); - } - - private static class ForwardsToTheWrongMethod implements Arithmetic { - private final Arithmetic arithmetic; - - ForwardsToTheWrongMethod(Arithmetic arithmetic) { - this.arithmetic = arithmetic; - } - - @Override public int minus(int a, int b) { // bad! - return arithmetic.add(b, a); - } - - @Override public int add(int a, int b) { - return arithmetic.add(b, a); - } - - @Override public String toString() { - return arithmetic.toString(); - } - } - - private interface ParameterTypesDifferent { - void foo(String s, Runnable r, Number n, Iterable<?> it, boolean b, Equivalence<String> eq, - Exception e, InputStream in, Comparable<?> c, Ordering<Integer> ord, - Charset charset, TimeUnit unit, Class<?> cls, Joiner joiner, - Pattern pattern, UnsignedInteger ui, UnsignedLong ul, StringBuilder sb, - Predicate<?> pred, Function<?, ?> func, Object obj); - } - - private static class ParameterTypesDifferentForwarder implements ParameterTypesDifferent { - private final ParameterTypesDifferent delegate; - - public ParameterTypesDifferentForwarder(ParameterTypesDifferent delegate) { - this.delegate = delegate; - } - - @Override public void foo( - String s, Runnable r, Number n, Iterable<?> it, boolean b, Equivalence<String> eq, - Exception e, InputStream in, Comparable<?> c, Ordering<Integer> ord, - Charset charset, TimeUnit unit, Class<?> cls, Joiner joiner, - Pattern pattern, UnsignedInteger ui, UnsignedLong ul, StringBuilder sb, - Predicate<?> pred, Function<?, ?> func, Object obj) { - delegate.foo(s, - r, n, it, b, eq, e, in, c, ord, charset, unit, cls, joiner, pattern, - ui, ul, sb, pred, func, obj); - } - - @Override public String toString() { - return delegate.toString(); - } - } - - public void testCovariantReturn() { - new ForwardingWrapperTester().testForwarding(Sub.class, new Function<Sub, Sub>() { - @Override public Sub apply(Sub sub) { - return new ForwardingSub(sub); - } - }); - } - - interface Base { - CharSequence getId(); - } - - interface Sub extends Base { - @Override String getId(); - } - - private static class ForwardingSub implements Sub { - private final Sub delegate; - - ForwardingSub(Sub delegate) { - this.delegate = delegate; - } - - @Override public String getId() { - return delegate.getId(); - } - - @Override public String toString() { - return delegate.toString(); - } - } - - private interface Equals { - @Override boolean equals(Object obj); - @Override int hashCode(); - @Override String toString(); - } - - private static class NoDelegateToEquals implements Equals { - - private static Function<Equals, Equals> WRAPPER = new Function<Equals, Equals>() { - @Override public NoDelegateToEquals apply(Equals delegate) { - return new NoDelegateToEquals(delegate); - } - }; - - private final Equals delegate; - - NoDelegateToEquals(Equals delegate) { - this.delegate = delegate; - } - - @Override public String toString() { - return delegate.toString(); - } - } - - public void testExplicitEqualsAndHashCodeNotDelegatedByDefault() { - new ForwardingWrapperTester() - .testForwarding(Equals.class, NoDelegateToEquals.WRAPPER); - } - - public void testExplicitEqualsAndHashCodeDelegatedWhenExplicitlyAsked() { - try { - new ForwardingWrapperTester() - .includingEquals() - .testForwarding(Equals.class, NoDelegateToEquals.WRAPPER); - } catch (AssertionError expected) { - return; - } - fail("Should have failed"); - } -} diff --git a/guava-testlib/test/com/google/common/testing/anotherpackage/SomeClassThatDoesNotUseNullable.java b/guava-testlib/test/com/google/common/testing/anotherpackage/SomeClassThatDoesNotUseNullable.java deleted file mode 100644 index 6a17d1e..0000000 --- a/guava-testlib/test/com/google/common/testing/anotherpackage/SomeClassThatDoesNotUseNullable.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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.testing.anotherpackage; - -/** Does not check null, but should not matter since it's in a different package. */ -@SuppressWarnings("unused") // For use by NullPointerTester -public class SomeClassThatDoesNotUseNullable { - - void packagePrivateButDoesNotCheckNull(String s) {} - - protected void protectedButDoesNotCheckNull(String s) {} - - public void publicButDoesNotCheckNull(String s) {} - - public static void staticButDoesNotCheckNull(String s) {} -} diff --git a/guava-testlib/test/com/google/common/util/concurrent/testing/TestingExecutorsTest.java b/guava-testlib/test/com/google/common/util/concurrent/testing/TestingExecutorsTest.java deleted file mode 100644 index 4a07967..0000000 --- a/guava-testlib/test/com/google/common/util/concurrent/testing/TestingExecutorsTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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.util.concurrent.testing; - -import com.google.common.collect.ImmutableList; -import com.google.common.util.concurrent.ListeningScheduledExecutorService; - -import junit.framework.TestCase; - -import java.lang.InterruptedException; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -/** - * Tests for TestingExecutors. - * - * @author Eric Chang - */ -public class TestingExecutorsTest extends TestCase { - private volatile boolean taskDone; - - public void testNoOpScheduledExecutor() throws InterruptedException { - taskDone = false; - Runnable task = new Runnable() { - @Override public void run() { - taskDone = true; - } - }; - ScheduledFuture<?> future = TestingExecutors.noOpScheduledExecutor().schedule( - task, 10, TimeUnit.MILLISECONDS); - Thread.sleep(20); - assertFalse(taskDone); - assertFalse(future.isDone()); - } - - public void testNoOpScheduledExecutorShutdown() { - ListeningScheduledExecutorService executor = TestingExecutors.noOpScheduledExecutor(); - assertFalse(executor.isShutdown()); - assertFalse(executor.isTerminated()); - executor.shutdown(); - assertTrue(executor.isShutdown()); - assertTrue(executor.isTerminated()); - } - - public void testNoOpScheduledExecutorInvokeAll() throws ExecutionException, InterruptedException { - ListeningScheduledExecutorService executor = TestingExecutors.noOpScheduledExecutor(); - taskDone = false; - Callable<Boolean> task = new Callable<Boolean>() { - @Override public Boolean call() { - taskDone = true; - return taskDone; - } - }; - List<Future<Boolean>> futureList = executor.invokeAll( - ImmutableList.of(task), 10, TimeUnit.MILLISECONDS); - Future<Boolean> future = futureList.get(0); - assertFalse(taskDone); - assertTrue(future.isDone()); - try { - future.get(); - fail(); - } catch (CancellationException e) { - // pass - } - } -} |