From 7a0fab3efd2104144dff752da334f8fa8a82951d Mon Sep 17 00:00:00 2001 From: Diego Marquez Date: Thu, 6 Feb 2025 16:34:05 -0500 Subject: [PATCH] feat: Update and adapt to GraalVM for JDK 23 (#2069) * build(deps): update dependency com.google.cloud:native-image-shared-config to v1.14.0 * disable testDisconnectShouldNotWaitToReadResponse for JDK >= 23 * fix assumption code * fix assumption ii * Revert "fix assumption ii" This reverts commit 2fbd4cb4721e8c89e47b436c988625731e7cb44e. * Revert "fix assumption code" This reverts commit d3557409adffaaa6ef4cf3e1f894b8bc030fd606. * Revert "disable testDisconnectShouldNotWaitToReadResponse for JDK >= 23" This reverts commit e2c988e45f83c2baf830a393b871d3bbcb40a37d. * chore: use JUnit4 in tests this is basically not rely on extending TestCase and using @Test annotations * use at least 1 Junit38 test * Revert "use at least 1 Junit38 test" This reverts commit 84f3f4f3619728917b0fb242e8de23ac88a55afc. * fix net http response tests * annotate tests with @RunWith(JUnit4.class) * initialize static members in static block * use static blocks to initialize test classes * format * set up class initialization * convert google-http-client-test to JUnit4 * use java.nio for tests * run with JUnit 4 explicitly * use static block * Revert "use static block" This reverts commit 73ebee2dfd5e097667608acde84943ab679f258f. * Reapply "use static block" This reverts commit 06acc4a5c30cb99bcc887cd78fa79df003ada591. * initialize IS_WINDOWS at build time * prevent cryptic message when initializing FileDataStoreFactory * fix static initialization in AbstractDatastoreFactory * test no IS_WINDOWS * Revert "test no IS_WINDOWS" This reverts commit 3f6483de2192a7c9e147a8fa354cfccbffcb9525. * ruling out logger initialization * add test output * safe initialization of ID_PATTERN * remove provided scope depdendency * convert appengine transport to JUnit 4 * add clirr differences * include appengine classes in runtime this allows native compilation * add native config * add reflect-config for appengine * use JUnit4 in GSON tests * fix clirr * port abstract json parser test to JUnit4 * remove unused imports * update clirr again * add native config to gson module * convert jackson module to JUnit4 * make jackson factory instantiation native friendly * config test-only build-time initialization * adapt protocol buffers module to JUnit 4 * initialize test classes at test time * convert xml module to JUnit4 * add test time initialization entries to xml module * format * restore debug setup * add junit test time initialization flags * add junit to gson deps * add junit test-scoped dependency to jackson2 module * add jackson factory to class initialization this is due to one of the test classes statically initializing this factory. * add app engine feature * try setup time feature registration * Revert "try setup time feature registration" This reverts commit eeb9352a031564eb02ef52eab0f6cc4a3b296f5f. * Revert "add app engine feature" This reverts commit e75875b34ab2156f7f6d4b6c66a92dd3d9990489. * add app engine core lib for testing this allows these classes to be included for native testing * add test-scoped dep in test module * use -Pnative-deps * add conflicting dep in native-deps profile for appengine * include appengine in graalvm tests * restore static blocks in google-http-client * restore static blocks in gson module * restore static blocks in jackson * restore static blocks in protobuf * format * restore static initailization in xml module * restore static block in jackson module * format * remove app engine from test --------- Co-authored-by: Mend Renovate --- .kokoro/presubmit/graalvm-native-a.cfg | 2 +- .kokoro/presubmit/graalvm-native-b.cfg | 2 +- google-http-client-appengine/pom.xml | 11 + .../reflect-config.json | 47 +++ .../appengine/http/UrlFetchTransportTest.java | 5 + .../native-image.properties | 1 + google-http-client-gson/pom.xml | 5 + .../api/client/json/gson/GsonFactoryTest.java | 15 +- .../native-image.properties | 1 + google-http-client-jackson2/pom.xml | 5 + .../json/jackson2/JacksonFactoryTest.java | 13 +- .../native-image.properties | 9 +- .../native-image.properties | 1 + .../client/protobuf/ProtocolBuffersTest.java | 10 +- .../clirr-ignored-differences.xml | 75 ++++ .../test/json/AbstractJsonFactoryTest.java | 352 ++++++++++++++---- .../test/json/AbstractJsonGeneratorTest.java | 11 +- .../test/json/AbstractJsonParserTest.java | 25 +- .../store/AbstractDataStoreFactoryTest.java | 37 +- .../native-image.properties | 1 + .../util/store/FileDataStoreFactoryTest.java | 12 +- .../store/MemoryDataStoreFactoryTest.java | 3 + .../com/google/api/client/xml/AtomTest.java | 3 + .../api/client/xml/GenericXmlListTest.java | 3 + .../google/api/client/xml/GenericXmlTest.java | 3 + .../google/api/client/xml/XmlEnumTest.java | 3 + .../google/api/client/xml/XmlListTest.java | 3 + .../xml/XmlNamespaceDictionaryTest.java | 28 +- .../com/google/api/client/xml/XmlTest.java | 3 + .../native-image.properties | 1 + .../util/store/AbstractDataStoreFactory.java | 18 +- .../util/store/FileDataStoreFactory.java | 14 +- .../client/http/AbstractHttpContentTest.java | 12 +- .../client/http/BasicAuthenticationTest.java | 11 +- .../api/client/http/ByteArrayContentTest.java | 12 +- .../client/http/ConsumingInputStreamTest.java | 3 + .../api/client/http/EmptyContentTest.java | 12 +- .../http/ExponentialBackOffPolicyTest.java | 33 +- .../api/client/http/GZipEncodingTest.java | 10 +- .../api/client/http/GenericUrlTest.java | 67 +++- .../api/client/http/GzipSupportTest.java | 3 + .../HttpBackOffIOExpcetionHandlerTest.java | 12 +- ...ackOffUnsuccessfulResponseHandlerTest.java | 14 +- .../HttpEncodingStreamingContentTest.java | 10 +- .../api/client/http/HttpHeadersTest.java | 29 +- .../api/client/http/HttpMediaTypeTest.java | 33 +- .../client/http/HttpRequestFactoryTest.java | 10 +- .../api/client/http/HttpRequestTest.java | 256 ++++++++----- .../client/http/HttpRequestTracingTest.java | 3 + .../http/HttpResponseExceptionTest.java | 24 +- .../api/client/http/HttpResponseTest.java | 45 ++- .../api/client/http/HttpStatusCodesTest.java | 12 +- .../api/client/http/MultipartContentTest.java | 13 +- .../api/client/http/OpenCensusUtilsTest.java | 42 ++- .../api/client/http/UriTemplateTest.java | 36 +- .../client/http/UrlEncodedContentTest.java | 15 +- .../api/client/http/UrlEncodedParserTest.java | 23 +- .../http/javanet/NetHttpRequestTest.java | 3 + .../http/javanet/NetHttpResponseTest.java | 11 +- .../http/javanet/NetHttpTransportTest.java | 16 +- .../api/client/json/GenericJsonTest.java | 10 +- .../api/client/json/JsonObjectParserTest.java | 9 +- .../api/client/json/JsonParserTest.java | 12 +- .../json/webtoken/JsonWebSignatureTest.java | 3 + .../client/testing/http/FixedClockTest.java | 10 +- .../testing/http/MockHttpTransportTest.java | 10 +- .../http/MockLowLevelHttpRequestTest.java | 10 +- .../javanet/MockHttpUrlConnectionTest.java | 13 +- .../client/testing/util/MockBackOffTest.java | 10 +- .../google/api/client/util/ArrayMapTest.java | 30 +- .../google/api/client/util/BackOffTest.java | 10 +- .../api/client/util/BackOffUtilsTest.java | 10 +- .../google/api/client/util/Base64Test.java | 21 +- .../google/api/client/util/ClassInfoTest.java | 18 +- .../com/google/api/client/util/ClockTest.java | 11 +- .../google/api/client/util/DataMapTest.java | 20 +- .../com/google/api/client/util/DataTest.java | 27 +- .../google/api/client/util/DateTimeTest.java | 29 +- .../client/util/ExponentialBackOffTest.java | 33 +- .../google/api/client/util/FieldInfoTest.java | 13 +- .../api/client/util/GenericDataTest.java | 25 +- .../google/api/client/util/IOUtilsTest.java | 15 +- .../util/LoggingStreamingContentTest.java | 12 +- .../google/api/client/util/NanoClockTest.java | 11 +- .../google/api/client/util/ObjectsTest.java | 13 +- .../google/api/client/util/PemReaderTest.java | 8 +- .../api/client/util/SecurityUtilsTest.java | 21 +- .../api/client/util/StringUtilsTest.java | 20 +- .../com/google/api/client/util/TypesTest.java | 21 +- .../client/util/escape/CharEscapersTest.java | 13 +- .../util/escape/PercentEscaperTest.java | 3 + .../native-image.properties | 8 +- pom.xml | 2 +- 93 files changed, 1562 insertions(+), 411 deletions(-) create mode 100644 google-http-client-appengine/src/main/resources/META-INF/native-image/com.google.http-client/google-http-client-appengine/reflect-config.json create mode 100644 google-http-client-appengine/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-appengine/native-image.properties create mode 100644 google-http-client-gson/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-gson/native-image.properties create mode 100644 google-http-client-protobuf/src/main/resources/META-INF/native-image/com.google.http-client/google-http-client-protobuf/native-image.properties create mode 100644 google-http-client-test/clirr-ignored-differences.xml create mode 100644 google-http-client-test/src/main/resources/META-INF/native-image/com.google.http-client/google-http-client-test/native-image.properties create mode 100644 google-http-client-xml/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-xml/native-image.properties diff --git a/.kokoro/presubmit/graalvm-native-a.cfg b/.kokoro/presubmit/graalvm-native-a.cfg index 1b125c908..1f4b4493c 100644 --- a/.kokoro/presubmit/graalvm-native-a.cfg +++ b/.kokoro/presubmit/graalvm-native-a.cfg @@ -29,5 +29,5 @@ env_vars: { } container_properties { - docker_image: "us-docker.pkg.dev/java-graalvm-ci-prod/graalvm-integration-testing/graalvm_a:1.13.0" + docker_image: "us-docker.pkg.dev/java-graalvm-ci-prod/graalvm-integration-testing/graalvm_a:1.14.0" } diff --git a/.kokoro/presubmit/graalvm-native-b.cfg b/.kokoro/presubmit/graalvm-native-b.cfg index 40dced107..1a8dec5aa 100644 --- a/.kokoro/presubmit/graalvm-native-b.cfg +++ b/.kokoro/presubmit/graalvm-native-b.cfg @@ -29,5 +29,5 @@ env_vars: { } container_properties { - docker_image: "us-docker.pkg.dev/java-graalvm-ci-prod/graalvm-integration-testing/graalvm_b:1.13.0" + docker_image: "us-docker.pkg.dev/java-graalvm-ci-prod/graalvm-integration-testing/graalvm_b:1.14.0" } diff --git a/google-http-client-appengine/pom.xml b/google-http-client-appengine/pom.xml index d7f740df1..8947539c3 100644 --- a/google-http-client-appengine/pom.xml +++ b/google-http-client-appengine/pom.xml @@ -90,4 +90,15 @@ test + + + native-deps + + + com.google.appengine + appengine-api-1.0-sdk + + + + diff --git a/google-http-client-appengine/src/main/resources/META-INF/native-image/com.google.http-client/google-http-client-appengine/reflect-config.json b/google-http-client-appengine/src/main/resources/META-INF/native-image/com.google.http-client/google-http-client-appengine/reflect-config.json new file mode 100644 index 000000000..d2efd41b8 --- /dev/null +++ b/google-http-client-appengine/src/main/resources/META-INF/native-image/com.google.http-client/google-http-client-appengine/reflect-config.json @@ -0,0 +1,47 @@ +[ + { + "name": "com.google.apphosting.api.DatastorePb$DeleteRequest", + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.google.apphosting.api.DatastorePb$GetRequest", + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.google.apphosting.api.DatastorePb$NextRequest", + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.google.apphosting.api.DatastorePb$PutRequest", + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.google.apphosting.api.DatastorePb$Query", + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + } +] diff --git a/google-http-client-appengine/src/test/java/com/google/api/client/extensions/appengine/http/UrlFetchTransportTest.java b/google-http-client-appengine/src/test/java/com/google/api/client/extensions/appengine/http/UrlFetchTransportTest.java index 3de60a6d7..b9ce9585d 100644 --- a/google-http-client-appengine/src/test/java/com/google/api/client/extensions/appengine/http/UrlFetchTransportTest.java +++ b/google-http-client-appengine/src/test/java/com/google/api/client/extensions/appengine/http/UrlFetchTransportTest.java @@ -15,14 +15,19 @@ package com.google.api.client.extensions.appengine.http; import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link UrlFetchTransport}. * * @author Tony Aiuto */ +@RunWith(JUnit4.class) public class UrlFetchTransportTest extends TestCase { + @Test public void test() { new UrlFetchTransport(); } diff --git a/google-http-client-appengine/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-appengine/native-image.properties b/google-http-client-appengine/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-appengine/native-image.properties new file mode 100644 index 000000000..33cc1b54d --- /dev/null +++ b/google-http-client-appengine/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-appengine/native-image.properties @@ -0,0 +1 @@ +Args=--initialize-at-build-time=org.junit.runner.RunWith,java.lang.annotation.Annotation \ diff --git a/google-http-client-gson/pom.xml b/google-http-client-gson/pom.xml index c25eb2afd..63f5fe10c 100644 --- a/google-http-client-gson/pom.xml +++ b/google-http-client-gson/pom.xml @@ -72,5 +72,10 @@ com.google.code.gson gson + + junit + junit + test + diff --git a/google-http-client-gson/src/test/java/com/google/api/client/json/gson/GsonFactoryTest.java b/google-http-client-gson/src/test/java/com/google/api/client/json/gson/GsonFactoryTest.java index 5d166e689..b256f74f5 100644 --- a/google-http-client-gson/src/test/java/com/google/api/client/json/gson/GsonFactoryTest.java +++ b/google-http-client-gson/src/test/java/com/google/api/client/json/gson/GsonFactoryTest.java @@ -14,6 +14,10 @@ package com.google.api.client.json.gson; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; @@ -25,6 +29,7 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import org.junit.Test; /** * Tests {@link GsonFactory}. @@ -58,21 +63,19 @@ public class GsonFactoryTest extends AbstractJsonFactoryTest { + GSON_LINE_SEPARATOR + "}"; - public GsonFactoryTest(String name) { - super(name); - } - @Override protected JsonFactory newFactory() { return new GsonFactory(); } + @Test public final void testToPrettyString_entry() throws Exception { Entry entry = new Entry(); entry.title = "foo"; assertEquals(JSON_ENTRY_PRETTY, newFactory().toPrettyString(entry)); } + @Test public final void testToPrettyString_Feed() throws Exception { Feed feed = new Feed(); Entry entryFoo = new Entry(); @@ -85,11 +88,13 @@ public final void testToPrettyString_Feed() throws Exception { assertEquals(JSON_FEED_PRETTY, newFactory().toPrettyString(feed)); } + @Test public final void testParse_directValue() throws IOException { JsonParser parser = newFactory().createJsonParser("123"); assertEquals(123, parser.parse(Integer.class, true)); } + @Test public final void testGetByteValue() throws IOException { JsonParser parser = newFactory().createJsonParser("123"); @@ -101,6 +106,7 @@ public final void testGetByteValue() throws IOException { } } + @Test public final void testReaderLeniency_lenient() throws IOException { JsonObjectParser parser = new JsonObjectParser(GsonFactory.builder().setReadLeniency(true).build()); @@ -113,6 +119,7 @@ public final void testReaderLeniency_lenient() throws IOException { assertEquals("foo", json.get("title")); } + @Test public final void testReaderLeniency_not_lenient_by_default() throws IOException { JsonObjectParser parser = new JsonObjectParser(GsonFactory.getDefaultInstance()); diff --git a/google-http-client-gson/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-gson/native-image.properties b/google-http-client-gson/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-gson/native-image.properties new file mode 100644 index 000000000..3cbd2b27f --- /dev/null +++ b/google-http-client-gson/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-gson/native-image.properties @@ -0,0 +1 @@ +Args=--initialize-at-build-time=org.junit.runner.RunWith,java.lang.annotation.Annotation diff --git a/google-http-client-jackson2/pom.xml b/google-http-client-jackson2/pom.xml index e1e09f8fb..3816e5094 100644 --- a/google-http-client-jackson2/pom.xml +++ b/google-http-client-jackson2/pom.xml @@ -71,5 +71,10 @@ com.fasterxml.jackson.core jackson-core + + junit + junit + test + diff --git a/google-http-client-jackson2/src/test/java/com/google/api/client/json/jackson2/JacksonFactoryTest.java b/google-http-client-jackson2/src/test/java/com/google/api/client/json/jackson2/JacksonFactoryTest.java index c90edc2e3..89e7d0596 100644 --- a/google-http-client-jackson2/src/test/java/com/google/api/client/json/jackson2/JacksonFactoryTest.java +++ b/google-http-client-jackson2/src/test/java/com/google/api/client/json/jackson2/JacksonFactoryTest.java @@ -14,12 +14,17 @@ package com.google.api.client.json.jackson2; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonParser; import com.google.api.client.test.json.AbstractJsonFactoryTest; import com.google.api.client.util.StringUtils; import java.io.IOException; import java.util.ArrayList; +import org.junit.Test; /** * Tests {@link JacksonFactory}. @@ -45,21 +50,19 @@ public class JacksonFactoryTest extends AbstractJsonFactoryTest { + StringUtils.LINE_SEPARATOR + "}"; - public JacksonFactoryTest(String name) { - super(name); - } - @Override protected JsonFactory newFactory() { return new JacksonFactory(); } + @Test public final void testToPrettyString_entry() throws Exception { Entry entry = new Entry(); entry.title = "foo"; assertEquals(JSON_ENTRY_PRETTY, newFactory().toPrettyString(entry)); } + @Test public final void testToPrettyString_Feed() throws Exception { Feed feed = new Feed(); Entry entryFoo = new Entry(); @@ -72,11 +75,13 @@ public final void testToPrettyString_Feed() throws Exception { assertEquals(JSON_FEED_PRETTY, newFactory().toPrettyString(feed)); } + @Test public final void testParse_directValue() throws Exception { JsonParser parser = newFactory().createJsonParser("123"); assertEquals(123, parser.parse(Integer.class, true)); } + @Test public final void testGetByteValue() throws IOException { JsonParser parser = newFactory().createJsonParser("123"); diff --git a/google-http-client-jackson2/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-jackson2/native-image.properties b/google-http-client-jackson2/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-jackson2/native-image.properties index b6b626175..0bb622f01 100644 --- a/google-http-client-jackson2/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-jackson2/native-image.properties +++ b/google-http-client-jackson2/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-jackson2/native-image.properties @@ -1,7 +1,6 @@ Args=--initialize-at-build-time=com.google.api.client.json.jackson2.JacksonFactoryTest \ --initialize-at-build-time=com.google.api.client.json.jackson2.JacksonGeneratorTest \ ---initialize-at-build-time=com.fasterxml.jackson.core.io.SerializedString \ ---initialize-at-build-time=com.fasterxml.jackson.core.io.CharTypes \ ---initialize-at-build-time=com.fasterxml.jackson.core.JsonFactory \ ---initialize-at-build-time=com.fasterxml.jackson.core.io.JsonStringEncoder \ ---initialize-at-build-time=com.google.api.client.util.StringUtils \ No newline at end of file +--initialize-at-build-time=com.google.api.client.json.jackson2.JacksonFactory \ +--initialize-at-build-time=com.google.api.client.util.StringUtils \ +--initialize-at-build-time=com.fasterxml.jackson.core \ +--initialize-at-build-time=org.junit.runner.RunWith,java.lang.annotation.Annotation \ No newline at end of file diff --git a/google-http-client-protobuf/src/main/resources/META-INF/native-image/com.google.http-client/google-http-client-protobuf/native-image.properties b/google-http-client-protobuf/src/main/resources/META-INF/native-image/com.google.http-client/google-http-client-protobuf/native-image.properties new file mode 100644 index 000000000..3cbd2b27f --- /dev/null +++ b/google-http-client-protobuf/src/main/resources/META-INF/native-image/com.google.http-client/google-http-client-protobuf/native-image.properties @@ -0,0 +1 @@ +Args=--initialize-at-build-time=org.junit.runner.RunWith,java.lang.annotation.Annotation diff --git a/google-http-client-protobuf/src/test/java/com/google/api/client/protobuf/ProtocolBuffersTest.java b/google-http-client-protobuf/src/test/java/com/google/api/client/protobuf/ProtocolBuffersTest.java index 94d7d1391..40265b8c3 100644 --- a/google-http-client-protobuf/src/test/java/com/google/api/client/protobuf/ProtocolBuffersTest.java +++ b/google-http-client-protobuf/src/test/java/com/google/api/client/protobuf/ProtocolBuffersTest.java @@ -14,16 +14,22 @@ package com.google.api.client.protobuf; +import static org.junit.Assert.assertEquals; + import java.io.ByteArrayInputStream; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link ProtocolBuffers}. * * @author Yaniv Inbar */ -public class ProtocolBuffersTest extends TestCase { +@RunWith(JUnit4.class) +public class ProtocolBuffersTest { + @Test public void testParseAndClose() throws Exception { SimpleProto.TestMessage mockResponse = SimpleProto.TestMessage.newBuilder() diff --git a/google-http-client-test/clirr-ignored-differences.xml b/google-http-client-test/clirr-ignored-differences.xml new file mode 100644 index 000000000..34c8e4f44 --- /dev/null +++ b/google-http-client-test/clirr-ignored-differences.xml @@ -0,0 +1,75 @@ + + + + + + + 4001 + com/google/api/client/test/util/store/AbstractDataStoreFactoryTest + junit/framework/Test + + + + 4001 + com/google/api/client/test/json/AbstractJsonFactoryTest + junit/framework/Test + + + + 4001 + com/google/api/client/test/json/AbstractJsonGeneratorTest + junit/framework/Test + + + + 4001 + com/google/api/client/test/json/AbstractJsonParserTest + junit/framework/Test + + + + 5001 + com/google/api/client/test/util/store/AbstractDataStoreFactoryTest + junit/framework/* + + + + 5001 + com/google/api/client/test/json/AbstractJsonFactoryTest + junit/framework/* + + + + 5001 + com/google/api/client/test/json/AbstractJsonGeneratorTest + junit/framework/* + + + + 5001 + com/google/api/client/test/json/AbstractJsonParserTest + junit/framework/* + + + + 7004 + com/google/api/client/test/json/AbstractJsonFactoryTest + * + + diff --git a/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonFactoryTest.java b/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonFactoryTest.java index 8bf518109..a0629280f 100644 --- a/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonFactoryTest.java +++ b/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonFactoryTest.java @@ -14,6 +14,13 @@ package com.google.api.client.test.json; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; @@ -53,29 +60,36 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Abstract test case for testing a {@link JsonFactory}. * * @author Yaniv Inbar */ -public abstract class AbstractJsonFactoryTest extends TestCase { - - public AbstractJsonFactoryTest(String name) { - super(name); - } +@RunWith(JUnit4.class) +public abstract class AbstractJsonFactoryTest { protected abstract JsonFactory newFactory(); - private static final String EMPTY = ""; - private static final String JSON_THREE_ELEMENTS = - "{" - + " \"one\": { \"num\": 1 }" - + ", \"two\": { \"num\": 2 }" - + ", \"three\": { \"num\": 3 }" - + "}"; + private static final String EMPTY; + private static final String JSON_THREE_ELEMENTS; + private static final String EMPTY_OBJECT; + static { + EMPTY = ""; + JSON_THREE_ELEMENTS = + "{" + + " \"one\": { \"num\": 1 }" + + ", \"two\": { \"num\": 2 }" + + ", \"three\": { \"num\": 3 }" + + "}"; + EMPTY_OBJECT = "{}"; + } + + @Test public void testParse_empty() throws Exception { JsonParser parser = newFactory().createJsonParser(EMPTY); parser.nextToken(); @@ -87,8 +101,7 @@ public void testParse_empty() throws Exception { } } - private static final String EMPTY_OBJECT = "{}"; - + @Test public void testParse_emptyMap() throws Exception { JsonParser parser = newFactory().createJsonParser(EMPTY_OBJECT); parser.nextToken(); @@ -97,6 +110,7 @@ public void testParse_emptyMap() throws Exception { assertTrue(map.isEmpty()); } + @Test public void testParse_emptyGenericJson() throws Exception { JsonParser parser = newFactory().createJsonParser(EMPTY_OBJECT); parser.nextToken(); @@ -104,6 +118,7 @@ public void testParse_emptyGenericJson() throws Exception { assertTrue(json.isEmpty()); } + @Test public void testParser_partialEmpty() throws Exception { JsonFactory factory = newFactory(); JsonParser parser; @@ -118,15 +133,21 @@ public void testParser_partialEmpty() throws Exception { assertTrue(result.isEmpty()); } - private static final String JSON_ENTRY = "{\"title\":\"foo\"}"; - private static final String JSON_FEED = - "{\"entries\":[" + "{\"title\":\"foo\"}," + "{\"title\":\"bar\"}]}"; + private static final String JSON_ENTRY; + private static final String JSON_FEED; + + static { + JSON_ENTRY = "{\"title\":\"foo\"}"; + JSON_FEED = "{\"entries\":[" + "{\"title\":\"foo\"}," + "{\"title\":\"bar\"}]}"; + } + @Test public void testParseEntry() throws Exception { Entry entry = newFactory().createJsonParser(JSON_ENTRY).parseAndClose(Entry.class); assertEquals("foo", entry.title); } + @Test public void testParser_partialEntry() throws Exception { JsonFactory factory = newFactory(); JsonParser parser; @@ -140,6 +161,7 @@ public void testParser_partialEntry() throws Exception { assertEquals("foo", result.title); } + @Test public void testParseFeed() throws Exception { JsonParser parser = newFactory().createJsonParser(JSON_FEED); parser.nextToken(); @@ -151,6 +173,7 @@ public void testParseFeed() throws Exception { } @SuppressWarnings("unchecked") + @Test public void testParseEntryAsMap() throws Exception { JsonParser parser = newFactory().createJsonParser(JSON_ENTRY); parser.nextToken(); @@ -159,6 +182,7 @@ public void testParseEntryAsMap() throws Exception { assertTrue(map.isEmpty()); } + @Test public void testSkipToKey_missingEmpty() throws Exception { JsonParser parser = newFactory().createJsonParser(EMPTY_OBJECT); parser.nextToken(); @@ -166,6 +190,7 @@ public void testSkipToKey_missingEmpty() throws Exception { assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken()); } + @Test public void testSkipToKey_missing() throws Exception { JsonParser parser = newFactory().createJsonParser(JSON_ENTRY); parser.nextToken(); @@ -173,6 +198,7 @@ public void testSkipToKey_missing() throws Exception { assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken()); } + @Test public void testSkipToKey_found() throws Exception { JsonParser parser = newFactory().createJsonParser(JSON_ENTRY); parser.nextToken(); @@ -181,6 +207,7 @@ public void testSkipToKey_found() throws Exception { assertEquals("foo", parser.getText()); } + @Test public void testSkipToKey_startWithFieldName() throws Exception { JsonParser parser = newFactory().createJsonParser(JSON_ENTRY); parser.nextToken(); @@ -190,6 +217,7 @@ public void testSkipToKey_startWithFieldName() throws Exception { assertEquals("foo", parser.getText()); } + @Test public void testSkipChildren_string() throws Exception { JsonParser parser = newFactory().createJsonParser(JSON_ENTRY); parser.nextToken(); @@ -199,6 +227,7 @@ public void testSkipChildren_string() throws Exception { assertEquals("foo", parser.getText()); } + @Test public void testSkipChildren_object() throws Exception { JsonParser parser = newFactory().createJsonParser(JSON_ENTRY); parser.nextToken(); @@ -206,6 +235,7 @@ public void testSkipChildren_object() throws Exception { assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken()); } + @Test public void testSkipChildren_array() throws Exception { JsonParser parser = newFactory().createJsonParser(JSON_FEED); parser.nextToken(); @@ -214,6 +244,7 @@ public void testSkipChildren_array() throws Exception { assertEquals(JsonToken.END_ARRAY, parser.getCurrentToken()); } + @Test public void testNextToken() throws Exception { JsonParser parser = newFactory().createJsonParser(JSON_FEED); assertEquals(JsonToken.START_OBJECT, parser.nextToken()); @@ -232,6 +263,7 @@ public void testNextToken() throws Exception { assertNull(parser.nextToken()); } + @Test public void testCurrentToken() throws Exception { JsonParser parser = newFactory().createJsonParser(JSON_FEED); assertNull(parser.getCurrentToken()); @@ -277,8 +309,13 @@ public static class A { @Key public Map map; } - static final String CONTAINED_MAP = "{\"map\":{\"title\":\"foo\"}}"; + static final String CONTAINED_MAP; + + static { + CONTAINED_MAP = "{\"map\":{\"title\":\"foo\"}}"; + } + @Test public void testParse() throws Exception { JsonParser parser = newFactory().createJsonParser(CONTAINED_MAP); parser.nextToken(); @@ -335,22 +372,27 @@ public static class NumberTypesAsString { @Key @JsonString Map longMapValue; } - static final String NUMBER_TYPES = - "{\"bigDecimalValue\":1.0,\"bigIntegerValue\":1,\"byteObjValue\":1,\"byteValue\":1," - + "\"doubleObjValue\":1.0,\"doubleValue\":1.0,\"floatObjValue\":1.0,\"floatValue\":1.0," - + "\"intObjValue\":1,\"intValue\":1,\"longListValue\":[1],\"longMapValue\":{\"a\":1}," - + "\"longObjValue\":1,\"longValue\":1,\"shortObjValue\":1,\"shortValue\":1," - + "\"yetAnotherBigDecimalValue\":1}"; + static final String NUMBER_TYPES; + static final String NUMBER_TYPES_AS_STRING; - static final String NUMBER_TYPES_AS_STRING = - "{\"bigDecimalValue\":\"1.0\",\"bigIntegerValue\":\"1\",\"byteObjValue\":\"1\"," - + "\"byteValue\":\"1\",\"doubleObjValue\":\"1.0\",\"doubleValue\":\"1.0\"," - + "\"floatObjValue\":\"1.0\",\"floatValue\":\"1.0\",\"intObjValue\":\"1\"," - + "\"intValue\":\"1\",\"longListValue\":[\"1\"],\"longMapValue\":{\"a\":\"1\"}," - + "\"longObjValue\":\"1\",\"longValue\":\"1\"," - + "\"shortObjValue\":\"1\"," - + "\"shortValue\":\"1\",\"yetAnotherBigDecimalValue\":\"1\"}"; + static { + NUMBER_TYPES = + "{\"bigDecimalValue\":1.0,\"bigIntegerValue\":1,\"byteObjValue\":1,\"byteValue\":1," + + "\"doubleObjValue\":1.0,\"doubleValue\":1.0,\"floatObjValue\":1.0,\"floatValue\":1.0," + + "\"intObjValue\":1,\"intValue\":1,\"longListValue\":[1],\"longMapValue\":{\"a\":1}," + + "\"longObjValue\":1,\"longValue\":1,\"shortObjValue\":1,\"shortValue\":1," + + "\"yetAnotherBigDecimalValue\":1}"; + NUMBER_TYPES_AS_STRING = + "{\"bigDecimalValue\":\"1.0\",\"bigIntegerValue\":\"1\",\"byteObjValue\":\"1\"," + + "\"byteValue\":\"1\",\"doubleObjValue\":\"1.0\",\"doubleValue\":\"1.0\"," + + "\"floatObjValue\":\"1.0\",\"floatValue\":\"1.0\",\"intObjValue\":\"1\"," + + "\"intValue\":\"1\",\"longListValue\":[\"1\"],\"longMapValue\":{\"a\":\"1\"}," + + "\"longObjValue\":\"1\",\"longValue\":\"1\"," + + "\"shortObjValue\":\"1\"," + + "\"shortValue\":\"1\",\"yetAnotherBigDecimalValue\":\"1\"}"; + } + @Test public void testParser_numberTypes() throws Exception { JsonFactory factory = newFactory(); JsonParser parser; @@ -384,15 +426,22 @@ public void testParser_numberTypes() throws Exception { } } + @Test public void testToFromString() throws Exception { JsonFactory factory = newFactory(); NumberTypes result = factory.fromString(NUMBER_TYPES, NumberTypes.class); assertEquals(NUMBER_TYPES, factory.toString(result)); } - private static final String UTF8_VALUE = "123\u05D9\u05e0\u05D9\u05D1"; - private static final String UTF8_JSON = "{\"value\":\"" + UTF8_VALUE + "\"}"; + private static final String UTF8_VALUE; + private static final String UTF8_JSON; + static { + UTF8_VALUE = "123\u05D9\u05e0\u05D9\u05D1"; + UTF8_JSON = "{\"value\":\"" + UTF8_VALUE + "\"}"; + } + + @Test public void testToFromString_UTF8() throws Exception { JsonFactory factory = newFactory(); GenericJson result = factory.fromString(UTF8_JSON, GenericJson.class); @@ -409,10 +458,15 @@ public static class AnyType { @Key public Object nul; } - static final String ANY_TYPE = - "{\"arr\":[1],\"bool\":true,\"nul\":null,\"num\":5," - + "\"obj\":{\"key\":\"value\"},\"str\":\"value\"}"; + static final String ANY_TYPE; + static { + ANY_TYPE = + "{\"arr\":[1],\"bool\":true,\"nul\":null,\"num\":5," + + "\"obj\":{\"key\":\"value\"},\"str\":\"value\"}"; + } + + @Test public void testParser_anyType() throws Exception { JsonFactory factory = newFactory(); JsonParser parser; @@ -430,8 +484,13 @@ public static class ArrayType { @Key public Integer[] integerArr; } - static final String ARRAY_TYPE = "{\"arr\":[4,5],\"arr2\":[[1,2],[3]],\"integerArr\":[6,7]}"; + static final String ARRAY_TYPE; + + static { + ARRAY_TYPE = "{\"arr\":[4,5],\"arr2\":[[1,2],[3]],\"integerArr\":[6,7]}"; + } + @Test public void testParser_arrayType() throws Exception { JsonFactory factory = newFactory(); JsonParser parser; @@ -461,8 +520,13 @@ public static class CollectionOfCollectionType { @Key public LinkedList> arr; } - static final String COLLECTION_TYPE = "{\"arr\":[[\"a\",\"b\"],[\"c\"]]}"; + static final String COLLECTION_TYPE; + static { + COLLECTION_TYPE = "{\"arr\":[[\"a\",\"b\"],[\"c\"]]}"; + } + + @Test public void testParser_collectionType() throws Exception { JsonFactory factory = newFactory(); JsonParser parser; @@ -480,9 +544,13 @@ public static class MapOfMapType { @Key public Map>[] value; } - static final String MAP_TYPE = - "{\"value\":[{\"map1\":{\"k1\":1,\"k2\":2},\"map2\":{\"kk1\":3,\"kk2\":4}}]}"; + static final String MAP_TYPE; + + static { + MAP_TYPE = "{\"value\":[{\"map1\":{\"k1\":1,\"k2\":2},\"map2\":{\"kk1\":3,\"kk2\":4}}]}"; + } + @Test public void testParser_mapType() throws Exception { // parse JsonFactory factory = newFactory(); @@ -503,6 +571,7 @@ public void testParser_mapType() throws Exception { assertEquals(4, map2.get("kk2").intValue()); } + @Test public void testParser_hashmapForMapType() throws Exception { // parse JsonFactory factory = newFactory(); @@ -531,11 +600,16 @@ public static class WildCardTypes { @Key public Collection[] upper; } - static final String WILDCARD_TYPE = - "{\"lower\":[[1,2,3]],\"map\":{\"v\":1},\"mapInWild\":[{\"v\":1}]," - + "\"mapUpper\":{\"v\":1},\"simple\":[[1,2,3]],\"upper\":[[1,2,3]]}"; + static final String WILDCARD_TYPE; + + static { + WILDCARD_TYPE = + "{\"lower\":[[1,2,3]],\"map\":{\"v\":1},\"mapInWild\":[{\"v\":1}]," + + "\"mapUpper\":{\"v\":1},\"simple\":[[1,2,3]],\"upper\":[[1,2,3]]}"; + } @SuppressWarnings("unchecked") + @Test public void testParser_wildCardType() throws Exception { // parse JsonFactory factory = newFactory(); @@ -590,20 +664,31 @@ public static class DoubleListTypeVariableType extends TypeVariableType> {} - static final String INTEGER_TYPE_VARIABLE_TYPE = - "{\"arr\":[null,[null,1]],\"list\":[null,[null,1]],\"nullValue\":null,\"value\":1}"; + static final String INTEGER_TYPE_VARIABLE_TYPE; + + static final String INT_ARRAY_TYPE_VARIABLE_TYPE; + + static final String DOUBLE_LIST_TYPE_VARIABLE_TYPE; + + static final String FLOAT_MAP_TYPE_VARIABLE_TYPE; + + static { + INTEGER_TYPE_VARIABLE_TYPE = + "{\"arr\":[null,[null,1]],\"list\":[null,[null,1]],\"nullValue\":null,\"value\":1}"; - static final String INT_ARRAY_TYPE_VARIABLE_TYPE = - "{\"arr\":[null,[null,[1]]],\"list\":[null,[null,[1]]],\"nullValue\":null,\"value\":[1]}"; + INT_ARRAY_TYPE_VARIABLE_TYPE = + "{\"arr\":[null,[null,[1]]],\"list\":[null,[null,[1]]],\"nullValue\":null,\"value\":[1]}"; - static final String DOUBLE_LIST_TYPE_VARIABLE_TYPE = - "{\"arr\":[null,[null,[1.0]]],\"list\":[null,[null,[1.0]]]," - + "\"nullValue\":null,\"value\":[1.0]}"; + DOUBLE_LIST_TYPE_VARIABLE_TYPE = + "{\"arr\":[null,[null,[1.0]]],\"list\":[null,[null,[1.0]]]," + + "\"nullValue\":null,\"value\":[1.0]}"; - static final String FLOAT_MAP_TYPE_VARIABLE_TYPE = - "{\"arr\":[null,[null,{\"a\":1.0}]],\"list\":[null,[null,{\"a\":1.0}]]," - + "\"nullValue\":null,\"value\":{\"a\":1.0}}"; + FLOAT_MAP_TYPE_VARIABLE_TYPE = + "{\"arr\":[null,[null,{\"a\":1.0}]],\"list\":[null,[null,{\"a\":1.0}]]," + + "\"nullValue\":null,\"value\":{\"a\":1.0}}"; + } + @Test public void testParser_integerTypeVariableType() throws Exception { // parse JsonFactory factory = newFactory(); @@ -640,6 +725,7 @@ public void testParser_integerTypeVariableType() throws Exception { assertEquals(1, value.intValue()); } + @Test public void testParser_intArrayTypeVariableType() throws Exception { // parse JsonFactory factory = newFactory(); @@ -676,6 +762,7 @@ public void testParser_intArrayTypeVariableType() throws Exception { assertTrue(Arrays.equals(new int[] {1}, value)); } + @Test public void testParser_doubleListTypeVariableType() throws Exception { // parse JsonFactory factory = newFactory(); @@ -696,7 +783,7 @@ public void testParser_doubleListTypeVariableType() throws Exception { List arrValue = subArr[1]; assertEquals(1, arrValue.size()); Double dValue = arrValue.get(0); - assertEquals(1.0, dValue); + assertEquals(Double.valueOf(1.0), dValue); // collection LinkedList>> list = result.list; assertEquals(2, list.size()); @@ -714,6 +801,7 @@ public void testParser_doubleListTypeVariableType() throws Exception { assertEquals(ImmutableList.of(Double.valueOf(1)), value); } + @Test public void testParser_floatMapTypeVariableType() throws Exception { // parse JsonFactory factory = newFactory(); @@ -734,7 +822,7 @@ public void testParser_floatMapTypeVariableType() throws Exception { Map arrValue = subArr[1]; assertEquals(1, arrValue.size()); Float fValue = arrValue.get("a"); - assertEquals(1.0f, fValue); + assertEquals(Float.valueOf(1.0f), fValue); // collection LinkedList>> list = result.list; assertEquals(2, list.size()); @@ -745,7 +833,7 @@ public void testParser_floatMapTypeVariableType() throws Exception { arrValue = subList.get(1); assertEquals(1, arrValue.size()); fValue = arrValue.get("a"); - assertEquals(1.0f, fValue); + assertEquals(Float.valueOf(1.0f), fValue); // null value Map nullValue = result.nullValue; assertEquals(Data.nullOf(HashMap.class), nullValue); @@ -753,10 +841,11 @@ public void testParser_floatMapTypeVariableType() throws Exception { Map value = result.value; assertEquals(1, value.size()); fValue = value.get("a"); - assertEquals(1.0f, fValue); + assertEquals(Float.valueOf(1.0f), fValue); } @SuppressWarnings("unchecked") + @Test public void testParser_treemapForTypeVariableType() throws Exception { // parse JsonFactory factory = newFactory(); @@ -790,8 +879,13 @@ public static class StringNullValue { @Key public String value; } - static final String NULL_VALUE = "{\"arr\":[null],\"arr2\":[null,[null]],\"value\":null}"; + static final String NULL_VALUE; + + static { + NULL_VALUE = "{\"arr\":[null],\"arr2\":[null,[null]],\"value\":null}"; + } + @Test public void testParser_nullValue() throws Exception { // parse JsonFactory factory = newFactory(); @@ -830,9 +924,13 @@ public static class EnumValue { @Key public E nullValue; } - static final String ENUM_VALUE = - "{\"nullValue\":null,\"otherValue\":\"other\",\"value\":\"VALUE\"}"; + static final String ENUM_VALUE; + static { + ENUM_VALUE = "{\"nullValue\":null,\"otherValue\":\"other\",\"value\":\"VALUE\"}"; + } + + @Test public void testParser_enumValue() throws Exception { // parse JsonFactory factory = newFactory(); @@ -862,8 +960,13 @@ public static class Z { public static class TypeVariablesPassedAround extends X> {} - static final String TYPE_VARS = "{\"y\":{\"z\":{\"f\":[\"abc\"]}}}"; + static final String TYPE_VARS; + + static { + TYPE_VARS = "{\"y\":{\"z\":{\"f\":[\"abc\"]}}}"; + } + @Test public void testParser_typeVariablesPassAround() throws Exception { // parse JsonFactory factory = newFactory(); @@ -878,8 +981,13 @@ public void testParser_typeVariablesPassAround() throws Exception { assertEquals("abc", f.get(0)); } - static final String STRING_ARRAY = "[\"a\",\"b\",\"c\"]"; + static final String STRING_ARRAY; + static { + STRING_ARRAY = "[\"a\",\"b\",\"c\"]"; + } + + @Test public void testParser_stringArray() throws Exception { JsonFactory factory = newFactory(); JsonParser parser; @@ -891,8 +999,13 @@ public void testParser_stringArray() throws Exception { assertTrue(Arrays.equals(new String[] {"a", "b", "c"}, result)); } - static final String INT_ARRAY = "[1,2,3]"; + static final String INT_ARRAY; + + static { + INT_ARRAY = "[1,2,3]"; + } + @Test public void testParser_intArray() throws Exception { JsonFactory factory = newFactory(); JsonParser parser; @@ -904,8 +1017,13 @@ public void testParser_intArray() throws Exception { assertTrue(Arrays.equals(new int[] {1, 2, 3}, result)); } - private static final String EMPTY_ARRAY = "[]"; + private static final String EMPTY_ARRAY; + static { + EMPTY_ARRAY = "[]"; + } + + @Test public void testParser_emptyArray() throws Exception { JsonFactory factory = newFactory(); String[] result = factory.createJsonParser(EMPTY_ARRAY).parse(String[].class); @@ -914,6 +1032,7 @@ public void testParser_emptyArray() throws Exception { assertEquals(0, result.length); } + @Test public void testParser_partialEmptyArray() throws Exception { JsonFactory factory = newFactory(); JsonParser parser; @@ -927,8 +1046,13 @@ public void testParser_partialEmptyArray() throws Exception { assertEquals(0, result.length); } - private static final String NUMBER_TOP_VALUE = "1"; + private static final String NUMBER_TOP_VALUE; + static { + NUMBER_TOP_VALUE = "1"; + } + + @Test public void testParser_num() throws Exception { JsonFactory factory = newFactory(); int result = factory.createJsonParser(NUMBER_TOP_VALUE).parse(int.class); @@ -937,8 +1061,13 @@ public void testParser_num() throws Exception { assertEquals(1, result); } - private static final String STRING_TOP_VALUE = "\"a\""; + private static final String STRING_TOP_VALUE; + + static { + STRING_TOP_VALUE = "\"a\""; + } + @Test public void testParser_string() throws Exception { JsonFactory factory = newFactory(); String result = factory.createJsonParser(STRING_TOP_VALUE).parse(String.class); @@ -947,8 +1076,13 @@ public void testParser_string() throws Exception { assertEquals("a", result); } - private static final String NULL_TOP_VALUE = "null"; + private static final String NULL_TOP_VALUE; + static { + NULL_TOP_VALUE = "null"; + } + + @Test public void testParser_null() throws Exception { JsonFactory factory = newFactory(); String result = factory.createJsonParser(NULL_TOP_VALUE).parse(String.class); @@ -957,8 +1091,13 @@ public void testParser_null() throws Exception { assertTrue(Data.isNull(result)); } - private static final String BOOL_TOP_VALUE = "true"; + private static final String BOOL_TOP_VALUE; + + static { + BOOL_TOP_VALUE = "true"; + } + @Test public void testParser_bool() throws Exception { JsonFactory factory = newFactory(); boolean result = factory.createJsonParser(BOOL_TOP_VALUE).parse(boolean.class); @@ -1040,6 +1179,7 @@ public final void testToPrettyString_FeedApproximate() throws Exception { assertEquals(JSON_FEED, factory.toString(factory.fromString(prettyString, Feed.class))); } + @Test public void testParser_nullInputStream() throws Exception { try { newFactory().createJsonParser((InputStream) null, Charsets.UTF_8); @@ -1049,6 +1189,7 @@ public void testParser_nullInputStream() throws Exception { } } + @Test public void testParser_nullString() throws Exception { try { newFactory().createJsonParser((String) null); @@ -1058,6 +1199,7 @@ public void testParser_nullString() throws Exception { } } + @Test public void testParser_nullReader() throws Exception { try { newFactory().createJsonParser((Reader) null); @@ -1067,6 +1209,7 @@ public void testParser_nullReader() throws Exception { } } + @Test public void testObjectParserParse_entry() throws Exception { @SuppressWarnings("serial") Entry entry = @@ -1077,6 +1220,7 @@ public void testObjectParserParse_entry() throws Exception { assertEquals("foo", entry.title); } + @Test public void testObjectParserParse_stringList() throws Exception { JsonFactory factory = newFactory(); @SuppressWarnings({"unchecked", "serial"}) @@ -1092,6 +1236,7 @@ public void testObjectParserParse_stringList() throws Exception { assertTrue(ImmutableList.of("a", "b", "c").equals(result)); } + @Test public void testToString_withFactory() { GenericJson data = new GenericJson(); data.put("a", "b"); @@ -1099,6 +1244,7 @@ public void testToString_withFactory() { assertEquals("{\"a\":\"b\"}", data.toString()); } + @Test public void testFactory() { JsonFactory factory = newFactory(); GenericJson data = new GenericJson(); @@ -1111,6 +1257,7 @@ private JsonParser createParser(String json) throws Exception { return newFactory().createJsonParser(json); } + @Test public void testSkipToKey_firstKey() throws Exception { JsonParser parser = createParser(JSON_THREE_ELEMENTS); assertEquals("one", parser.skipToKey(ImmutableSet.of("one"))); @@ -1118,6 +1265,7 @@ public void testSkipToKey_firstKey() throws Exception { assertEquals(1, parser.getIntValue()); } + @Test public void testSkipToKey_lastKey() throws Exception { JsonParser parser = createParser(JSON_THREE_ELEMENTS); assertEquals("three", parser.skipToKey(ImmutableSet.of("three"))); @@ -1125,6 +1273,7 @@ public void testSkipToKey_lastKey() throws Exception { assertEquals(3, parser.getIntValue()); } + @Test public void testSkipToKey_multipleKeys() throws Exception { JsonParser parser = createParser(JSON_THREE_ELEMENTS); assertEquals("two", parser.skipToKey(ImmutableSet.of("foo", "three", "two"))); @@ -1132,6 +1281,7 @@ public void testSkipToKey_multipleKeys() throws Exception { assertEquals(2, parser.getIntValue()); } + @Test public void testSkipToKey_noMatch() throws Exception { JsonParser parser = createParser(JSON_THREE_ELEMENTS); assertEquals(null, parser.skipToKey(ImmutableSet.of("foo", "bar", "num"))); @@ -1220,8 +1370,13 @@ public ExtendsGenericJson set(String fieldName, Object value) { } } - static final String EXTENDS_JSON = "{\"numAsString\":\"1\",\"num\":1}"; + static final String EXTENDS_JSON; + static { + EXTENDS_JSON = "{\"numAsString\":\"1\",\"num\":1}"; + } + + @Test public void testParser_extendsGenericJson() throws Exception { JsonFactory factory = newFactory(); JsonParser parser; @@ -1236,9 +1391,15 @@ public static class Simple { @Key String a; } - static final String SIMPLE = "{\"a\":\"b\"}"; - static final String SIMPLE_WRAPPED = "{\"d\":{\"a\":\"b\"}}"; + static final String SIMPLE; + static final String SIMPLE_WRAPPED; + + static { + SIMPLE = "{\"a\":\"b\"}"; + SIMPLE_WRAPPED = "{\"d\":{\"a\":\"b\"}}"; + } + @Test public void testJsonObjectParser_reader() throws Exception { JsonFactory factory = newFactory(); JsonObjectParser parser = new JsonObjectParser(factory); @@ -1246,6 +1407,7 @@ public void testJsonObjectParser_reader() throws Exception { assertEquals("b", simple.a); } + @Test public void testJsonObjectParser_inputStream() throws Exception { JsonFactory factory = newFactory(); JsonObjectParser parser = new JsonObjectParser(factory); @@ -1257,6 +1419,7 @@ public void testJsonObjectParser_inputStream() throws Exception { assertEquals("b", simple.a); } + @Test public void testJsonObjectParser_readerWrapped() throws Exception { JsonFactory factory = newFactory(); JsonObjectParser parser = @@ -1265,6 +1428,7 @@ public void testJsonObjectParser_readerWrapped() throws Exception { assertEquals("b", simple.a); } + @Test public void testJsonObjectParser_inputStreamWrapped() throws Exception { JsonFactory factory = newFactory(); JsonObjectParser parser = @@ -1277,6 +1441,7 @@ public void testJsonObjectParser_inputStreamWrapped() throws Exception { assertEquals("b", simple.a); } + @Test public void testJsonHttpContent_simple() throws Exception { JsonFactory factory = newFactory(); Simple simple = new Simple(); @@ -1287,6 +1452,7 @@ public void testJsonHttpContent_simple() throws Exception { assertEquals(SIMPLE, out.toString("UTF-8")); } + @Test public void testJsonHttpContent_wrapped() throws Exception { JsonFactory factory = newFactory(); Simple simple = new Simple(); @@ -1302,6 +1468,7 @@ public static class V { @Key String s; } + @Test public void testParse_void() throws Exception { subtestParse_void(null); subtestParse_void("\"a\""); @@ -1328,14 +1495,25 @@ public static class BooleanTypes { @Key boolean bool; } - public static final String BOOLEAN_TYPE_EMPTY = "{}"; - public static final String BOOLEAN_TYPE_EMPTY_OUTPUT = "{\"bool\":false}"; - public static final String BOOLEAN_TYPE_TRUE = "{\"bool\":true,\"boolObj\":true}"; - public static final String BOOLEAN_TYPE_FALSE = "{\"bool\":false,\"boolObj\":false}"; - public static final String BOOLEAN_TYPE_NULL = "{\"boolObj\":null}"; - public static final String BOOLEAN_TYPE_NULL_OUTPUT = "{\"bool\":false,\"boolObj\":null}"; - public static final String BOOLEAN_TYPE_WRONG = "{\"boolObj\":{}}"; + public static final String BOOLEAN_TYPE_EMPTY; + public static final String BOOLEAN_TYPE_EMPTY_OUTPUT; + public static final String BOOLEAN_TYPE_TRUE; + public static final String BOOLEAN_TYPE_FALSE; + public static final String BOOLEAN_TYPE_NULL; + public static final String BOOLEAN_TYPE_NULL_OUTPUT; + public static final String BOOLEAN_TYPE_WRONG; + + static { + BOOLEAN_TYPE_EMPTY = "{}"; + BOOLEAN_TYPE_EMPTY_OUTPUT = "{\"bool\":false}"; + BOOLEAN_TYPE_TRUE = "{\"bool\":true,\"boolObj\":true}"; + BOOLEAN_TYPE_FALSE = "{\"bool\":false,\"boolObj\":false}"; + BOOLEAN_TYPE_NULL = "{\"boolObj\":null}"; + BOOLEAN_TYPE_NULL_OUTPUT = "{\"bool\":false,\"boolObj\":null}"; + BOOLEAN_TYPE_WRONG = "{\"boolObj\":{}}"; + } + @Test public void testParse_boolean() throws Exception { JsonFactory factory = newFactory(); BooleanTypes parsed; @@ -1414,6 +1592,7 @@ public static class Centipede extends Animal { "{\"unused\":0, \"bodyColor\":\"green\",\"name\":\"Mr. Icky\",\"legCount\":68,\"type\":" + "\"bug\"}"; + @Test public void testParser_heterogeneousSchemata() throws Exception { testParser_heterogeneousSchemata_Helper(DOG, CENTIPEDE); // TODO(ngmiceli): Test that this uses the optimized flow (once implemented) @@ -1451,6 +1630,7 @@ private void testParser_heterogeneousSchemata_Helper(String dogJson, String cent public static final String ANIMAL_WITHOUT_TYPE = "{\"legCount\":3,\"name\":\"Confused\"}"; + @Test public void testParser_heterogeneousSchema_missingType() throws Exception { JsonFactory factory = newFactory(); JsonParser parser; @@ -1471,6 +1651,7 @@ public static class Human extends Animal { public static final String HUMAN = "{\"bestFriend\":" + DOG + ",\"legCount\":2,\"name\":\"Joe\",\"type\":\"human\"}"; + @Test public void testParser_heterogeneousSchema_withObject() throws Exception { JsonFactory factory = newFactory(); JsonParser parser = factory.createJsonParser(HUMAN); @@ -1508,6 +1689,7 @@ public static class DogGenericJson extends AnimalGenericJson { + "\"unusedInfo\":\"this is not being used!\",\"unused\":{\"foo\":200}}"; @SuppressWarnings("unchecked") + @Test public void testParser_heterogeneousSchema_genericJson() throws Exception { JsonFactory factory = newFactory(); JsonParser parser = factory.createJsonParser(DOG_EXTRA_INFO); @@ -1536,6 +1718,7 @@ public static class DogWithFamily extends Dog { @Key public Animal[] children; } + @Test public void testParser_heterogeneousSchema_withArrays() throws Exception { JsonFactory factory = newFactory(); JsonParser parser = factory.createJsonParser(DOG_WITH_FAMILY); @@ -1560,6 +1743,7 @@ public void testParser_heterogeneousSchema_withArrays() throws Exception { public static final String DOG_WITH_NO_FAMILY_PARSED = "{\"legCount\":4,\"tricksKnown\":0,\"type\":\"dogwithfamily\"}"; + @Test public void testParser_heterogeneousSchema_withNullArrays() throws Exception { JsonFactory factory = newFactory(); JsonParser parser = factory.createJsonParser(DOG_WITH_NO_FAMILY); @@ -1590,6 +1774,7 @@ public static class PolymorphicWithMultipleAnnotations { public static final String MULTIPLE_ANNOTATIONS_JSON = "{\"a\":\"foo\",\"b\":\"dog\",\"c\":\"bar\",\"d\":\"bug\"}"; + @Test public void testParser_polymorphicClass_tooManyAnnotations() throws Exception { JsonFactory factory = newFactory(); JsonParser parser = factory.createJsonParser(MULTIPLE_ANNOTATIONS_JSON); @@ -1620,6 +1805,7 @@ public static class NumericTypedSubclass2 extends PolymorphicWithNumericType {} public static final String POLYMORPHIC_NUMERIC_TYPE_1 = "{\"foo\":\"bar\",\"type\":1}"; public static final String POLYMORPHIC_NUMERIC_TYPE_2 = "{\"foo\":\"bar\",\"type\":2}"; + @Test public void testParser_heterogeneousSchema_numericType() throws Exception { JsonFactory factory = newFactory(); JsonParser parser = factory.createJsonParser(POLYMORPHIC_NUMERIC_TYPE_1); @@ -1648,6 +1834,7 @@ public static class NumericValueTypedSubclass2 extends PolymorphicWithNumericVal public static final String POLYMORPHIC_NUMERIC_UNSPECIFIED_TYPE = "{\"foo\":\"bar\"}"; + @Test public void testParser_heterogeneousSchema_numericValueType() throws Exception { JsonFactory factory = newFactory(); JsonParser parser = factory.createJsonParser(POLYMORPHIC_NUMERIC_TYPE_1); @@ -1679,6 +1866,7 @@ public static class PolymorphicWithIllegalValueType { Object type; } + @Test public void testParser_heterogeneousSchema_illegalValueType() throws Exception { JsonFactory factory = newFactory(); JsonParser parser = factory.createJsonParser(POLYMORPHIC_NUMERIC_TYPE_1); @@ -1700,6 +1888,7 @@ public static class PolymorphicWithDuplicateTypeKeys { String type; } + @Test public void testParser_polymorphicClass_duplicateTypeKeys() throws Exception { JsonFactory factory = newFactory(); JsonParser parser = factory.createJsonParser(EMPTY_OBJECT); @@ -1714,6 +1903,7 @@ public void testParser_polymorphicClass_duplicateTypeKeys() throws Exception { public static final String POLYMORPHIC_WITH_UNKNOWN_KEY = "{\"legCount\":4,\"name\":\"Fido\",\"tricksKnown\":3,\"type\":\"unknown\"}"; + @Test public void testParser_polymorphicClass_noMatchingTypeKey() throws Exception { JsonFactory factory = newFactory(); JsonParser parser = factory.createJsonParser(POLYMORPHIC_WITH_UNKNOWN_KEY); @@ -1736,6 +1926,7 @@ public static class PolymorphicSelfReferencing { public static final String POLYMORPHIC_SELF_REFERENCING = "{\"info\":\"blah\",\"type\":\"self\"}"; + @Test public void testParser_polymorphicClass_selfReferencing() throws Exception { JsonFactory factory = newFactory(); JsonParser parser = factory.createJsonParser(POLYMORPHIC_SELF_REFERENCING); @@ -1765,6 +1956,7 @@ public static class HumanWithPets extends Human { + ",\"second\":{\"legCount\":0,\"tricksKnown\":0,\"type\":\"dog\"}}," + "\"type\":\"human with pets\"}"; + @Test public void testParser_polymorphicClass_mapOfPolymorphicClasses() throws Exception { JsonFactory factory = newFactory(); JsonParser parser = factory.createJsonParser(HUMAN_WITH_PETS); diff --git a/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonGeneratorTest.java b/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonGeneratorTest.java index 1a2a1bb54..96db2b1f5 100644 --- a/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonGeneratorTest.java +++ b/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonGeneratorTest.java @@ -14,6 +14,8 @@ package com.google.api.client.test.json; +import static org.junit.Assert.assertEquals; + import com.google.api.client.json.JsonGenerator; import java.io.IOException; import java.io.StringWriter; @@ -21,9 +23,12 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; -public abstract class AbstractJsonGeneratorTest extends TestCase { +@RunWith(JUnit4.class) +public abstract class AbstractJsonGeneratorTest { protected abstract JsonGenerator newGenerator(Writer writer) throws IOException; @@ -34,6 +39,7 @@ public Iterator> iterator() { } } + @Test public void testSerialize_simpleMap() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = newGenerator(writer); @@ -46,6 +52,7 @@ public void testSerialize_simpleMap() throws Exception { assertEquals("{\"a\":\"b\"}", writer.toString()); } + @Test public void testSerialize_iterableMap() throws Exception { StringWriter writer = new StringWriter(); JsonGenerator generator = newGenerator(writer); diff --git a/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonParserTest.java b/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonParserTest.java index 985637aea..25bb77bb4 100644 --- a/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonParserTest.java +++ b/google-http-client-test/src/main/java/com/google/api/client/test/json/AbstractJsonParserTest.java @@ -13,6 +13,10 @@ */ package com.google.api.client.test.json; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; @@ -21,17 +25,25 @@ import java.io.InputStream; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; -import junit.framework.TestCase; import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; -public abstract class AbstractJsonParserTest extends TestCase { +@RunWith(JUnit4.class) +public abstract class AbstractJsonParserTest { protected abstract JsonFactory newJsonFactory(); - private static final String TEST_JSON = - "{\"strValue\": \"bar\", \"intValue\": 123, \"boolValue\": false}"; - private static final String TEST_JSON_BIG_DECIMAL = "{\"bigDecimalValue\": 1559341956102}"; + private static final String TEST_JSON; + private static final String TEST_JSON_BIG_DECIMAL; + + static { + TEST_JSON = "{\"strValue\": \"bar\", \"intValue\": 123, \"boolValue\": false}"; + TEST_JSON_BIG_DECIMAL = "{\"bigDecimalValue\": 1559341956102}"; + } + @Test public void testParse_basic() throws IOException { JsonObjectParser parser = new JsonObjectParser(newJsonFactory()); InputStream inputStream = new ByteArrayInputStream(TEST_JSON.getBytes(StandardCharsets.UTF_8)); @@ -45,6 +57,7 @@ public void testParse_basic() throws IOException { assertEquals(Boolean.FALSE, json.get("boolValue")); } + @Test public void testGetWrongType() throws IOException { JsonObjectParser parser = new JsonObjectParser(newJsonFactory()); InputStream inputStream = new ByteArrayInputStream(TEST_JSON.getBytes(StandardCharsets.UTF_8)); @@ -57,6 +70,7 @@ public void testGetWrongType() throws IOException { assertEquals(Boolean.FALSE, json.get("boolValue")); } + @Test public void testParse_badJson() throws IOException { JsonObjectParser parser = new JsonObjectParser(newJsonFactory()); InputStream inputStream = new ByteArrayInputStream("not json".getBytes(StandardCharsets.UTF_8)); @@ -68,6 +82,7 @@ public void testParse_badJson() throws IOException { } } + @Test public void testParse_bigDecimal() throws IOException { JsonObjectParser parser = new JsonObjectParser(newJsonFactory()); InputStream inputStream = diff --git a/google-http-client-test/src/main/java/com/google/api/client/test/util/store/AbstractDataStoreFactoryTest.java b/google-http-client-test/src/main/java/com/google/api/client/test/util/store/AbstractDataStoreFactoryTest.java index e1e8e4061..7a5f464c8 100644 --- a/google-http-client-test/src/main/java/com/google/api/client/test/util/store/AbstractDataStoreFactoryTest.java +++ b/google-http-client-test/src/main/java/com/google/api/client/test/util/store/AbstractDataStoreFactoryTest.java @@ -14,6 +14,12 @@ package com.google.api.client.test.util.store; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.api.client.util.Beta; import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.DataStoreFactory; @@ -21,7 +27,11 @@ import java.util.Arrays; import java.util.Collection; import java.util.Set; -import junit.framework.TestCase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link DataStoreFactory}. @@ -29,10 +39,17 @@ * @author Yaniv Inbar */ @Beta -public abstract class AbstractDataStoreFactoryTest extends TestCase { +@RunWith(JUnit4.class) +public abstract class AbstractDataStoreFactoryTest { + + private static final String STRING_ID; + private static final String BOOLEAN_ID; + + static { + STRING_ID = "String"; + BOOLEAN_ID = "Boolean"; + } - private static final String STRING_ID = "String"; - private static final String BOOLEAN_ID = "Boolean"; DataStoreFactory dataStore; DataStore stringTyped; DataStore boolTyped; @@ -40,14 +57,14 @@ public abstract class AbstractDataStoreFactoryTest extends TestCase { /** Returns a new instance of the data store factory to test. */ protected abstract DataStoreFactory newDataStoreFactory() throws Exception; - @Override + @Before public void setUp() throws Exception { dataStore = newDataStoreFactory(); stringTyped = dataStore.getDataStore(STRING_ID); boolTyped = dataStore.getDataStore(BOOLEAN_ID); } - @Override + @After public void tearDown() throws Exception { stringTyped.clear(); assertTrue(stringTyped.values().isEmpty()); @@ -59,6 +76,7 @@ private static void assertContentsAnyOrder(Collection c, Object... elts) { assertEquals(Sets.newHashSet(c), Sets.newHashSet(Arrays.asList(elts))); } + @Test public void testId() throws Exception { subtestIdNoException("1"); subtestIdNoException("123456789012345678901234567890"); @@ -83,6 +101,7 @@ private void subtestIdNoException(String id) throws Exception { newDataStoreFactory().getDataStore(id); } + @Test public void testSet() throws Exception { // get null assertNull(stringTyped.get(null)); @@ -123,6 +142,7 @@ public void testSet() throws Exception { assertTrue(boolTyped.get("k")); } + @Test public void testValues() throws Exception { // before assertTrue(stringTyped.values().isEmpty()); @@ -144,6 +164,7 @@ public void testValues() throws Exception { assertContentsAnyOrder(boolTyped.values(), true); } + @Test public void testKeySet() throws Exception { // before assertTrue(stringTyped.keySet().isEmpty()); @@ -164,6 +185,7 @@ public void testKeySet() throws Exception { assertTrue(stringTyped.keySet().isEmpty()); } + @Test public void testDelete() throws Exception { // store with basic values stringTyped.set("k", "v").set("k2", "v2"); @@ -186,6 +208,7 @@ public void testDelete() throws Exception { assertEquals(0, stringTyped.size()); } + @Test public void testClear() throws Exception { // store with basic values stringTyped.set("k", "v").set("k2", "v2"); @@ -199,6 +222,7 @@ public void testClear() throws Exception { assertEquals(0, stringTyped.size()); } + @Test public void testLarge() throws Exception { // TODO(yanivi): size = 1000? need to speed up JdoDataStoreTest first int size = 100; @@ -210,6 +234,7 @@ public void testLarge() throws Exception { assertEquals("hello" + mid, stringTyped.get(String.valueOf(mid))); } + @Test public void testContainsKeyAndValue() throws Exception { // before assertFalse(stringTyped.containsKey("k")); diff --git a/google-http-client-test/src/main/resources/META-INF/native-image/com.google.http-client/google-http-client-test/native-image.properties b/google-http-client-test/src/main/resources/META-INF/native-image/com.google.http-client/google-http-client-test/native-image.properties new file mode 100644 index 000000000..3cbd2b27f --- /dev/null +++ b/google-http-client-test/src/main/resources/META-INF/native-image/com.google.http-client/google-http-client-test/native-image.properties @@ -0,0 +1 @@ +Args=--initialize-at-build-time=org.junit.runner.RunWith,java.lang.annotation.Annotation diff --git a/google-http-client-test/src/test/java/com/google/api/client/test/util/store/FileDataStoreFactoryTest.java b/google-http-client-test/src/test/java/com/google/api/client/test/util/store/FileDataStoreFactoryTest.java index 46918d765..78282861e 100644 --- a/google-http-client-test/src/test/java/com/google/api/client/test/util/store/FileDataStoreFactoryTest.java +++ b/google-http-client-test/src/test/java/com/google/api/client/test/util/store/FileDataStoreFactoryTest.java @@ -14,27 +14,35 @@ package com.google.api.client.test.util.store; +import static java.nio.file.Files.createTempDirectory; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.common.collect.ImmutableSet; -import com.google.common.io.Files; import java.io.File; import java.io.IOException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link FileDataStoreFactory}. * * @author Yaniv Inbar */ +@RunWith(JUnit4.class) public class FileDataStoreFactoryTest extends AbstractDataStoreFactoryTest { @Override protected FileDataStoreFactory newDataStoreFactory() throws IOException { - File dataDir = Files.createTempDir(); + File dataDir = createTempDirectory("temp").toFile(); dataDir.deleteOnExit(); return new FileDataStoreFactory(dataDir); } + @Test public void testSave() throws IOException { FileDataStoreFactory factory = newDataStoreFactory(); DataStore store = factory.getDataStore("foo"); diff --git a/google-http-client-test/src/test/java/com/google/api/client/test/util/store/MemoryDataStoreFactoryTest.java b/google-http-client-test/src/test/java/com/google/api/client/test/util/store/MemoryDataStoreFactoryTest.java index a18384a10..3454f8dba 100644 --- a/google-http-client-test/src/test/java/com/google/api/client/test/util/store/MemoryDataStoreFactoryTest.java +++ b/google-http-client-test/src/test/java/com/google/api/client/test/util/store/MemoryDataStoreFactoryTest.java @@ -16,12 +16,15 @@ import com.google.api.client.util.store.DataStoreFactory; import com.google.api.client.util.store.MemoryDataStoreFactory; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link MemoryDataStoreFactory}. * * @author Yaniv Inbar */ +@RunWith(JUnit4.class) public class MemoryDataStoreFactoryTest extends AbstractDataStoreFactoryTest { @Override diff --git a/google-http-client-xml/src/test/java/com/google/api/client/xml/AtomTest.java b/google-http-client-xml/src/test/java/com/google/api/client/xml/AtomTest.java index f93311d46..b33196b0f 100644 --- a/google-http-client-xml/src/test/java/com/google/api/client/xml/AtomTest.java +++ b/google-http-client-xml/src/test/java/com/google/api/client/xml/AtomTest.java @@ -32,6 +32,8 @@ import java.util.List; import org.junit.Assert; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import org.xmlpull.v1.XmlPullParser; /** @@ -40,6 +42,7 @@ * @author Yaniv Inbar * @author Gerald Madlmayr */ +@RunWith(JUnit4.class) public class AtomTest { private static final String SAMPLE_FEED = diff --git a/google-http-client-xml/src/test/java/com/google/api/client/xml/GenericXmlListTest.java b/google-http-client-xml/src/test/java/com/google/api/client/xml/GenericXmlListTest.java index 0172fccb7..e40f0658d 100644 --- a/google-http-client-xml/src/test/java/com/google/api/client/xml/GenericXmlListTest.java +++ b/google-http-client-xml/src/test/java/com/google/api/client/xml/GenericXmlListTest.java @@ -24,6 +24,8 @@ import java.util.ArrayList; import java.util.Collection; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlSerializer; @@ -35,6 +37,7 @@ * * @author Gerald Madlmayr */ +@RunWith(JUnit4.class) public class GenericXmlListTest { private static final String MULTI_TYPE_WITH_CLASS_TYPE = diff --git a/google-http-client-xml/src/test/java/com/google/api/client/xml/GenericXmlTest.java b/google-http-client-xml/src/test/java/com/google/api/client/xml/GenericXmlTest.java index 02a85cfa9..abc083fcc 100644 --- a/google-http-client-xml/src/test/java/com/google/api/client/xml/GenericXmlTest.java +++ b/google-http-client-xml/src/test/java/com/google/api/client/xml/GenericXmlTest.java @@ -28,6 +28,8 @@ import java.util.List; import java.util.Map; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; @@ -41,6 +43,7 @@ * @author Yaniv Inbar * @author Gerald Madlmayr */ +@RunWith(JUnit4.class) public class GenericXmlTest { private static final String XML = diff --git a/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlEnumTest.java b/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlEnumTest.java index 7cb908d62..b199cb2db 100644 --- a/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlEnumTest.java +++ b/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlEnumTest.java @@ -25,6 +25,8 @@ import java.io.StringReader; import java.util.ArrayList; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlSerializer; @@ -33,6 +35,7 @@ * * @author Gerald Madlmayr */ +@RunWith(JUnit4.class) public class XmlEnumTest { private static final String XML = diff --git a/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlListTest.java b/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlListTest.java index 930d0de86..c12904faa 100644 --- a/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlListTest.java +++ b/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlListTest.java @@ -24,6 +24,8 @@ import java.util.ArrayList; import java.util.Collection; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlSerializer; @@ -32,6 +34,7 @@ * * @author Gerald Madlmayr */ +@RunWith(JUnit4.class) public class XmlListTest { private static final String MULTI_TYPE_WITH_CLASS_TYPE = diff --git a/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlNamespaceDictionaryTest.java b/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlNamespaceDictionaryTest.java index 569477010..562bdb224 100644 --- a/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlNamespaceDictionaryTest.java +++ b/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlNamespaceDictionaryTest.java @@ -14,13 +14,20 @@ package com.google.api.client.xml; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.api.client.util.Key; import com.google.api.client.xml.atom.Atom; import com.google.common.collect.ImmutableMap; import java.io.StringWriter; import java.util.Collection; import java.util.TreeSet; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import org.xmlpull.v1.XmlSerializer; /** @@ -28,7 +35,8 @@ * * @author Yaniv Inbar */ -public class XmlNamespaceDictionaryTest extends TestCase { +@RunWith(JUnit4.class) +public class XmlNamespaceDictionaryTest { private static final String EXPECTED = "One" + "Two"; - public XmlNamespaceDictionaryTest() {} - - public XmlNamespaceDictionaryTest(String name) { - super(name); - } - + @Test public void testSet() { XmlNamespaceDictionary dictionary = new XmlNamespaceDictionary(); dictionary.set("", "http://www.w3.org/2005/Atom").set("gd", "http://schemas.google.com/g/2005"); @@ -78,6 +81,7 @@ public void testSet() { assertTrue(dictionary.getAliasToUriMap().isEmpty()); } + @Test public void testSerialize() throws Exception { Feed feed = new Feed(); feed.entries = new TreeSet(); @@ -93,6 +97,7 @@ public void testSerialize() throws Exception { assertEquals(EXPECTED, writer.toString()); } + @Test public void testSerializeByName() throws Exception { Feed feed = new Feed(); feed.entries = new TreeSet(); @@ -108,6 +113,7 @@ public void testSerializeByName() throws Exception { assertEquals(EXPECTED, writer.toString()); } + @Test public void testSerialize_emptyMap() throws Exception { ImmutableMap map = ImmutableMap.of(); StringWriter writer = new StringWriter(); @@ -119,6 +125,7 @@ public void testSerialize_emptyMap() throws Exception { assertEquals(EXPECTED_EMPTY_MAP, writer.toString()); } + @Test public void testSerializeByName_emptyMap() throws Exception { ImmutableMap map = ImmutableMap.of(); StringWriter writer = new StringWriter(); @@ -130,6 +137,7 @@ public void testSerializeByName_emptyMap() throws Exception { assertEquals(EXPECTED_EMPTY_MAP, writer.toString()); } + @Test public void testSerializeByName_emptyMapAtomNs() throws Exception { ImmutableMap map = ImmutableMap.of(); StringWriter writer = new StringWriter(); @@ -141,6 +149,7 @@ public void testSerializeByName_emptyMapAtomNs() throws Exception { assertEquals(EXPECTED_EMPTY_MAP_ATOM_NS, writer.toString()); } + @Test public void testSerialize_emptyMapNsUndeclared() throws Exception { ImmutableMap map = ImmutableMap.of(); StringWriter writer = new StringWriter(); @@ -151,6 +160,7 @@ public void testSerialize_emptyMapNsUndeclared() throws Exception { assertEquals(EXPECTED_EMPTY_MAP_NS_UNDECLARED, writer.toString()); } + @Test public void testSerialize_errorOnUnknown() throws Exception { Entry entry = new Entry("One", "abc"); StringWriter writer = new StringWriter(); @@ -166,6 +176,7 @@ public void testSerialize_errorOnUnknown() throws Exception { } } + @Test public void testSerializeByName_errorOnUnknown() throws Exception { Entry entry = new Entry("One", "abc"); StringWriter writer = new StringWriter(); @@ -181,6 +192,7 @@ public void testSerializeByName_errorOnUnknown() throws Exception { } } + @Test public void testSerialize_unknown() throws Exception { Feed feed = new Feed(); feed.entries = new TreeSet(); diff --git a/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlTest.java b/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlTest.java index b1345f15c..d9a381424 100644 --- a/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlTest.java +++ b/google-http-client-xml/src/test/java/com/google/api/client/xml/XmlTest.java @@ -28,6 +28,8 @@ import java.util.Collection; import java.util.List; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlSerializer; @@ -37,6 +39,7 @@ * @author Yaniv Inbar * @author Gerald Madlmayr */ +@RunWith(JUnit4.class) public class XmlTest { private static final String SIMPLE_XML = "test"; diff --git a/google-http-client-xml/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-xml/native-image.properties b/google-http-client-xml/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-xml/native-image.properties new file mode 100644 index 000000000..3cbd2b27f --- /dev/null +++ b/google-http-client-xml/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client-xml/native-image.properties @@ -0,0 +1 @@ +Args=--initialize-at-build-time=org.junit.runner.RunWith,java.lang.annotation.Annotation diff --git a/google-http-client/src/main/java/com/google/api/client/util/store/AbstractDataStoreFactory.java b/google-http-client/src/main/java/com/google/api/client/util/store/AbstractDataStoreFactory.java index 0136e5a32..d70de7d43 100644 --- a/google-http-client/src/main/java/com/google/api/client/util/store/AbstractDataStoreFactory.java +++ b/google-http-client/src/main/java/com/google/api/client/util/store/AbstractDataStoreFactory.java @@ -14,13 +14,15 @@ package com.google.api.client.util.store; +import static com.google.api.client.util.Preconditions.checkArgument; + import com.google.api.client.util.Maps; -import com.google.api.client.util.Preconditions; import java.io.IOException; import java.io.Serializable; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Logger; import java.util.regex.Pattern; /** @@ -41,11 +43,19 @@ public abstract class AbstractDataStoreFactory implements DataStoreFactory { * Pattern to control possible values for the {@code id} parameter of {@link * #getDataStore(String)}. */ - private static final Pattern ID_PATTERN = Pattern.compile("\\w{1,30}"); + private static final Pattern ID_PATTERN; + + static { + try { + ID_PATTERN = Pattern.compile("\\w{1,30}"); + } catch (Throwable t) { + Logger.getLogger(AbstractDataStoreFactory.class.getName()).severe(t.getMessage()); + throw t; + } + } public final DataStore getDataStore(String id) throws IOException { - Preconditions.checkArgument( - ID_PATTERN.matcher(id).matches(), "%s does not match pattern %s", id, ID_PATTERN); + checkArgument(ID_PATTERN.matcher(id).matches(), "%s does not match pattern %s", id, ID_PATTERN); lock.lock(); try { @SuppressWarnings("unchecked") diff --git a/google-http-client/src/main/java/com/google/api/client/util/store/FileDataStoreFactory.java b/google-http-client/src/main/java/com/google/api/client/util/store/FileDataStoreFactory.java index 98c5003ef..16b33b093 100644 --- a/google-http-client/src/main/java/com/google/api/client/util/store/FileDataStoreFactory.java +++ b/google-http-client/src/main/java/com/google/api/client/util/store/FileDataStoreFactory.java @@ -37,6 +37,7 @@ import java.util.HashSet; import java.util.Locale; import java.util.Set; +import java.util.logging.Logger; /** * Thread-safe file implementation of a credential store. @@ -54,8 +55,17 @@ */ public class FileDataStoreFactory extends AbstractDataStoreFactory { - private static final boolean IS_WINDOWS = - StandardSystemProperty.OS_NAME.value().toLowerCase(Locale.ENGLISH).startsWith("windows"); + private static final boolean IS_WINDOWS; + + static { + try { + IS_WINDOWS = + StandardSystemProperty.OS_NAME.value().toLowerCase(Locale.ENGLISH).startsWith("windows"); + } catch (Throwable ex) { + Logger.getLogger(FileDataStoreFactory.class.getName()).severe(ex.getMessage()); + throw ex; + } + } /** Directory to store data. */ private final File dataDirectory; diff --git a/google-http-client/src/test/java/com/google/api/client/http/AbstractHttpContentTest.java b/google-http-client/src/test/java/com/google/api/client/http/AbstractHttpContentTest.java index 93f3fa963..0d916512e 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/AbstractHttpContentTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/AbstractHttpContentTest.java @@ -14,17 +14,23 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link AbstractHttpContent}. * * @author Yaniv Inbar */ -public class AbstractHttpContentTest extends TestCase { +@RunWith(JUnit4.class) +public class AbstractHttpContentTest { static class TestHttpContent extends AbstractHttpContent { @@ -54,11 +60,13 @@ public boolean retrySupported() { } } + @Test public void testRetrySupported() { AbstractHttpContent content = new TestHttpContent(true, 0); assertTrue(content.retrySupported()); } + @Test public void testComputeLength() throws Exception { subtestComputeLength(true, 0, 0); subtestComputeLength(true, 1, 1); diff --git a/google-http-client/src/test/java/com/google/api/client/http/BasicAuthenticationTest.java b/google-http-client/src/test/java/com/google/api/client/http/BasicAuthenticationTest.java index a76081275..be7e3dd83 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/BasicAuthenticationTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/BasicAuthenticationTest.java @@ -14,16 +14,21 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; + import com.google.api.client.testing.http.HttpTesting; import com.google.api.client.testing.http.MockHttpTransport; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link BasicAuthentication}. * * @author Yaniv Inbar */ -public class BasicAuthenticationTest extends TestCase { +@RunWith(JUnit4.class) +public class BasicAuthenticationTest { static final String USERNAME = "Aladdin"; @@ -31,12 +36,14 @@ public class BasicAuthenticationTest extends TestCase { static final String AUTH_HEADER = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; + @Test public void testConstructor() { BasicAuthentication auth = new BasicAuthentication(USERNAME, PASSWORD); assertEquals(USERNAME, auth.getUsername()); assertEquals(PASSWORD, auth.getPassword()); } + @Test public void testInitialize() throws Exception { BasicAuthentication auth = new BasicAuthentication(USERNAME, PASSWORD); HttpRequest request = diff --git a/google-http-client/src/test/java/com/google/api/client/http/ByteArrayContentTest.java b/google-http-client/src/test/java/com/google/api/client/http/ByteArrayContentTest.java index da73c5437..66f28c53d 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/ByteArrayContentTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/ByteArrayContentTest.java @@ -14,20 +14,28 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.api.client.util.IOUtils; import com.google.api.client.util.StringUtils; import java.io.ByteArrayOutputStream; import java.io.IOException; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link ByteArrayContent}. * * @author Yaniv Inbar */ -public class ByteArrayContentTest extends TestCase { +@RunWith(JUnit4.class) +public class ByteArrayContentTest { private static final byte[] FOO = StringUtils.getBytesUtf8("foo"); + @Test public void testConstructor() throws IOException { subtestConstructor(new ByteArrayContent("type", FOO), "foo"); subtestConstructor(new ByteArrayContent("type", FOO, 0, 3), "foo"); diff --git a/google-http-client/src/test/java/com/google/api/client/http/ConsumingInputStreamTest.java b/google-http-client/src/test/java/com/google/api/client/http/ConsumingInputStreamTest.java index afcdf2bf5..d86a1d811 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/ConsumingInputStreamTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/ConsumingInputStreamTest.java @@ -22,7 +22,10 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +@RunWith(JUnit4.class) public class ConsumingInputStreamTest { @Test diff --git a/google-http-client/src/test/java/com/google/api/client/http/EmptyContentTest.java b/google-http-client/src/test/java/com/google/api/client/http/EmptyContentTest.java index 743fc75e1..06e942a38 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/EmptyContentTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/EmptyContentTest.java @@ -14,17 +14,25 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + import java.io.ByteArrayOutputStream; import java.io.IOException; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link EmptyContent}. * * @author Yaniv Inbar */ -public class EmptyContentTest extends TestCase { +@RunWith(JUnit4.class) +public class EmptyContentTest { + @Test public void test() throws IOException { EmptyContent content = new EmptyContent(); assertEquals(0L, content.getLength()); diff --git a/google-http-client/src/test/java/com/google/api/client/http/ExponentialBackOffPolicyTest.java b/google-http-client/src/test/java/com/google/api/client/http/ExponentialBackOffPolicyTest.java index 5a0cb0494..159305d43 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/ExponentialBackOffPolicyTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/ExponentialBackOffPolicyTest.java @@ -14,8 +14,13 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.google.api.client.util.NanoClock; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link ExponentialBackOffPolicy}. @@ -23,12 +28,10 @@ * @author Ravi Mistry */ @Deprecated -public class ExponentialBackOffPolicyTest extends TestCase { - - public ExponentialBackOffPolicyTest(String name) { - super(name); - } +@RunWith(JUnit4.class) +public class ExponentialBackOffPolicyTest { + @Test public void testConstructor() { ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy(); assertEquals( @@ -39,8 +42,9 @@ public void testConstructor() { backOffPolicy.getCurrentIntervalMillis()); assertEquals( ExponentialBackOffPolicy.DEFAULT_RANDOMIZATION_FACTOR, - backOffPolicy.getRandomizationFactor()); - assertEquals(ExponentialBackOffPolicy.DEFAULT_MULTIPLIER, backOffPolicy.getMultiplier()); + backOffPolicy.getRandomizationFactor(), + 0); + assertEquals(ExponentialBackOffPolicy.DEFAULT_MULTIPLIER, backOffPolicy.getMultiplier(), 0); assertEquals( ExponentialBackOffPolicy.DEFAULT_MAX_INTERVAL_MILLIS, backOffPolicy.getMaxIntervalMillis()); assertEquals( @@ -48,6 +52,7 @@ public void testConstructor() { backOffPolicy.getMaxElapsedTimeMillis()); } + @Test public void testBuilder() { ExponentialBackOffPolicy backOffPolicy = ExponentialBackOffPolicy.builder().build(); assertEquals( @@ -58,8 +63,9 @@ public void testBuilder() { backOffPolicy.getCurrentIntervalMillis()); assertEquals( ExponentialBackOffPolicy.DEFAULT_RANDOMIZATION_FACTOR, - backOffPolicy.getRandomizationFactor()); - assertEquals(ExponentialBackOffPolicy.DEFAULT_MULTIPLIER, backOffPolicy.getMultiplier()); + backOffPolicy.getRandomizationFactor(), + 0); + assertEquals(ExponentialBackOffPolicy.DEFAULT_MULTIPLIER, backOffPolicy.getMultiplier(), 0); assertEquals( ExponentialBackOffPolicy.DEFAULT_MAX_INTERVAL_MILLIS, backOffPolicy.getMaxIntervalMillis()); assertEquals( @@ -82,12 +88,13 @@ public void testBuilder() { .build(); assertEquals(testInitialInterval, backOffPolicy.getInitialIntervalMillis()); assertEquals(testInitialInterval, backOffPolicy.getCurrentIntervalMillis()); - assertEquals(testRandomizationFactor, backOffPolicy.getRandomizationFactor()); - assertEquals(testMultiplier, backOffPolicy.getMultiplier()); + assertEquals(testRandomizationFactor, backOffPolicy.getRandomizationFactor(), 0); + assertEquals(testMultiplier, backOffPolicy.getMultiplier(), 0); assertEquals(testMaxInterval, backOffPolicy.getMaxIntervalMillis()); assertEquals(testMaxElapsedTime, backOffPolicy.getMaxElapsedTimeMillis()); } + @Test public void testBackOff() throws Exception { int testInitialInterval = 500; double testRandomizationFactor = 0.1; @@ -130,6 +137,7 @@ public long nanoTime() { } } + @Test public void testGetElapsedTimeMillis() { ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy.Builder().setNanoClock(new MyNanoClock()).build(); @@ -137,6 +145,7 @@ public void testGetElapsedTimeMillis() { assertEquals("elapsedTimeMillis=" + elapsedTimeMillis, 1000, elapsedTimeMillis); } + @Test public void testBackOffOverflow() throws Exception { int testInitialInterval = Integer.MAX_VALUE / 2; double testMultiplier = 2.1; diff --git a/google-http-client/src/test/java/com/google/api/client/http/GZipEncodingTest.java b/google-http-client/src/test/java/com/google/api/client/http/GZipEncodingTest.java index 4963b05bd..e73edc311 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/GZipEncodingTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/GZipEncodingTest.java @@ -14,19 +14,24 @@ package com.google.api.client.http; +import static org.junit.Assert.assertFalse; + import com.google.api.client.testing.util.TestableByteArrayOutputStream; import com.google.api.client.util.ByteArrayStreamingContent; import com.google.api.client.util.StringUtils; import java.io.IOException; -import junit.framework.TestCase; import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link GZipEncoding}. * * @author Yaniv Inbar */ -public class GZipEncodingTest extends TestCase { +@RunWith(JUnit4.class) +public class GZipEncodingTest { private static final byte[] EXPECED_ZIPPED = new byte[] { @@ -42,6 +47,7 @@ public class GZipEncodingTest extends TestCase { 0, 0, 0, 0, 0, 0, 0, 0 }; + @Test public void test() throws IOException { // TODO: remove when no longer using Java < 16. byte[] expected = diff --git a/google-http-client/src/test/java/com/google/api/client/http/GenericUrlTest.java b/google-http-client/src/test/java/com/google/api/client/http/GenericUrlTest.java index dbe1cc931..1e2dfddf1 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/GenericUrlTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/GenericUrlTest.java @@ -14,6 +14,11 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + import com.google.api.client.util.Key; import java.net.MalformedURLException; import java.net.URI; @@ -24,24 +29,21 @@ import java.util.Collection; import java.util.Iterator; import java.util.List; -import junit.framework.TestCase; -import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link GenericUrl}. * * @author Yaniv Inbar */ -public class GenericUrlTest extends TestCase { - - public GenericUrlTest() {} - - public GenericUrlTest(String name) { - super(name); - } +@RunWith(JUnit4.class) +public class GenericUrlTest { private static final String MINIMAL = "http://bar"; + @Test public void testBuild_minimal() { GenericUrl url = new GenericUrl(); url.setScheme("http"); @@ -49,6 +51,7 @@ public void testBuild_minimal() { assertEquals(MINIMAL, url.build()); } + @Test public void testParse_minimal() { GenericUrl url = new GenericUrl(MINIMAL); assertEquals("http", url.getScheme()); @@ -56,6 +59,7 @@ public void testParse_minimal() { private static final String NO_PATH = "http://bar?a=b"; + @Test public void testBuild_noPath() { GenericUrl url = new GenericUrl(); url.setScheme("http"); @@ -64,11 +68,13 @@ public void testBuild_noPath() { assertEquals(NO_PATH, url.build()); } + @Test public void testBuild_noUserInfo() { GenericUrl url = new GenericUrl(NO_PATH); assertNull(url.getUserInfo()); } + @Test public void testBuild_noScheme() { GenericUrl url = new GenericUrl(); try { @@ -79,6 +85,7 @@ public void testBuild_noScheme() { } } + @Test public void testBuild_noHost() { GenericUrl url = new GenericUrl(); try { @@ -90,6 +97,7 @@ public void testBuild_noHost() { } } + @Test public void testParse_noPath() { GenericUrl url = new GenericUrl(NO_PATH); assertEquals("http", url.getScheme()); @@ -102,6 +110,7 @@ public void testParse_noPath() { private static final List SHORT_PATH_PARTS = Arrays.asList("", "path"); + @Test public void testBuild_shortPath() { GenericUrl url = new GenericUrl(); url.setScheme("http"); @@ -111,6 +120,7 @@ public void testBuild_shortPath() { assertEquals(SHORT_PATH, url.build()); } + @Test public void testParse_shortPath() { GenericUrl url = new GenericUrl(SHORT_PATH); assertEquals("http", url.getScheme()); @@ -123,6 +133,7 @@ public void testParse_shortPath() { private static final List LONG_PATH_PARTS = Arrays.asList("", "path", "to", "resource"); + @Test public void testBuild_longPath() { GenericUrl url = new GenericUrl(); url.setScheme("http"); @@ -132,6 +143,7 @@ public void testBuild_longPath() { assertEquals(LONG_PATH, url.build()); } + @Test public void testParse_longPath() { GenericUrl url = new GenericUrl(LONG_PATH); assertEquals("http", url.getScheme()); @@ -172,6 +184,7 @@ public TestUrl(String encodedUrl, boolean verbatim) { private static final String USER_INFO = "user:"; private static final String FRAGMENT = ""; + @Test public void testBuild_full() { TestUrl url = new TestUrl(); url.setScheme("https"); @@ -189,6 +202,7 @@ public void testBuild_full() { assertEquals(FULL, url.build()); } + @Test public void testParse_full() { TestUrl url = new TestUrl(FULL); subtestFull(url); @@ -197,27 +211,32 @@ public void testParse_full() { assertEquals("bar", url.foo); } + @Test public void testParse_full_verbatim() { TestUrl url = new TestUrl(FULL, true); assertNull(url.hidden); assertEquals("Go%3D%23/%25%26%20?%3Co%3Egle", url.getFirst("q")); } + @Test public void testConstructor_url() throws MalformedURLException { GenericUrl url = new GenericUrl(new URL(FULL)); subtestFull(url); } + @Test public void testConstructor_uri() throws URISyntaxException { GenericUrl url = new GenericUrl(new URI(FULL)); subtestFull(url); } + @Test public void testConstructor_string() { GenericUrl url = new GenericUrl(FULL); subtestFull(url); } + @Test public void testConstructor_schemeToLowerCase() throws URISyntaxException, MalformedURLException { GenericUrl url = new GenericUrl("HTTps://www.google.com:223"); assertEquals("https", url.getScheme()); @@ -274,6 +293,7 @@ public FieldTypesUrl set(String fieldName, Object value) { private static final String FIELD_TYPES = "http://bar?B=true&D=-3.14&I=-3&b=true&d=-3.14&i=-3&s=a&a=b"; + @Test public void testBuild_fieldTypes() { FieldTypesUrl url = new FieldTypesUrl(); url.setScheme("http"); @@ -290,6 +310,7 @@ public void testBuild_fieldTypes() { assertEquals(FIELD_TYPES, url.build()); } + @Test public void testParse_fieldTypes() { FieldTypesUrl url = new FieldTypesUrl(FIELD_TYPES); assertEquals("http", url.getScheme()); @@ -308,6 +329,7 @@ public void testParse_fieldTypes() { private static final String FRAGMENT1 = "http://bar/path/to/resource#fragme=%23/%25&%20?%3Co%3Ent"; + @Test public void testBuild_fragment1() { GenericUrl url = new GenericUrl(); url.setScheme("http"); @@ -317,6 +339,7 @@ public void testBuild_fragment1() { assertEquals(FRAGMENT1, url.build()); } + @Test public void testParse_fragment1() { GenericUrl url = new GenericUrl(FRAGMENT1); assertEquals("http", url.getScheme()); @@ -327,6 +350,7 @@ public void testParse_fragment1() { private static final String FRAGMENT2 = "http://bar/path/to/resource?a=b#fragment"; + @Test public void testBuild_fragment2() { GenericUrl url = new GenericUrl(); url.setScheme("http"); @@ -337,6 +361,7 @@ public void testBuild_fragment2() { assertEquals(FRAGMENT2, url.build()); } + @Test public void testParse_fragment2() { GenericUrl url = new GenericUrl(FRAGMENT2); assertEquals("http", url.getScheme()); @@ -346,6 +371,7 @@ public void testParse_fragment2() { assertEquals("fragment", url.getFragment()); } + @Test public void testBuildAuthority_exception() { // Test without a scheme. GenericUrl url = new GenericUrl(); @@ -353,7 +379,7 @@ public void testBuildAuthority_exception() { try { url.buildAuthority(); - Assert.fail("no exception was thrown"); + fail("no exception was thrown"); } catch (NullPointerException expected) { } @@ -363,11 +389,12 @@ public void testBuildAuthority_exception() { try { url.buildAuthority(); - Assert.fail("no exception was thrown"); + fail("no exception was thrown"); } catch (NullPointerException expected) { } } + @Test public void testBuildAuthority_simple() { GenericUrl url = new GenericUrl(); url.setScheme("http"); @@ -375,6 +402,7 @@ public void testBuildAuthority_simple() { assertEquals("http://example.com", url.buildAuthority()); } + @Test public void testBuildAuthority_withPort() { GenericUrl url = new GenericUrl(); url.setScheme("http"); @@ -383,6 +411,7 @@ public void testBuildAuthority_withPort() { assertEquals("http://example.com:1234", url.buildAuthority()); } + @Test public void testBuildAuthority_withUserInfo() { GenericUrl url = new GenericUrl(); url.setScheme("http"); @@ -391,6 +420,7 @@ public void testBuildAuthority_withUserInfo() { assertEquals("http://first.last:pa%40%40@www.example.com", url.buildAuthority()); } + @Test public void testBuildRelativeUrl_empty() { GenericUrl url = new GenericUrl(); url.setScheme("foo"); @@ -399,6 +429,7 @@ public void testBuildRelativeUrl_empty() { assertEquals("", url.buildRelativeUrl()); } + @Test public void testBuildRelativeUrl_simple() { GenericUrl url = new GenericUrl(); url.setScheme("foo"); @@ -407,6 +438,7 @@ public void testBuildRelativeUrl_simple() { assertEquals("/example", url.buildRelativeUrl()); } + @Test public void testBuildRelativeUrl_simpleQuery() { GenericUrl url = new GenericUrl(); url.setScheme("foo"); @@ -416,6 +448,7 @@ public void testBuildRelativeUrl_simpleQuery() { assertEquals("/example?key=value", url.buildRelativeUrl()); } + @Test public void testBuildRelativeUrl_fragment() { GenericUrl url = new GenericUrl(); url.setScheme("foo"); @@ -425,6 +458,7 @@ public void testBuildRelativeUrl_fragment() { assertEquals("/example#test", url.buildRelativeUrl()); } + @Test public void testBuildRelativeUrl_onlyQuery() { GenericUrl url = new GenericUrl(); url.setScheme("foo"); @@ -437,6 +471,7 @@ public void testBuildRelativeUrl_onlyQuery() { private static final String BASE_URL = "http://google.com"; private static final String FULL_PATH = "/some/path/someone%2Fis%2F@gmail.com/test/?one=1&two=2"; + @Test public void testBuildRelativeUrl_full() { GenericUrl url = new GenericUrl(BASE_URL + FULL_PATH); assertEquals(FULL_PATH, url.buildRelativeUrl()); @@ -448,6 +483,7 @@ public void testBuildRelativeUrl_full() { private static final List PATH_WITH_SLASH_PARTS = Arrays.asList("", "m8", "feeds", "contacts", "someone/is/@gmail.com", "full", ""); + @Test public void testBuild_pathWithSlash() { GenericUrl url = new GenericUrl(); url.setScheme("http"); @@ -456,12 +492,14 @@ public void testBuild_pathWithSlash() { assertEquals(PATH_WITH_SLASH, url.build()); } + @Test public void testConstructorUnderscore() { String url = "http://url_with_underscore.google.com"; GenericUrl parsed = new GenericUrl(url); assertEquals("url_with_underscore.google.com", parsed.getHost()); } + @Test public void testParse_pathWithSlash() { GenericUrl url = new GenericUrl(PATH_WITH_SLASH); assertEquals("http", url.getScheme()); @@ -469,6 +507,7 @@ public void testParse_pathWithSlash() { assertEquals(PATH_WITH_SLASH_PARTS, url.getPathParts()); } + @Test public void testToPathParts() { subtestToPathParts(null, (String[]) null); subtestToPathParts(null, ""); @@ -493,6 +532,7 @@ private void subtestToPathParts(String encodedPath, String... expectedDecodedPar } } + @Test public void testAppendPath() { GenericUrl url = new GenericUrl("http://google.com"); assertNull(url.getPathParts()); @@ -525,6 +565,7 @@ public void testAppendPath() { private static final String REPEATED_PARAM = PREFIX + REPEATED_PARAM_PATH + "?q=c&q=a&q=b&s=e"; + @Test public void testRepeatedParam_build() { GenericUrl url = new GenericUrl(); url.setScheme("https"); @@ -535,6 +576,7 @@ public void testRepeatedParam_build() { assertEquals(REPEATED_PARAM, url.build()); } + @Test public void testRepeatedParam_parse() { GenericUrl url = new GenericUrl(REPEATED_PARAM); assertEquals("https", url.getScheme()); @@ -552,6 +594,7 @@ public void testRepeatedParam_parse() { assertEquals(Arrays.asList("c", "a", "b"), new ArrayList(url.getAll("q"))); } + @Test public void testBuild_noValue() { GenericUrl url = new GenericUrl(); url.setScheme("https"); @@ -561,12 +604,14 @@ public void testBuild_noValue() { assertEquals(PREFIX + REPEATED_PARAM_PATH + "?noval", url.build()); } + @Test public void testClone() { GenericUrl url = new GenericUrl("http://www.google.com"); GenericUrl clone = url.clone(); assertEquals("http://www.google.com", clone.build()); } + @Test public void testToUrl_relative() { // relative redirect testRedirectUtility("http://www.google.com/test", "http://www.google.com", "/test"); diff --git a/google-http-client/src/test/java/com/google/api/client/http/GzipSupportTest.java b/google-http-client/src/test/java/com/google/api/client/http/GzipSupportTest.java index f7c863222..ba7d2df32 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/GzipSupportTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/GzipSupportTest.java @@ -27,7 +27,10 @@ import java.io.SequenceInputStream; import java.util.zip.GZIPInputStream; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +@RunWith(JUnit4.class) public final class GzipSupportTest { @SuppressWarnings("UnstableApiUsage") // CountingInputStream is @Beta diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffIOExpcetionHandlerTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffIOExpcetionHandlerTest.java index ae0ae125f..f2760c447 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffIOExpcetionHandlerTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffIOExpcetionHandlerTest.java @@ -14,21 +14,28 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.google.api.client.testing.util.MockBackOff; import com.google.api.client.testing.util.MockSleeper; import com.google.api.client.util.BackOff; import com.google.api.client.util.Sleeper; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link HttpBackOffIOExceptionHandler}. * * @author Eyal Peled */ -public class HttpBackOffIOExpcetionHandlerTest extends TestCase { +@RunWith(JUnit4.class) +public class HttpBackOffIOExpcetionHandlerTest { + @Test public void testHandle() throws IOException { subsetHandle(0, 0, true, BackOff.STOP_BACKOFF); subsetHandle(0, 0, false, new MockBackOff().setBackOffMillis(0).setMaxTries(5)); @@ -49,6 +56,7 @@ public void subsetHandle(long count, long millis, boolean retrySupported, BackOf assertEquals(count, sleeper.getCount()); } + @Test public void testHandleIOException_returnsFalseAndThreadRemainsInterrupted_whenSleepIsInterrupted() throws Exception { final AtomicBoolean stillInterrupted = new AtomicBoolean(false); diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandlerTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandlerTest.java index afe9ff65d..daefab430 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandlerTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandlerTest.java @@ -14,6 +14,9 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler.BackOffRequired; import com.google.api.client.testing.util.MockBackOff; import com.google.api.client.testing.util.MockSleeper; @@ -21,19 +24,24 @@ import com.google.api.client.util.Sleeper; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Test {@link HttpBackOffUnsuccessfulResponseHandler}. * * @author Eyal Peled */ -public class HttpBackOffUnsuccessfulResponseHandlerTest extends TestCase { +@RunWith(JUnit4.class) +public class HttpBackOffUnsuccessfulResponseHandlerTest { + @Test public void testHandleResponse_retryFalse() throws IOException { subsetHandleResponse(0, 0, false, new MockBackOff(), BackOffRequired.ALWAYS); } + @Test public void testHandleResponse_requiredFalse() throws IOException { subsetHandleResponse( 0, @@ -47,6 +55,7 @@ public boolean isRequired(HttpResponse response) { }); } + @Test public void testHandleResponse_requiredTrue() throws IOException { BackOff backOff = new MockBackOff().setBackOffMillis(4).setMaxTries(7); subsetHandleResponse(7, 4, true, backOff, BackOffRequired.ALWAYS); @@ -70,6 +79,7 @@ private void subsetHandleResponse( assertEquals(count, sleeper.getCount()); } + @Test public void testHandleResponse_returnsFalseAndThreadRemainsInterrupted_whenSleepIsInterrupted() throws Exception { final AtomicBoolean stillInterrupted = new AtomicBoolean(false); diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpEncodingStreamingContentTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpEncodingStreamingContentTest.java index 265814722..96c16a244 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpEncodingStreamingContentTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpEncodingStreamingContentTest.java @@ -14,19 +14,24 @@ package com.google.api.client.http; +import static org.junit.Assert.assertFalse; + import com.google.api.client.testing.util.TestableByteArrayOutputStream; import com.google.api.client.util.ByteArrayStreamingContent; import com.google.api.client.util.StringUtils; import java.io.IOException; -import junit.framework.TestCase; import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link HttpEncodingStreamingContent}. * * @author Yaniv Inbar */ -public class HttpEncodingStreamingContentTest extends TestCase { +@RunWith(JUnit4.class) +public class HttpEncodingStreamingContentTest { private static final byte[] EXPECED_ZIPPED = new byte[] { @@ -42,6 +47,7 @@ public class HttpEncodingStreamingContentTest extends TestCase { 0, 0, 0, 0, 0, 0, 0, 0 }; + @Test public void test() throws IOException { // TODO: remove when no longer using Java < 16. byte[] expected = diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpHeadersTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpHeadersTest.java index 70f76cd32..3b9baf113 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpHeadersTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpHeadersTest.java @@ -14,6 +14,10 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + import com.google.api.client.http.HttpRequestTest.E; import com.google.api.client.testing.http.MockLowLevelHttpRequest; import com.google.api.client.testing.http.MockLowLevelHttpResponse; @@ -25,21 +29,19 @@ import java.io.Writer; import java.util.Arrays; import java.util.List; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link HttpHeaders}. * * @author Yaniv Inbar */ -public class HttpHeadersTest extends TestCase { - - public HttpHeadersTest() {} - - public HttpHeadersTest(String name) { - super(name); - } +@RunWith(JUnit4.class) +public class HttpHeadersTest { + @Test public void testBasicAuthentication() { HttpHeaders headers = new HttpHeaders(); headers.setBasicAuthentication( @@ -66,6 +68,7 @@ public static class MyHeaders extends HttpHeaders { @Key E otherValue; } + @Test public void testSerializeHeaders() throws Exception { // custom headers MyHeaders myHeaders = new MyHeaders(); @@ -131,6 +134,7 @@ public void testSerializeHeaders() throws Exception { } @SuppressWarnings("unchecked") + @Test public void testFromHttpHeaders() { HttpHeaders rawHeaders = new HttpHeaders(); rawHeaders.setContentLength(Long.MAX_VALUE); @@ -169,6 +173,7 @@ public void testFromHttpHeaders() { private static final String AUTHORIZATION_HEADERS = "Accept-Encoding: gzip\r\nAuthorization: Foo\r\nAuthorization: Bar\r\n"; + @Test public void testAuthorizationHeader() throws IOException { // serialization HttpHeaders headers = new HttpHeaders(); @@ -187,6 +192,7 @@ public void testAuthorizationHeader() throws IOException { assertTrue(authHeader.toString(), ImmutableList.of("Foo", "Bar").equals(authHeader)); } + @Test public void testHeaderStringValues() { // custom headers MyHeaders myHeaders = new MyHeaders(); @@ -236,6 +242,7 @@ public static class SlugHeaders extends HttpHeaders { String slug; } + @Test public void testParseAge() throws Exception { MockLowLevelHttpResponse httpResponse = new MockLowLevelHttpResponse() @@ -247,6 +254,7 @@ public void testParseAge() throws Exception { assertEquals(3456L, httpHeaders.getAge().longValue()); } + @Test public void testFromHttpResponse_normalFlow() throws Exception { MockLowLevelHttpResponse httpResponse = new MockLowLevelHttpResponse() @@ -266,6 +274,7 @@ public void testFromHttpResponse_normalFlow() throws Exception { assertEquals("123456789", slugHeaders.slug); } + @Test public void testFromHttpResponse_doubleConvert() throws Exception { MockLowLevelHttpResponse httpResponse = new MockLowLevelHttpResponse() @@ -285,6 +294,7 @@ public void testFromHttpResponse_doubleConvert() throws Exception { assertEquals("123456789", slugHeaders2.slug); } + @Test public void testFromHttpResponse_clearOldValue() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.put("Foo", "oldValue"); @@ -301,7 +311,8 @@ public static class V extends HttpHeaders { @Key String s; } - public void testFromHttpResponse_void(String value) throws Exception { + @Test + public void testFromHttpResponse_void() throws Exception { MockLowLevelHttpResponse httpResponse = new MockLowLevelHttpResponse() .setHeaderNames(Arrays.asList("v", "v", "s")) diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpMediaTypeTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpMediaTypeTest.java index 91342a144..da5600a2e 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpMediaTypeTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpMediaTypeTest.java @@ -14,9 +14,14 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import com.google.common.base.Charsets; import com.google.common.testing.EqualsTester; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests for the {@link HttpMediaType} class. @@ -24,18 +29,22 @@ * @author Matthias Linder (mlinder) * @since 1.10 */ -public class HttpMediaTypeTest extends TestCase { +@RunWith(JUnit4.class) +public class HttpMediaTypeTest { + @Test public void testBuild() { HttpMediaType m = new HttpMediaType("main", "sub"); assertEquals("main/sub", m.build()); } + @Test public void testBuild_star() { HttpMediaType m = new HttpMediaType("*", "*"); assertEquals("*/*", m.build()); } + @Test public void testBuild_parameters() { HttpMediaType m = new HttpMediaType("main", "sub"); m.setParameter("bbb", ";/ "); @@ -43,35 +52,41 @@ public void testBuild_parameters() { assertEquals("main/sub; aaa=1; bbb=\";/ \"", m.build()); } + @Test public void testBuild_json() { HttpMediaType m = new HttpMediaType("application/json").setCharsetParameter(Charsets.UTF_8); assertEquals("application/json; charset=UTF-8", m.build()); } + @Test public void testBuild_multipartSpec() { HttpMediaType m = new HttpMediaType("main", "sub"); m.setParameter("bbb", "foo=/bar"); assertEquals("main/sub; bbb=\"foo=/bar\"", m.build()); } + @Test public void testBuild_parametersCasing() { HttpMediaType m = new HttpMediaType("main", "sub"); m.setParameter("foo", "FooBar"); assertEquals("main/sub; foo=FooBar", m.build()); } + @Test public void testFromString() { HttpMediaType m = new HttpMediaType("main/sub"); assertEquals("main", m.getType()); assertEquals("sub", m.getSubType()); } + @Test public void testFromString_star() { HttpMediaType m = new HttpMediaType("text/*"); assertEquals("text", m.getType()); assertEquals("*", m.getSubType()); } + @Test public void testFromString_null() { try { new HttpMediaType(null); @@ -80,6 +95,7 @@ public void testFromString_null() { } } + @Test public void testFromString_multipartSpec() { // Values allowed by the spec: http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html String value = "f00'()+_,-./:=?bar"; @@ -88,6 +104,7 @@ public void testFromString_multipartSpec() { assertEquals("bar", m.getParameter("foo")); } + @Test public void testFromString_full() { HttpMediaType m = new HttpMediaType("text/plain; charset=utf-8; foo=\"foo; =bar\""); assertEquals("text", m.getType()); @@ -97,15 +114,18 @@ public void testFromString_full() { assertEquals(2, m.getParameters().size()); } + @Test public void testFromString_case() { HttpMediaType m = new HttpMediaType("text/plain; Foo=Bar"); assertEquals("Bar", m.getParameter("fOO")); } + @Test public void testSetMainType() { assertEquals("foo", new HttpMediaType("text", "plain").setType("foo").getType()); } + @Test public void testSetMainType_invalid() { try { new HttpMediaType("text", "plain").setType("foo/bar"); @@ -114,10 +134,12 @@ public void testSetMainType_invalid() { } } + @Test public void testSetSubType() { assertEquals("foo", new HttpMediaType("text", "plain").setSubType("foo").getSubType()); } + @Test public void testSetSubType_invalid() { try { new HttpMediaType("text", "plain").setSubType("foo/bar"); @@ -126,6 +148,7 @@ public void testSetSubType_invalid() { } } + @Test public void testSetParameter_casing() { HttpMediaType mt = new HttpMediaType("text", "plain"); mt.setParameter("Foo", "Bar"); @@ -145,6 +168,7 @@ private void assertFullSerialization(String str) { assertEquals(str, new HttpMediaType(str).build()); } + @Test public void testFullSerialization() { assertFullSerialization("text/plain"); assertFullSerialization("text/plain; foo=bar"); @@ -155,6 +179,7 @@ public void testFullSerialization() { assertFullSerialization("text/*; charset=utf-8; foo=\"bar bar bar\""); } + @Test public void testInvalidCharsRegex() { assertEquals(false, containsInvalidChar("foo")); assertEquals(false, containsInvalidChar("X-Foo-Bar")); @@ -163,6 +188,7 @@ public void testInvalidCharsRegex() { assertEquals(true, containsInvalidChar("foo;bar")); } + @Test public void testCharset() { HttpMediaType hmt = new HttpMediaType("foo/bar"); assertEquals(null, hmt.getCharsetParameter()); @@ -171,6 +197,7 @@ public void testCharset() { assertEquals(Charsets.UTF_8, hmt.getCharsetParameter()); } + @Test public void testEqualsIgnoreParameters() { assertEquals( true, new HttpMediaType("foo/bar").equalsIgnoreParameters(new HttpMediaType("Foo/bar"))); @@ -183,6 +210,7 @@ public void testEqualsIgnoreParameters() { assertEquals(false, new HttpMediaType("foo/bar").equalsIgnoreParameters(null)); } + @Test public void testEqualsIgnoreParameters_static() { assertEquals(true, HttpMediaType.equalsIgnoreParameters(null, null)); assertEquals(false, HttpMediaType.equalsIgnoreParameters(null, "foo/bar")); @@ -190,6 +218,7 @@ public void testEqualsIgnoreParameters_static() { assertEquals(true, HttpMediaType.equalsIgnoreParameters("foo/bar; a=c", "foo/bar; b=d")); } + @Test public void testEquals() { new EqualsTester() .addEqualityGroup(new HttpMediaType("foo/bar"), new HttpMediaType("foo/bar")) diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpRequestFactoryTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpRequestFactoryTest.java index 568eb201c..66d21826e 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpRequestFactoryTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpRequestFactoryTest.java @@ -14,13 +14,19 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; + import com.google.api.client.http.javanet.NetHttpTransport; import java.io.IOException; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Tests {@link HttpRequestFactory}. */ -public class HttpRequestFactoryTest extends TestCase { +@RunWith(JUnit4.class) +public class HttpRequestFactoryTest { + @Test public void testBuildRequest_urlShouldBeSet() throws IllegalArgumentException, IOException { HttpRequestFactory requestFactory = new NetHttpTransport() diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTest.java index e7075131d..085b9f563 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTest.java @@ -14,6 +14,13 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.api.client.testing.http.HttpTesting; import com.google.api.client.testing.http.MockHttpTransport; import com.google.api.client.testing.http.MockHttpUnsuccessfulResponseHandler; @@ -42,37 +49,38 @@ import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.regex.Pattern; -import junit.framework.TestCase; -import org.junit.Assert; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link HttpRequest}. * * @author Yaniv Inbar */ -public class HttpRequestTest extends TestCase { +@RunWith(JUnit4.class) +public class HttpRequestTest { private static final ImmutableSet BASIC_METHODS = ImmutableSet.of(HttpMethods.GET, HttpMethods.PUT, HttpMethods.POST, HttpMethods.DELETE); private static final ImmutableSet OTHER_METHODS = ImmutableSet.of(HttpMethods.HEAD, HttpMethods.PATCH); - public HttpRequestTest(String name) { - super(name); - } - - @Override + @Before public void setUp() { // suppress logging warnings to the console HttpTransport.LOGGER.setLevel(java.util.logging.Level.SEVERE); } - @Override + @After public void tearDown() { // back to the standard logging level for console HttpTransport.LOGGER.setLevel(java.util.logging.Level.WARNING); } + @Test public void testNotSupportedByDefault() throws Exception { MockHttpTransport transport = new MockHttpTransport(); HttpRequest request = @@ -203,6 +211,7 @@ public boolean handleResponse( }); } + @Test public void test301Redirect() throws Exception { // Set up RedirectTransport to redirect on the first request and then return success. RedirectTransport fakeTransport = new RedirectTransport(); @@ -210,11 +219,12 @@ public void test301Redirect() throws Exception { fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://gmail.com")); HttpResponse resp = request.execute(); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(2, fakeTransport.lowLevelExecCalls); + assertEquals(200, resp.getStatusCode()); + assertEquals(2, fakeTransport.lowLevelExecCalls); } @Deprecated + @Test public void test301RedirectWithUnsuccessfulResponseHandled() throws Exception { MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(true); MockBackOffPolicy backOffPolicy = new MockBackOffPolicy(); @@ -226,18 +236,19 @@ public void test301RedirectWithUnsuccessfulResponseHandled() throws Exception { request.setBackOffPolicy(backOffPolicy); HttpResponse resp = request.execute(); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(2, fakeTransport.lowLevelExecCalls); + assertEquals(200, resp.getStatusCode()); + assertEquals(2, fakeTransport.lowLevelExecCalls); // Assert that the redirect logic was not invoked because the response handler could handle the // request. The request url should be the original http://gmail.com - Assert.assertEquals("http://gmail.com", request.getUrl().toString()); + assertEquals("http://gmail.com", request.getUrl().toString()); // Assert that the backoff policy was not invoked because the response handler could handle the // request. - Assert.assertEquals(1, backOffPolicy.resetCalls); - Assert.assertEquals(0, backOffPolicy.backOffCalls); - Assert.assertTrue(handler.isCalled()); + assertEquals(1, backOffPolicy.resetCalls); + assertEquals(0, backOffPolicy.backOffCalls); + assertTrue(handler.isCalled()); } + @Test public void test301RedirectWithBackOffUnsuccessfulResponseHandled() throws Exception { MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(true); // Set up RedirectTransport to redirect on the first request and then return success. @@ -250,14 +261,14 @@ public void test301RedirectWithBackOffUnsuccessfulResponseHandled() throws Excep HttpResponse resp = request.execute(); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(2, fakeTransport.lowLevelExecCalls); + assertEquals(200, resp.getStatusCode()); + assertEquals(2, fakeTransport.lowLevelExecCalls); // Assert that the redirect logic was not invoked because the response handler could handle the // request. The request url should be the original http://gmail.com - Assert.assertEquals("http://gmail.com", request.getUrl().toString()); + assertEquals("http://gmail.com", request.getUrl().toString()); // Assert that the backoff was not invoked since the response handler could handle the request - Assert.assertEquals(0, backOff.getNumberOfTries()); - Assert.assertTrue(handler.isCalled()); + assertEquals(0, backOff.getNumberOfTries()); + assertTrue(handler.isCalled()); } @Deprecated @@ -273,17 +284,18 @@ public void test301RedirectWithUnsuccessfulResponseNotHandled() throws Exception request.setBackOffPolicy(backOffPolicy); HttpResponse resp = request.execute(); - Assert.assertEquals(200, resp.getStatusCode()); + assertEquals(200, resp.getStatusCode()); // Assert that the redirect logic was invoked because the response handler could not handle the // request. The request url should have changed from http://gmail.com to http://google.com - Assert.assertEquals(HttpTesting.SIMPLE_URL, request.getUrl().toString()); - Assert.assertEquals(2, fakeTransport.lowLevelExecCalls); + assertEquals(HttpTesting.SIMPLE_URL, request.getUrl().toString()); + assertEquals(2, fakeTransport.lowLevelExecCalls); // Assert that the backoff policy is never invoked (except to reset) because the response // handler returned false. - Assert.assertEquals(1, backOffPolicy.resetCalls); - Assert.assertEquals(0, backOffPolicy.backOffCalls); + assertEquals(1, backOffPolicy.resetCalls); + assertEquals(0, backOffPolicy.backOffCalls); } + @Test public void test301RedirectWithBackOffUnsuccessfulResponseNotHandled() throws Exception { // Create an Unsuccessful response handler that always returns false. MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false); @@ -297,15 +309,16 @@ public void test301RedirectWithBackOffUnsuccessfulResponseNotHandled() throws Ex HttpResponse resp = request.execute(); - Assert.assertEquals(200, resp.getStatusCode()); + assertEquals(200, resp.getStatusCode()); // Assert that the redirect logic was invoked because the response handler could not handle the // request. The request url should have changed from http://gmail.com to http://google.com - Assert.assertEquals(HttpTesting.SIMPLE_URL, request.getUrl().toString()); - Assert.assertEquals(2, fakeTransport.lowLevelExecCalls); + assertEquals(HttpTesting.SIMPLE_URL, request.getUrl().toString()); + assertEquals(2, fakeTransport.lowLevelExecCalls); // Assert that the backoff was not invoked since it's not required for 3xx errors - Assert.assertEquals(0, backOff.getNumberOfTries()); + assertEquals(0, backOff.getNumberOfTries()); } + @Test public void test303Redirect() throws Exception { // Set up RedirectTransport to redirect on the first request and then return success. RedirectTransport fakeTransport = new RedirectTransport(); @@ -320,14 +333,15 @@ public void test303Redirect() throws Exception { request.setRequestMethod(HttpMethods.POST); HttpResponse resp = request.execute(); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(2, fakeTransport.lowLevelExecCalls); + assertEquals(200, resp.getStatusCode()); + assertEquals(2, fakeTransport.lowLevelExecCalls); // Assert that the method in the request was changed to a GET due to the 303. - Assert.assertEquals(HttpMethods.GET, request.getRequestMethod()); + assertEquals(HttpMethods.GET, request.getRequestMethod()); // Assert that the content is null, since GET requests don't support non-zero content-length - Assert.assertNull(request.getContent()); + assertNull(request.getContent()); } + @Test public void testInfiniteRedirects() throws Exception { // Set up RedirectTransport to cause infinite redirections. RedirectTransport fakeTransport = new RedirectTransport(); @@ -342,9 +356,10 @@ public void testInfiniteRedirects() throws Exception { // Should be called 1 more than the number of retries allowed (because the first request is not // counted as a retry). - Assert.assertEquals(request.getNumberOfRetries() + 1, fakeTransport.lowLevelExecCalls); + assertEquals(request.getNumberOfRetries() + 1, fakeTransport.lowLevelExecCalls); } + @Test public void testMissingLocationRedirect() throws Exception { // Set up RedirectTransport to set responses with missing location headers. RedirectTransport fakeTransport = new RedirectTransport(); @@ -357,7 +372,7 @@ public void testMissingLocationRedirect() throws Exception { } catch (HttpResponseException e) { } - Assert.assertEquals(1, fakeTransport.lowLevelExecCalls); + assertEquals(1, fakeTransport.lowLevelExecCalls); } private static class FailThenSuccessBackoffTransport extends MockHttpTransport { @@ -454,6 +469,7 @@ public LowLevelHttpRequest buildRequest(String method, String url) { } } + @Test public void testHandleRedirect() throws Exception { StatusCodesTransport transport = new StatusCodesTransport(); HttpRequest req = @@ -508,6 +524,7 @@ private void subtestRedirect(int statusCode, boolean setLocation) throws Excepti } } + @Test public void testHandleRedirect_relativeLocation() throws IOException { subtestHandleRedirect_relativeLocation("http://some.org/a/b", "z", "http://some.org/a/z"); subtestHandleRedirect_relativeLocation("http://some.org/a/b", "z/", "http://some.org/a/z/"); @@ -527,6 +544,7 @@ public void subtestHandleRedirect_relativeLocation( } @Deprecated + @Test public void testExecuteErrorWithRetryEnabled() throws Exception { int callsBeforeSuccess = 3; FailThenSuccessConnectionErrorTransport fakeTransport = @@ -537,10 +555,11 @@ public void testExecuteErrorWithRetryEnabled() throws Exception { req.setNumberOfRetries(callsBeforeSuccess + 1); HttpResponse resp = req.execute(); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(4, fakeTransport.lowLevelExecCalls); + assertEquals(200, resp.getStatusCode()); + assertEquals(4, fakeTransport.lowLevelExecCalls); } + @Test public void testExecuteErrorWithIOExceptionHandler() throws Exception { int callsBeforeSuccess = 3; FailThenSuccessConnectionErrorTransport fakeTransport = @@ -551,11 +570,12 @@ public void testExecuteErrorWithIOExceptionHandler() throws Exception { req.setNumberOfRetries(callsBeforeSuccess + 1); HttpResponse resp = req.execute(); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(4, fakeTransport.lowLevelExecCalls); + assertEquals(200, resp.getStatusCode()); + assertEquals(4, fakeTransport.lowLevelExecCalls); } @Deprecated + @Test public void testExecuteErrorWithRetryEnabledBeyondRetryLimit() throws Exception { int callsBeforeSuccess = 11; FailThenSuccessConnectionErrorTransport fakeTransport = @@ -570,9 +590,10 @@ public void testExecuteErrorWithRetryEnabledBeyondRetryLimit() throws Exception } catch (IOException e) { // Expected } - Assert.assertEquals(callsBeforeSuccess, fakeTransport.lowLevelExecCalls); + assertEquals(callsBeforeSuccess, fakeTransport.lowLevelExecCalls); } + @Test public void testExecuteErrorWithIOExceptionHandlerBeyondRetryLimit() throws Exception { int callsBeforeSuccess = 11; FailThenSuccessConnectionErrorTransport fakeTransport = @@ -587,9 +608,10 @@ public void testExecuteErrorWithIOExceptionHandlerBeyondRetryLimit() throws Exce } catch (IOException e) { // Expected } - Assert.assertEquals(callsBeforeSuccess, fakeTransport.lowLevelExecCalls); + assertEquals(callsBeforeSuccess, fakeTransport.lowLevelExecCalls); } + @Test public void testExecuteErrorWithoutIOExceptionHandler() throws Exception { int callsBeforeSuccess = 3; FailThenSuccessConnectionErrorTransport fakeTransport = @@ -604,10 +626,11 @@ public void testExecuteErrorWithoutIOExceptionHandler() throws Exception { } catch (IOException e) { // Expected } - Assert.assertEquals(1, fakeTransport.lowLevelExecCalls); + assertEquals(1, fakeTransport.lowLevelExecCalls); } @Deprecated + @Test public void testUserAgentWithExecuteErrorAndRetryEnabled() throws Exception { int callsBeforeSuccess = 3; FailThenSuccessConnectionErrorTransport fakeTransport = @@ -618,12 +641,13 @@ public void testUserAgentWithExecuteErrorAndRetryEnabled() throws Exception { req.setNumberOfRetries(callsBeforeSuccess + 1); HttpResponse resp = req.execute(); - Assert.assertEquals(1, fakeTransport.userAgentHeader.size()); - Assert.assertEquals(HttpRequest.USER_AGENT_SUFFIX, fakeTransport.userAgentHeader.get(0)); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(4, fakeTransport.lowLevelExecCalls); + assertEquals(1, fakeTransport.userAgentHeader.size()); + assertEquals(HttpRequest.USER_AGENT_SUFFIX, fakeTransport.userAgentHeader.get(0)); + assertEquals(200, resp.getStatusCode()); + assertEquals(4, fakeTransport.lowLevelExecCalls); } + @Test public void testUserAgentWithExecuteErrorAndIOExceptionHandler() throws Exception { int callsBeforeSuccess = 3; FailThenSuccessConnectionErrorTransport fakeTransport = @@ -634,12 +658,13 @@ public void testUserAgentWithExecuteErrorAndIOExceptionHandler() throws Exceptio req.setNumberOfRetries(callsBeforeSuccess + 1); HttpResponse resp = req.execute(); - Assert.assertEquals(1, fakeTransport.userAgentHeader.size()); - Assert.assertEquals(HttpRequest.USER_AGENT_SUFFIX, fakeTransport.userAgentHeader.get(0)); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(4, fakeTransport.lowLevelExecCalls); + assertEquals(1, fakeTransport.userAgentHeader.size()); + assertEquals(HttpRequest.USER_AGENT_SUFFIX, fakeTransport.userAgentHeader.get(0)); + assertEquals(200, resp.getStatusCode()); + assertEquals(4, fakeTransport.lowLevelExecCalls); } + @Test public void testAbnormalResponseHandlerWithNoBackOff() throws Exception { FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, 1); @@ -650,12 +675,13 @@ public void testAbnormalResponseHandlerWithNoBackOff() throws Exception { req.setUnsuccessfulResponseHandler(handler); HttpResponse resp = req.execute(); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(2, fakeTransport.lowLevelExecCalls); - Assert.assertTrue(handler.isCalled()); + assertEquals(200, resp.getStatusCode()); + assertEquals(2, fakeTransport.lowLevelExecCalls); + assertTrue(handler.isCalled()); } @Deprecated + @Test public void testAbnormalResponseHandlerWithBackOff() throws Exception { FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1); @@ -668,13 +694,14 @@ public void testAbnormalResponseHandlerWithBackOff() throws Exception { req.setBackOffPolicy(backOffPolicy); HttpResponse resp = req.execute(); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(2, fakeTransport.lowLevelExecCalls); - Assert.assertEquals(1, backOffPolicy.resetCalls); - Assert.assertEquals(0, backOffPolicy.backOffCalls); - Assert.assertTrue(handler.isCalled()); + assertEquals(200, resp.getStatusCode()); + assertEquals(2, fakeTransport.lowLevelExecCalls); + assertEquals(1, backOffPolicy.resetCalls); + assertEquals(0, backOffPolicy.backOffCalls); + assertTrue(handler.isCalled()); } + @Test public void testAbnormalResponseHandlerWithBackOffUnsuccessfulResponseHandler() throws Exception { FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1); @@ -686,13 +713,14 @@ public void testAbnormalResponseHandlerWithBackOffUnsuccessfulResponseHandler() setBackOffUnsuccessfulResponseHandler(req, backOff, handler); HttpResponse resp = req.execute(); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(2, fakeTransport.lowLevelExecCalls); - Assert.assertEquals(0, backOff.getNumberOfTries()); - Assert.assertTrue(handler.isCalled()); + assertEquals(200, resp.getStatusCode()); + assertEquals(2, fakeTransport.lowLevelExecCalls); + assertEquals(0, backOff.getNumberOfTries()); + assertTrue(handler.isCalled()); } @Deprecated + @Test public void testBackOffSingleCall() throws Exception { FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1); @@ -705,13 +733,14 @@ public void testBackOffSingleCall() throws Exception { req.setBackOffPolicy(backOffPolicy); HttpResponse resp = req.execute(); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(2, fakeTransport.lowLevelExecCalls); - Assert.assertEquals(1, backOffPolicy.resetCalls); - Assert.assertEquals(1, backOffPolicy.backOffCalls); - Assert.assertTrue(handler.isCalled()); + assertEquals(200, resp.getStatusCode()); + assertEquals(2, fakeTransport.lowLevelExecCalls); + assertEquals(1, backOffPolicy.resetCalls); + assertEquals(1, backOffPolicy.backOffCalls); + assertTrue(handler.isCalled()); } + @Test public void testBackOffUnsuccessfulResponseSingleCall() throws Exception { FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1); @@ -723,13 +752,14 @@ public void testBackOffUnsuccessfulResponseSingleCall() throws Exception { setBackOffUnsuccessfulResponseHandler(req, backOff, handler); HttpResponse resp = req.execute(); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(2, fakeTransport.lowLevelExecCalls); - Assert.assertEquals(1, backOff.getNumberOfTries()); - Assert.assertTrue(handler.isCalled()); + assertEquals(200, resp.getStatusCode()); + assertEquals(2, fakeTransport.lowLevelExecCalls); + assertEquals(1, backOff.getNumberOfTries()); + assertTrue(handler.isCalled()); } @Deprecated + @Test public void testBackOffMultipleCalls() throws Exception { int callsBeforeSuccess = 5; FailThenSuccessBackoffTransport fakeTransport = @@ -744,13 +774,14 @@ public void testBackOffMultipleCalls() throws Exception { req.setBackOffPolicy(backOffPolicy); HttpResponse resp = req.execute(); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(callsBeforeSuccess + 1, fakeTransport.lowLevelExecCalls); - Assert.assertEquals(1, backOffPolicy.resetCalls); - Assert.assertEquals(callsBeforeSuccess, backOffPolicy.backOffCalls); - Assert.assertTrue(handler.isCalled()); + assertEquals(200, resp.getStatusCode()); + assertEquals(callsBeforeSuccess + 1, fakeTransport.lowLevelExecCalls); + assertEquals(1, backOffPolicy.resetCalls); + assertEquals(callsBeforeSuccess, backOffPolicy.backOffCalls); + assertTrue(handler.isCalled()); } + @Test public void testBackOffUnsucessfulReponseMultipleCalls() throws Exception { int callsBeforeSuccess = 5; FailThenSuccessBackoffTransport fakeTransport = @@ -764,13 +795,14 @@ public void testBackOffUnsucessfulReponseMultipleCalls() throws Exception { setBackOffUnsuccessfulResponseHandler(req, backOff, handler); HttpResponse resp = req.execute(); - Assert.assertEquals(200, resp.getStatusCode()); - Assert.assertEquals(callsBeforeSuccess + 1, fakeTransport.lowLevelExecCalls); - Assert.assertEquals(callsBeforeSuccess, backOff.getNumberOfTries()); - Assert.assertTrue(handler.isCalled()); + assertEquals(200, resp.getStatusCode()); + assertEquals(callsBeforeSuccess + 1, fakeTransport.lowLevelExecCalls); + assertEquals(callsBeforeSuccess, backOff.getNumberOfTries()); + assertTrue(handler.isCalled()); } @Deprecated + @Test public void testBackOffCallsBeyondRetryLimit() throws Exception { int callsBeforeSuccess = 11; FailThenSuccessBackoffTransport fakeTransport = @@ -789,12 +821,13 @@ public void testBackOffCallsBeyondRetryLimit() throws Exception { fail("expected HttpResponseException"); } catch (HttpResponseException e) { } - Assert.assertEquals(callsBeforeSuccess, fakeTransport.lowLevelExecCalls); - Assert.assertEquals(1, backOffPolicy.resetCalls); - Assert.assertEquals(callsBeforeSuccess - 1, backOffPolicy.backOffCalls); - Assert.assertTrue(handler.isCalled()); + assertEquals(callsBeforeSuccess, fakeTransport.lowLevelExecCalls); + assertEquals(1, backOffPolicy.resetCalls); + assertEquals(callsBeforeSuccess - 1, backOffPolicy.backOffCalls); + assertTrue(handler.isCalled()); } + @Test public void testBackOffUnsuccessfulReponseCallsBeyondRetryLimit() throws Exception { int callsBeforeSuccess = 11; FailThenSuccessBackoffTransport fakeTransport = @@ -812,12 +845,13 @@ public void testBackOffUnsuccessfulReponseCallsBeyondRetryLimit() throws Excepti fail("expected HttpResponseException"); } catch (HttpResponseException e) { } - Assert.assertEquals(callsBeforeSuccess, fakeTransport.lowLevelExecCalls); - Assert.assertEquals(callsBeforeSuccess - 1, backOff.getMaxTries()); - Assert.assertTrue(handler.isCalled()); + assertEquals(callsBeforeSuccess, fakeTransport.lowLevelExecCalls); + assertEquals(callsBeforeSuccess - 1, backOff.getMaxTries()); + assertTrue(handler.isCalled()); } @Deprecated + @Test public void testBackOffUnRecognizedStatusCode() throws Exception { FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, 1); @@ -833,13 +867,14 @@ public void testBackOffUnRecognizedStatusCode() throws Exception { } catch (HttpResponseException e) { } - Assert.assertEquals(1, fakeTransport.lowLevelExecCalls); - Assert.assertEquals(1, backOffPolicy.resetCalls); + assertEquals(1, fakeTransport.lowLevelExecCalls); + assertEquals(1, backOffPolicy.resetCalls); // The BackOffPolicy should not be called since it does not support 401 status codes. - Assert.assertEquals(0, backOffPolicy.backOffCalls); - Assert.assertTrue(handler.isCalled()); + assertEquals(0, backOffPolicy.backOffCalls); + assertTrue(handler.isCalled()); } + @Test public void testBackOffUnsuccessfulReponseUnRecognizedStatusCode() throws Exception { FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, 1); @@ -854,13 +889,14 @@ public void testBackOffUnsuccessfulReponseUnRecognizedStatusCode() throws Except } catch (HttpResponseException e) { } - Assert.assertEquals(1, fakeTransport.lowLevelExecCalls); + assertEquals(1, fakeTransport.lowLevelExecCalls); // The back-off should not be called since it does not support 401 status codes. - Assert.assertEquals(0, backOff.getNumberOfTries()); - Assert.assertTrue(handler.isCalled()); + assertEquals(0, backOff.getNumberOfTries()); + assertTrue(handler.isCalled()); } @Deprecated + @Test public void testBackOffStop() throws Exception { int callsBeforeSuccess = 5; FailThenSuccessBackoffTransport fakeTransport = @@ -879,14 +915,15 @@ public void testBackOffStop() throws Exception { } catch (HttpResponseException e) { } - Assert.assertEquals(1, fakeTransport.lowLevelExecCalls); - Assert.assertEquals(1, backOffPolicy.resetCalls); + assertEquals(1, fakeTransport.lowLevelExecCalls); + assertEquals(1, backOffPolicy.resetCalls); // The BackOffPolicy should be called only once and then it should return BackOffPolicy.STOP // should stop all back off retries. - Assert.assertEquals(1, backOffPolicy.backOffCalls); - Assert.assertTrue(handler.isCalled()); + assertEquals(1, backOffPolicy.backOffCalls); + assertTrue(handler.isCalled()); } + @Test public void testBackOffUnsucessfulResponseStop() throws Exception { int callsBeforeSuccess = 5; FailThenSuccessBackoffTransport fakeTransport = @@ -903,10 +940,10 @@ public void testBackOffUnsucessfulResponseStop() throws Exception { } catch (HttpResponseException e) { } - Assert.assertEquals(2, fakeTransport.lowLevelExecCalls); + assertEquals(2, fakeTransport.lowLevelExecCalls); // The back-off should be called only once, since the its max tries is set to 1 - Assert.assertEquals(1, backOff.getNumberOfTries()); - Assert.assertTrue(handler.isCalled()); + assertEquals(1, backOff.getNumberOfTries()); + assertTrue(handler.isCalled()); } public enum E { @@ -933,6 +970,7 @@ public static class MyHeaders extends HttpHeaders { @Key E otherValue; } + @Test public void testExecute_headerSerialization() throws Exception { // custom headers MyHeaders myHeaders = new MyHeaders(); @@ -973,6 +1011,7 @@ public LowLevelHttpRequest buildRequest(String method, String url) throws IOExce assertEquals(ImmutableList.of("other"), lowLevelRequest.getHeaderValues("othervalue")); } + @Test public void testGZipEncoding() throws Exception { class MyTransport extends MockHttpTransport { @@ -1022,6 +1061,7 @@ public LowLevelHttpResponse execute() throws IOException { request.execute(); } + @Test public void testContentLoggingLimitWithLoggingEnabledAndDisabled() throws Exception { class MyTransport extends MockHttpTransport { @@ -1088,17 +1128,20 @@ public LowLevelHttpResponse execute() throws IOException { } } + @Test public void testVersion() { assertNotNull("version constant should not be null", HttpRequest.VERSION); Pattern semverPattern = Pattern.compile("\\d+\\.\\d+\\.\\d+(-sp\\.\\d+)?(-SNAPSHOT)?"); assertTrue(semverPattern.matcher(HttpRequest.VERSION).matches()); } + @Test public void testUserAgent() { assertTrue(HttpRequest.USER_AGENT_SUFFIX.contains("Google-HTTP-Java-Client")); assertTrue(HttpRequest.USER_AGENT_SUFFIX.contains("gzip")); } + @Test public void testExecute_headers() throws Exception { HttpTransport transport = new MockHttpTransport(); HttpRequest request = @@ -1108,6 +1151,7 @@ public void testExecute_headers() throws Exception { request.execute(); } + @Test public void testSuppressUserAgentSuffix() throws Exception { class MyTransport extends MockHttpTransport { String expectedUserAgent; @@ -1150,6 +1194,7 @@ public LowLevelHttpResponse execute() throws IOException { request.execute(); } + @Test public void testExecuteAsync() throws IOException, InterruptedException, ExecutionException, TimeoutException { MockExecutor mockExecutor = new MockExecutor(); @@ -1164,6 +1209,7 @@ public void testExecuteAsync() assertNotNull(futureResponse.get(10, TimeUnit.MILLISECONDS)); } + @Test public void testExecute_redirects() throws Exception { class MyTransport extends MockHttpTransport { int count = 1; @@ -1194,6 +1240,7 @@ public LowLevelHttpRequest buildRequest(String method, String url) throws IOExce } } + @Test public void testExecute_redirectWithIncorrectContentRetryableSetting() throws Exception { // TODO(yanivi): any way we can warn user about this? RedirectTransport fakeTransport = new RedirectTransport(); @@ -1214,6 +1261,7 @@ public void testExecute_redirectWithIncorrectContentRetryableSetting() throws Ex assertEquals(2, fakeTransport.lowLevelExecCalls); } + @Test public void testExecute_curlLogger() throws Exception { LogRecordingHandler recorder = new LogRecordingHandler(); HttpTransport.LOGGER.setLevel(Level.CONFIG); @@ -1236,6 +1284,7 @@ public void testExecute_curlLogger() throws Exception { assertTrue(found); } + @Test public void testExecute_curlLoggerWithContentEncoding() throws Exception { LogRecordingHandler recorder = new LogRecordingHandler(); HttpTransport.LOGGER.setLevel(Level.CONFIG); @@ -1269,6 +1318,7 @@ public void testExecute_curlLoggerWithContentEncoding() throws Exception { assertTrue(found); } + @Test public void testVersion_matchesAcceptablePatterns() throws Exception { String acceptableVersionPattern = "unknown-version|(?:\\d+\\.\\d+\\.\\d+(?:-.*?)?(?:-SNAPSHOT)?)"; diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTracingTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTracingTest.java index 6fc9cb37d..528f5f309 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTracingTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpRequestTracingTest.java @@ -36,7 +36,10 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +@RunWith(JUnit4.class) public class HttpRequestTracingTest { private static final TestHandler testHandler = new TestHandler(); diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpResponseExceptionTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpResponseExceptionTest.java index cbe6e6a0d..3c4c2aa94 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpResponseExceptionTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpResponseExceptionTest.java @@ -17,7 +17,10 @@ import static com.google.api.client.testing.http.HttpTesting.SIMPLE_GENERIC_URL; import static com.google.api.client.util.StringUtils.LINE_SEPARATOR; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import com.google.api.client.http.HttpResponseException.Builder; import com.google.api.client.testing.http.MockHttpTransport; @@ -30,17 +33,20 @@ import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; -import junit.framework.TestCase; -import org.junit.Assert; +import org.junit.Test; import org.junit.function.ThrowingRunnable; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link HttpResponseException}. * * @author Yaniv Inbar */ -public class HttpResponseExceptionTest extends TestCase { +@RunWith(JUnit4.class) +public class HttpResponseExceptionTest { + @Test public void testConstructor() throws Exception { HttpTransport transport = new MockHttpTransport(); HttpRequest request = transport.createRequestFactory().buildGetRequest(SIMPLE_GENERIC_URL); @@ -54,6 +60,7 @@ public void testConstructor() throws Exception { assertTrue(headers == responseException.getHeaders()); } + @Test public void testBuilder() throws Exception { HttpHeaders headers = new HttpHeaders(); Builder builder = @@ -73,6 +80,7 @@ public void testBuilder() throws Exception { assertTrue(headers == e.getHeaders()); } + @Test public void testConstructorWithStatusMessage() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -94,6 +102,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals("OK", responseException.getStatusMessage()); } + @Test public void testConstructor_noStatusCode() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -123,6 +132,7 @@ public void run() throws Throwable { assertThat(responseException).hasMessageThat().isEqualTo("GET " + SIMPLE_GENERIC_URL); } + @Test public void testConstructor_messageButNoStatusCode() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -153,6 +163,7 @@ public void run() throws Throwable { assertThat(responseException).hasMessageThat().isEqualTo("Foo\nGET " + SIMPLE_GENERIC_URL); } + @Test public void testComputeMessage() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -174,6 +185,7 @@ public LowLevelHttpResponse execute() throws IOException { .isEqualTo("200 Foo\nGET " + SIMPLE_GENERIC_URL); } + @Test public void testThrown() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -214,6 +226,7 @@ public void run() throws Throwable { assertEquals(1, responseException.getAttemptCount()); } + @Test public void testInvalidCharset() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -249,6 +262,7 @@ public void run() throws Throwable { .isEqualTo("404 Not Found\nGET " + SIMPLE_GENERIC_URL); } + @Test public void testAttemptCountWithBackOff() throws Exception { HttpTransport fakeTransport = new MockHttpTransport() { @@ -288,11 +302,12 @@ public void run() throws Throwable { } }); - Assert.assertEquals(500, responseException.getStatusCode()); + assertEquals(500, responseException.getStatusCode()); // original request and 1 retry - total 2 assertEquals(2, responseException.getAttemptCount()); } + @Test public void testUnsupportedCharset() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -327,6 +342,7 @@ public void run() throws Throwable { .isEqualTo("404 Not Found\nGET " + SIMPLE_GENERIC_URL); } + @Test public void testSerialization() throws Exception { HttpTransport transport = new MockHttpTransport(); HttpRequest request = transport.createRequestFactory().buildGetRequest(SIMPLE_GENERIC_URL); diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpResponseTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpResponseTest.java index ef7599197..9017b39a5 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpResponseTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpResponseTest.java @@ -14,6 +14,13 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.api.client.json.Json; import com.google.api.client.testing.http.HttpTesting; import com.google.api.client.testing.http.MockHttpTransport; @@ -37,21 +44,19 @@ import java.util.logging.Level; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link HttpResponse}. * * @author Yaniv Inbar */ -public class HttpResponseTest extends TestCase { - - public HttpResponseTest() {} - - public HttpResponseTest(String name) { - super(name); - } +@RunWith(JUnit4.class) +public class HttpResponseTest { + @Test public void testParseAsString_none() throws Exception { HttpTransport transport = new MockHttpTransport(); HttpRequest request = @@ -72,6 +77,7 @@ public void testParseAsString_none() throws Exception { private static final String INVALID_CONTENT_TYPE = "!!!invalid!!!"; private static final String JSON_CONTENT_TYPE = "application/json"; + @Test public void testParseAsString_utf8() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -95,6 +101,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals("UTF-8", response.getContentCharset().name()); } + @Test public void testParseAsString_noContentType() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -117,6 +124,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals("ISO-8859-1", response.getContentCharset().name()); } + @Test public void testParseAsString_validContentType() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -143,6 +151,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals("ISO-8859-1", response.getContentCharset().name()); } + @Test public void testParseAsString_validContentTypeWithParams() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -169,6 +178,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals("UTF-8", response.getContentCharset().name()); } + @Test public void testParseAsString_invalidContentType() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -195,6 +205,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals("ISO-8859-1", response.getContentCharset().name()); } + @Test public void testParseAsString_validContentTypeWithoutCharSetWithParams() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -221,6 +232,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals("UTF-8", response.getContentCharset().name()); } + @Test public void testParseAsString_jsonContentType() throws IOException { HttpTransport transport = new MockHttpTransport() { @@ -246,10 +258,12 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals("UTF-8", response.getContentCharset().name()); } + @Test public void testStatusCode_negative_dontThrowException() throws Exception { subtestStatusCode_negative(false); } + @Test public void testStatusCode_negative_throwException() throws Exception { subtestStatusCode_negative(true); } @@ -289,6 +303,7 @@ public static class MyHeaders extends HttpHeaders { static final String ETAG_VALUE = "\"abc\""; + @Test public void testHeaderParsing() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -325,6 +340,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals(ETAG_VALUE, response.getHeaders().getETag()); } + @Test public void testParseAs_noParser() throws Exception { try { new MockHttpTransport() @@ -338,6 +354,7 @@ public void testParseAs_noParser() throws Exception { } } + @Test public void testParseAs_classNoContent() throws Exception { final MockLowLevelHttpResponse result = new MockLowLevelHttpResponse(); @@ -375,6 +392,7 @@ public LowLevelHttpResponse execute() throws IOException { } } + @Test public void testParseAs_typeNoContent() throws Exception { final MockLowLevelHttpResponse result = new MockLowLevelHttpResponse(); @@ -412,6 +430,7 @@ public LowLevelHttpResponse execute() throws IOException { } } + @Test public void testDownload() throws Exception { HttpTransport transport = new MockHttpTransport() { @@ -436,6 +455,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals(SAMPLE, outputStream.toString("UTF-8")); } + @Test public void testDisconnectWithContent() throws Exception { final MockLowLevelHttpResponse lowLevelHttpResponse = new MockLowLevelHttpResponse(); @@ -466,6 +486,7 @@ public LowLevelHttpResponse execute() throws IOException { assertTrue(content.isClosed()); } + @Test public void testDisconnectWithNoContent() throws Exception { final MockLowLevelHttpResponse lowLevelHttpResponse = new MockLowLevelHttpResponse(); @@ -490,6 +511,7 @@ public LowLevelHttpResponse execute() throws IOException { assertTrue(lowLevelHttpResponse.isDisconnected()); } + @Test public void testContentLoggingLimitWithLoggingEnabledAndDisabled() throws Exception { subtestContentLoggingLimit("", 2, false); subtestContentLoggingLimit("A", 2, false); @@ -556,6 +578,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals(Arrays.asList(expectedMessages), recorder.messages()); } + @Test public void testGetContent_gzipNoContent() throws IOException { HttpTransport transport = new MockHttpTransport() { @@ -580,6 +603,7 @@ public LowLevelHttpResponse execute() throws IOException { assertNull(noContent); } + @Test public void testGetContent_gzipEncoding_ReturnRawStream() throws IOException { HttpTransport transport = new MockHttpTransport() { @@ -609,15 +633,18 @@ public LowLevelHttpResponse execute() throws IOException { request.execute().getContent() instanceof BufferedInputStream); } + @Test public void testGetContent_gzipEncoding_finishReading() throws IOException { do_testGetContent_gzipEncoding_finishReading("gzip"); } + @Test public void testGetContent_gzipEncoding_finishReadingWithUppercaseContentEncoding() throws IOException { do_testGetContent_gzipEncoding_finishReading("GZIP"); } + @Test public void testGetContent_gzipEncoding_finishReadingWithDifferentDefaultLocaleAndUppercaseContentEncoding() throws IOException { @@ -677,6 +704,7 @@ public LowLevelHttpResponse execute() throws IOException { } } + @Test public void testGetContent_otherEncodingWithgzipInItsName_GzipIsNotUsed() throws IOException { final MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse(); mockResponse.setContent("abcd"); @@ -703,6 +731,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals("abcd", response.parseAsString()); } + @Test public void testGetContent_bufferedContent() throws IOException { HttpTransport transport = new MockHttpTransport() { diff --git a/google-http-client/src/test/java/com/google/api/client/http/HttpStatusCodesTest.java b/google-http-client/src/test/java/com/google/api/client/http/HttpStatusCodesTest.java index 58b43f024..16a7c4bef 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/HttpStatusCodesTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/HttpStatusCodesTest.java @@ -14,11 +14,18 @@ package com.google.api.client.http; -import junit.framework.TestCase; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Tests {@link HttpStatusCodes}. */ -public class HttpStatusCodesTest extends TestCase { +@RunWith(JUnit4.class) +public class HttpStatusCodesTest { + @Test public void testIsRedirect_3xx() { assertTrue(HttpStatusCodes.isRedirect(301)); assertTrue(HttpStatusCodes.isRedirect(302)); @@ -27,6 +34,7 @@ public void testIsRedirect_3xx() { assertTrue(HttpStatusCodes.isRedirect(308)); } + @Test public void testIsRedirect_non3xx() { assertFalse(HttpStatusCodes.isRedirect(200)); assertFalse(HttpStatusCodes.isRedirect(401)); diff --git a/google-http-client/src/test/java/com/google/api/client/http/MultipartContentTest.java b/google-http-client/src/test/java/com/google/api/client/http/MultipartContentTest.java index 8b286a983..198534f6f 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/MultipartContentTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/MultipartContentTest.java @@ -14,18 +14,25 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import com.google.api.client.json.Json; import com.google.api.client.util.StringUtils; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link MultipartContent}. * * @author Yaniv Inbar */ -public class MultipartContentTest extends TestCase { +@RunWith(JUnit4.class) +public class MultipartContentTest { private static final String BOUNDARY = "__END_OF_PART__"; private static final String CRLF = "\r\n"; @@ -43,6 +50,7 @@ private static String headers(String contentType, String value) { + CRLF; } + @Test public void testRandomContent() throws Exception { MultipartContent content = new MultipartContent(); String boundaryString = content.getBoundary(); @@ -81,6 +89,7 @@ public void testRandomContent() throws Exception { assertEquals(StringUtils.getBytesUtf8(expectedContent).length, content.getLength()); } + @Test public void testContent() throws Exception { subtestContent("--" + BOUNDARY + "--" + CRLF, null); subtestContent( diff --git a/google-http-client/src/test/java/com/google/api/client/http/OpenCensusUtilsTest.java b/google-http-client/src/test/java/com/google/api/client/http/OpenCensusUtilsTest.java index 480d10150..f29d6b986 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/OpenCensusUtilsTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/OpenCensusUtilsTest.java @@ -14,6 +14,10 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + import io.opencensus.trace.Annotation; import io.opencensus.trace.AttributeValue; import io.opencensus.trace.BlankSpan; @@ -27,14 +31,19 @@ import io.opencensus.trace.propagation.TextFormat; import java.util.List; import java.util.Map; -import junit.framework.TestCase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link OpenCensusUtils}. * * @author Hailong Wen */ -public class OpenCensusUtilsTest extends TestCase { +@RunWith(JUnit4.class) +public class OpenCensusUtilsTest { TextFormat mockTextFormat; TextFormat.Setter mockTextFormatSetter; @@ -44,11 +53,7 @@ public class OpenCensusUtilsTest extends TestCase { HttpHeaders headers; Tracer tracer; - public OpenCensusUtilsTest(String testName) { - super(testName); - } - - @Override + @Before public void setUp() { mockTextFormat = new TextFormat() { @@ -100,28 +105,32 @@ public void end(EndSpanOptions options) {} originTextFormatSetter = OpenCensusUtils.propagationTextFormatSetter; } - @Override + @After public void tearDown() { OpenCensusUtils.setPropagationTextFormat(originTextFormat); OpenCensusUtils.setPropagationTextFormatSetter(originTextFormatSetter); } - public void testInitializatoin() { + @Test + public void testInitialization() { assertNotNull(OpenCensusUtils.getTracer()); assertNotNull(OpenCensusUtils.propagationTextFormat); assertNotNull(OpenCensusUtils.propagationTextFormatSetter); } + @Test public void testSetPropagationTextFormat() { OpenCensusUtils.setPropagationTextFormat(mockTextFormat); assertEquals(mockTextFormat, OpenCensusUtils.propagationTextFormat); } + @Test public void testSetPropagationTextFormatSetter() { OpenCensusUtils.setPropagationTextFormatSetter(mockTextFormatSetter); assertEquals(mockTextFormatSetter, OpenCensusUtils.propagationTextFormatSetter); } + @Test public void testPropagateTracingContextInjection() { OpenCensusUtils.setPropagationTextFormat(mockTextFormat); try { @@ -132,6 +141,7 @@ public void testPropagateTracingContextInjection() { } } + @Test public void testPropagateTracingContextHeader() { OpenCensusUtils.setPropagationTextFormatSetter(mockTextFormatSetter); try { @@ -142,6 +152,7 @@ public void testPropagateTracingContextHeader() { } } + @Test public void testPropagateTracingContextNullSpan() { OpenCensusUtils.setPropagationTextFormat(mockTextFormat); try { @@ -152,6 +163,7 @@ public void testPropagateTracingContextNullSpan() { } } + @Test public void testPropagateTracingContextNullHeaders() { OpenCensusUtils.setPropagationTextFormat(mockTextFormat); try { @@ -162,17 +174,20 @@ public void testPropagateTracingContextNullHeaders() { } } + @Test public void testPropagateTracingContextInvalidSpan() { OpenCensusUtils.setPropagationTextFormat(mockTextFormat); // No injection. No exceptions should be thrown. OpenCensusUtils.propagateTracingContext(BlankSpan.INSTANCE, headers); } + @Test public void testGetEndSpanOptionsNoResponse() { EndSpanOptions expected = EndSpanOptions.builder().setStatus(Status.UNKNOWN).build(); assertEquals(expected, OpenCensusUtils.getEndSpanOptions(null)); } + @Test public void testGetEndSpanOptionsSuccess() { EndSpanOptions expected = EndSpanOptions.builder().setStatus(Status.OK).build(); assertEquals(expected, OpenCensusUtils.getEndSpanOptions(200)); @@ -180,37 +195,44 @@ public void testGetEndSpanOptionsSuccess() { assertEquals(expected, OpenCensusUtils.getEndSpanOptions(202)); } + @Test public void testGetEndSpanOptionsBadRequest() { EndSpanOptions expected = EndSpanOptions.builder().setStatus(Status.INVALID_ARGUMENT).build(); assertEquals(expected, OpenCensusUtils.getEndSpanOptions(400)); } + @Test public void testGetEndSpanOptionsUnauthorized() { EndSpanOptions expected = EndSpanOptions.builder().setStatus(Status.UNAUTHENTICATED).build(); assertEquals(expected, OpenCensusUtils.getEndSpanOptions(401)); } + @Test public void testGetEndSpanOptionsForbidden() { EndSpanOptions expected = EndSpanOptions.builder().setStatus(Status.PERMISSION_DENIED).build(); assertEquals(expected, OpenCensusUtils.getEndSpanOptions(403)); } + @Test public void testGetEndSpanOptionsNotFound() { EndSpanOptions expected = EndSpanOptions.builder().setStatus(Status.NOT_FOUND).build(); assertEquals(expected, OpenCensusUtils.getEndSpanOptions(404)); } + @Test public void testGetEndSpanOptionsPreconditionFailed() { EndSpanOptions expected = EndSpanOptions.builder().setStatus(Status.FAILED_PRECONDITION).build(); assertEquals(expected, OpenCensusUtils.getEndSpanOptions(412)); } + @Test public void testGetEndSpanOptionsServerError() { EndSpanOptions expected = EndSpanOptions.builder().setStatus(Status.UNAVAILABLE).build(); assertEquals(expected, OpenCensusUtils.getEndSpanOptions(500)); } + @Test public void testGetEndSpanOptionsOther() { EndSpanOptions expected = EndSpanOptions.builder().setStatus(Status.UNKNOWN).build(); // test some random unsupported statuses @@ -219,6 +241,7 @@ public void testGetEndSpanOptionsOther() { assertEquals(expected, OpenCensusUtils.getEndSpanOptions(501)); } + @Test public void testRecordMessageEventInNullSpan() { try { OpenCensusUtils.recordMessageEvent(null, 0, MessageEvent.Type.SENT); @@ -228,6 +251,7 @@ public void testRecordMessageEventInNullSpan() { } } + @Test public void testRecordMessageEvent() { try { OpenCensusUtils.recordMessageEvent(mockSpan, 0, MessageEvent.Type.SENT); diff --git a/google-http-client/src/test/java/com/google/api/client/http/UriTemplateTest.java b/google-http-client/src/test/java/com/google/api/client/http/UriTemplateTest.java index 14ebc61b6..73492d3c4 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/UriTemplateTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/UriTemplateTest.java @@ -14,6 +14,9 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.google.api.client.util.Value; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -21,14 +24,17 @@ import java.util.List; import java.util.Map; import java.util.SortedMap; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link UriTemplate}. * * @author Ravi Mistry */ -public class UriTemplateTest extends TestCase { +@RunWith(JUnit4.class) +public class UriTemplateTest { public void testExpandTemplates_initialization() { SortedMap map = Maps.newTreeMap(); @@ -39,6 +45,7 @@ public void testExpandTemplates_initialization() { assertEquals("/a/b/c", UriTemplate.expand("{/id*}", map, false)); } + @Test public void testExpandTemplates_basic() { SortedMap requestMap = Maps.newTreeMap(); requestMap.put("abc", "xyz"); @@ -58,6 +65,7 @@ public void testExpandTemplates_basic() { assertTrue(requestMap.containsKey("unused")); } + @Test public void testExpandTemplates_basicEncodeValue() { SortedMap requestMap = Maps.newTreeMap(); requestMap.put("abc", "xyz;def"); @@ -65,12 +73,14 @@ public void testExpandTemplates_basicEncodeValue() { assertEquals("xyz;def", UriTemplate.expand("{+abc}", requestMap, false)); } + @Test public void testExpandTemplates_encodeSpace() { SortedMap requestMap = Maps.newTreeMap(); requestMap.put("abc", "xyz def"); assertEquals(";abc=xyz%20def", UriTemplate.expand("{;abc}", requestMap, false)); } + @Test public void testExpandTemplates_noExpansionsWithQueryParams() { SortedMap requestMap = Maps.newTreeMap(); requestMap.put("abc", "xyz"); @@ -79,6 +89,7 @@ public void testExpandTemplates_noExpansionsWithQueryParams() { "foo/xyz/bar/123?abc=xyz&def=123", UriTemplate.expand("foo/xyz/bar/123", requestMap, true)); } + @Test public void testExpandTemplates_noExpansionsWithoutQueryParams() { SortedMap requestMap = Maps.newTreeMap(); requestMap.put("abc", "xyz"); @@ -86,12 +97,14 @@ public void testExpandTemplates_noExpansionsWithoutQueryParams() { assertEquals("foo/xyz/bar/123", UriTemplate.expand("foo/xyz/bar/123", requestMap, false)); } + @Test public void testExpandTemplates_missingParameter() { SortedMap requestMap = Maps.newTreeMap(); requestMap.put("abc", "xyz"); assertEquals("foo/xyz/bar/", UriTemplate.expand("foo/{abc}/bar/{def}", requestMap, true)); } + @Test public void testExpandTemplates_nullValue() { SortedMap requestMap = Maps.newTreeMap(); requestMap.put("abc", "xyz"); @@ -99,6 +112,7 @@ public void testExpandTemplates_nullValue() { assertEquals("foo/xyz/bar/", UriTemplate.expand("foo/{abc}/bar/{def}", requestMap, true)); } + @Test public void testExpandTemplates_emptyAndNullRequestMap() { SortedMap requestMap = Maps.newTreeMap(); assertEquals("foo//bar/", UriTemplate.expand("foo/{abc}/bar/{def}", requestMap, true)); @@ -129,6 +143,7 @@ private Iterable getListIterable() { {"{&d*}", "&d=red&d=green&d=blue"}, }; + @Test public void testExpandTemplates_explodeIterator() { for (String[] test : LIST_TESTS) { SortedMap requestMap = Maps.newTreeMap(); @@ -137,6 +152,7 @@ public void testExpandTemplates_explodeIterator() { } } + @Test public void testExpandTemplates_explodeIterable() { for (String[] test : LIST_TESTS) { SortedMap requestMap = Maps.newTreeMap(); @@ -150,12 +166,14 @@ enum testEnum { ONE } + @Test public void testExpandTemplates_explodeEnum() { SortedMap requestMap = Maps.newTreeMap(); requestMap.put("d", testEnum.ONE); assertEquals(testEnum.ONE.toString(), UriTemplate.expand("{d}", requestMap, true)); } + @Test public void testExpandTemplates_missingCompositeParameter() { SortedMap requestMap = Maps.newTreeMap(); requestMap.put("abc", "xyz"); @@ -163,6 +181,7 @@ public void testExpandTemplates_missingCompositeParameter() { assertEquals("?abc=xyz", UriTemplate.expand("{d}", requestMap, true)); } + @Test public void testExpandTemplates_emptyListParameter() { SortedMap requestMap = Maps.newTreeMap(); requestMap.put("d", Lists.newArrayList()); @@ -197,6 +216,7 @@ private Map getMapParams() { {"{&d*}", "&semi=%3B&dot=.&comma=%2C"}, }; + @Test public void testExpandTemplates_explodeMap() { for (String[] test : MAP_TESTS) { SortedMap requestMap = Maps.newTreeMap(); @@ -205,12 +225,14 @@ public void testExpandTemplates_explodeMap() { } } + @Test public void testExpandTemplates_emptyMapParameter() { SortedMap requestMap = Maps.newTreeMap(); requestMap.put("d", Maps.newTreeMap()); assertEquals("", UriTemplate.expand("{d}", requestMap, true)); } + @Test public void testExpandTemplates_unusedQueryParametersEncoding() { Map requestMap = Maps.newLinkedHashMap(); // Add unused params. @@ -222,6 +244,7 @@ public void testExpandTemplates_unusedQueryParametersEncoding() { UriTemplate.expand("", requestMap, true)); } + @Test public void testExpandTemplates_unusedListQueryParameters() { Map requestMap = Maps.newLinkedHashMap(); // Add unused params. @@ -236,6 +259,7 @@ public void testExpandTemplates_unusedListQueryParameters() { UriTemplate.expand("", requestMap, true)); } + @Test public void testExpandTemplates_mixedBagParameters() { Map requestMap = Maps.newLinkedHashMap(); // Add list params. @@ -264,6 +288,7 @@ public void testExpandTemplates_mixedBagParameters() { assertTrue(requestMap.containsKey("unused2")); } + @Test public void testExpandTemplates_withBaseUrl() { SortedMap requestMap = Maps.newTreeMap(); requestMap.put("abc", "xyz"); @@ -284,6 +309,7 @@ public void testExpandTemplates_withBaseUrl() { "https://test/base/path/", "http://test3/{abc}/{def}/bar/", requestMap, true)); } + @Test public void testExpandNonReservedNonComposite() { SortedMap requestMap = Maps.newTreeMap(); requestMap.put("abc", "xyz"); @@ -294,6 +320,7 @@ public void testExpandNonReservedNonComposite() { "foo/xyz/bar/a/b?c", UriTemplate.expand("foo/{abc}/bar/{+def}", requestMap, false)); } + @Test public void testExpandSeveralTemplates() { SortedMap map = Maps.newTreeMap(); map.put("id", "a"); @@ -302,6 +329,7 @@ public void testExpandSeveralTemplates() { assertEquals("?id=a&uid=b", UriTemplate.expand("{?id,uid}", map, false)); } + @Test public void testExpandSeveralTemplatesUnusedParameterInMiddle() { SortedMap map = Maps.newTreeMap(); map.put("id", "a"); @@ -310,6 +338,7 @@ public void testExpandSeveralTemplatesUnusedParameterInMiddle() { assertEquals("?id=a&uid=b", UriTemplate.expand("{?id,foo,bar,uid}", map, false)); } + @Test public void testExpandSeveralTemplatesFirstParameterUnused() { SortedMap map = Maps.newTreeMap(); map.put("id", "a"); @@ -318,11 +347,13 @@ public void testExpandSeveralTemplatesFirstParameterUnused() { assertEquals("?id=a&uid=b", UriTemplate.expand("{?foo,id,uid}", map, false)); } + @Test public void testExpandSeveralTemplatesNoParametersUsed() { SortedMap map = Maps.newTreeMap(); assertEquals("", UriTemplate.expand("{?id,uid}", map, false)); } + @Test public void testExpandTemplates_reservedExpansion_mustNotEscapeReservedCharSet() { String reservedSet = ":/?#[]@!$&'()*+,;="; @@ -336,6 +367,7 @@ public void testExpandTemplates_reservedExpansion_mustNotEscapeReservedCharSet() UriTemplate.expand("{+var}", requestMap, false)); } + @Test public void testExpandTemplates_reservedExpansion_mustNotEscapeUnreservedCharSet() { String unReservedSet = "-._~"; diff --git a/google-http-client/src/test/java/com/google/api/client/http/UrlEncodedContentTest.java b/google-http-client/src/test/java/com/google/api/client/http/UrlEncodedContentTest.java index 059d9e2c9..42510c279 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/UrlEncodedContentTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/UrlEncodedContentTest.java @@ -14,6 +14,11 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.api.client.testing.http.HttpTesting; import com.google.api.client.testing.http.MockHttpTransport; import com.google.api.client.util.ArrayMap; @@ -23,15 +28,19 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link UrlEncodedContent}. * * @author Yaniv Inbar */ -public class UrlEncodedContentTest extends TestCase { +@RunWith(JUnit4.class) +public class UrlEncodedContentTest { + @Test public void testWriteTo() throws IOException { subtestWriteTo("a=x", ArrayMap.of("a", "x"), false); subtestWriteTo("noval", ArrayMap.of("noval", ""), false); @@ -64,6 +73,7 @@ private void subtestWriteTo(String expected, Object data, boolean useEscapeUriPa assertEquals(expected, out.toString()); } + @Test public void testGetContent() throws Exception { HttpRequest request = new MockHttpTransport() @@ -75,6 +85,7 @@ public void testGetContent() throws Exception { assertEquals(content, UrlEncodedContent.getContent(request)); } + @Test public void testGetData() { try { new UrlEncodedContent(null); diff --git a/google-http-client/src/test/java/com/google/api/client/http/UrlEncodedParserTest.java b/google-http-client/src/test/java/com/google/api/client/http/UrlEncodedParserTest.java index e61799777..e4beed966 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/UrlEncodedParserTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/UrlEncodedParserTest.java @@ -14,6 +14,10 @@ package com.google.api.client.http; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + import com.google.api.client.util.ArrayMap; import com.google.api.client.util.GenericData; import com.google.api.client.util.Key; @@ -25,20 +29,17 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link UrlEncodedParser}. * * @author Yaniv Inbar */ -public class UrlEncodedParserTest extends TestCase { - - public UrlEncodedParserTest() {} - - public UrlEncodedParserTest(String name) { - super(name); - } +@RunWith(JUnit4.class) +public class UrlEncodedParserTest { public static class Simple { @@ -99,6 +100,7 @@ public Generic set(String fieldName, Object value) { } } + @Test public void testParse_simple() { Simple actual = new Simple(); UrlEncodedParser.parse( @@ -114,6 +116,7 @@ public void testParse_simple() { assertNull(expected.v); } + @Test public void testParse_generic() { Generic actual = new Generic(); UrlEncodedParser.parse("p=4&q=1&a=x&p=3&b=y&c=z&d=v&q=2&p=5&o=object", actual); @@ -128,6 +131,7 @@ public void testParse_generic() { assertEquals(ArrayList.class, actual.get("d").getClass()); } + @Test public void testParse_map() { ArrayMap actual = new ArrayMap(); UrlEncodedParser.parse("p=4&q=1&a=x&p=3&b=y&c=z&d=v&q=2&p=5&noval1&noval2=", actual); @@ -144,6 +148,7 @@ public void testParse_map() { assertEquals(ArrayList.class, actual.get("a").getClass()); } + @Test public void testParse_encoding() { ArrayMap actual = new ArrayMap(); UrlEncodedParser.parse("q=%20", actual); @@ -152,6 +157,7 @@ public void testParse_encoding() { assertEquals(expected, actual); } + @Test public void testParse_null() { ArrayMap actual = new ArrayMap(); UrlEncodedParser.parse((String) null, actual); @@ -177,6 +183,7 @@ public EnumValue set(String fieldName, Object value) { static final String ENUM_VALUE = "otherValue=other&value=VALUE"; + @Test public void testParse_enum() throws IOException { EnumValue actual = new EnumValue(); UrlEncodedParser.parse(ENUM_VALUE, actual); diff --git a/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java b/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java index 754ae8fad..9599507a2 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpRequestTest.java @@ -17,7 +17,10 @@ import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeoutException; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +@RunWith(JUnit4.class) public class NetHttpRequestTest { static class SleepingOutputWriter implements OutputWriter { diff --git a/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpResponseTest.java b/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpResponseTest.java index beb4891ef..f82c4b25f 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpResponseTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpResponseTest.java @@ -14,20 +14,25 @@ package com.google.api.client.http.javanet; +import static org.junit.Assert.assertEquals; + import com.google.api.client.testing.http.javanet.MockHttpURLConnection; import com.google.api.client.util.StringUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link NetHttpResponse}. * * @author Yaniv Inbar */ -public class NetHttpResponseTest extends TestCase { +@RunWith(JUnit4.class) +public class NetHttpResponseTest { private static final String VALID_RESPONSE = "This is a valid response."; private static final String ERROR_RESPONSE = "This is an error response."; @@ -45,6 +50,7 @@ public void subtestGetStatusCode(int expectedCode, int responseCode) throws IOEx .getStatusCode()); } + @Test public void testGetContent() throws IOException { subtestGetContent(0); subtestGetContent(200); @@ -103,6 +109,7 @@ public void subtestGetContentWithShortRead(int responseCode) throws IOException } } + @Test public void testSkippingBytes() throws IOException { MockHttpURLConnection connection = new MockHttpURLConnection(null) diff --git a/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpTransportTest.java b/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpTransportTest.java index 26ecd5139..87c5337c6 100644 --- a/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpTransportTest.java +++ b/google-http-client/src/test/java/com/google/api/client/http/javanet/NetHttpTransportTest.java @@ -14,6 +14,11 @@ package com.google.api.client.http.javanet; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpTransport; import com.google.api.client.testing.http.HttpTesting; @@ -33,15 +38,17 @@ import java.security.KeyStore; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import junit.framework.TestCase; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link NetHttpTransport}. * * @author Yaniv Inbar */ -public class NetHttpTransportTest extends TestCase { +@RunWith(JUnit4.class) +public class NetHttpTransportTest { private static final String[] METHODS = { "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE" @@ -55,6 +62,7 @@ public void testNotMtlsWithoutClientCert() throws Exception { assertFalse(transport.isMtls()); } + @Test public void testIsMtlsWithClientCert() throws Exception { KeyStore trustStore = KeyStore.getInstance("JKS"); KeyStore keyStore = KeyStore.getInstance("PKCS12"); @@ -73,6 +81,7 @@ public void testIsMtlsWithClientCert() throws Exception { assertTrue(transport.isMtls()); } + @Test public void testExecute_mock() throws Exception { for (String method : METHODS) { boolean isPutOrPost = method.equals("PUT") || method.equals("POST"); @@ -97,6 +106,7 @@ public void testExecute_mock() throws Exception { } } + @Test public void testExecute_methodUnchanged() throws Exception { String body = "Arbitrary body"; byte[] buf = StringUtils.getBytesUtf8(body); @@ -113,6 +123,7 @@ public void testExecute_methodUnchanged() throws Exception { } } + @Test public void testAbruptTerminationIsNoticedWithContentLength() throws Exception { String incompleteBody = "" + "Fixed size body test.\r\n" + "Incomplete response."; byte[] buf = StringUtils.getBytesUtf8(incompleteBody); @@ -138,6 +149,7 @@ public void testAbruptTerminationIsNoticedWithContentLength() throws Exception { assertTrue(thrown); } + @Test public void testAbruptTerminationIsNoticedWithContentLengthWithReadToBuf() throws Exception { String incompleteBody = "" + "Fixed size body test.\r\n" + "Incomplete response."; byte[] buf = StringUtils.getBytesUtf8(incompleteBody); diff --git a/google-http-client/src/test/java/com/google/api/client/json/GenericJsonTest.java b/google-http-client/src/test/java/com/google/api/client/json/GenericJsonTest.java index 5d56eae40..cfa2efcb3 100644 --- a/google-http-client/src/test/java/com/google/api/client/json/GenericJsonTest.java +++ b/google-http-client/src/test/java/com/google/api/client/json/GenericJsonTest.java @@ -14,15 +14,21 @@ package com.google.api.client.json; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link GenericJson}. * * @author Yaniv Inbar */ -public class GenericJsonTest extends TestCase { +@RunWith(JUnit4.class) +public class GenericJsonTest { + @Test public void testToString_noFactory() { GenericJson data = new GenericJson(); data.put("a", "b"); diff --git a/google-http-client/src/test/java/com/google/api/client/json/JsonObjectParserTest.java b/google-http-client/src/test/java/com/google/api/client/json/JsonObjectParserTest.java index d4f030a22..394468553 100644 --- a/google-http-client/src/test/java/com/google/api/client/json/JsonObjectParserTest.java +++ b/google-http-client/src/test/java/com/google/api/client/json/JsonObjectParserTest.java @@ -14,6 +14,9 @@ package com.google.api.client.json; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import com.google.api.client.testing.json.MockJsonFactory; import com.google.api.client.testing.json.MockJsonParser; import com.google.common.base.Charsets; @@ -24,8 +27,9 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.nio.charset.Charset; -import junit.framework.TestCase; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests for the {@link JsonObjectParser} class. @@ -33,7 +37,8 @@ * @author Matthias Linder (mlinder) * @since 1.10 */ -public class JsonObjectParserTest extends TestCase { +@RunWith(JUnit4.class) +public class JsonObjectParserTest { @Test public void testConstructor_null() { diff --git a/google-http-client/src/test/java/com/google/api/client/json/JsonParserTest.java b/google-http-client/src/test/java/com/google/api/client/json/JsonParserTest.java index 3f4db6fc9..ffedade88 100644 --- a/google-http-client/src/test/java/com/google/api/client/json/JsonParserTest.java +++ b/google-http-client/src/test/java/com/google/api/client/json/JsonParserTest.java @@ -14,17 +14,24 @@ package com.google.api.client.json; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.google.api.client.testing.json.MockJsonFactory; import com.google.api.client.testing.json.MockJsonParser; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link JsonParser}. * * @author Yaniv Inbar */ -public class JsonParserTest extends TestCase { +@RunWith(JUnit4.class) +public class JsonParserTest { + @Test public void testParseAndClose_noInput() throws Exception { MockJsonParser parser = (MockJsonParser) new MockJsonFactory().createJsonParser(""); try { @@ -35,6 +42,7 @@ public void testParseAndClose_noInput() throws Exception { } } + @Test public void testParseAndClose_noInputVoid() throws Exception { MockJsonParser parser = (MockJsonParser) new MockJsonFactory().createJsonParser(""); parser.parseAndClose(Void.class); diff --git a/google-http-client/src/test/java/com/google/api/client/json/webtoken/JsonWebSignatureTest.java b/google-http-client/src/test/java/com/google/api/client/json/webtoken/JsonWebSignatureTest.java index 78fb06def..94a688162 100644 --- a/google-http-client/src/test/java/com/google/api/client/json/webtoken/JsonWebSignatureTest.java +++ b/google-http-client/src/test/java/com/google/api/client/json/webtoken/JsonWebSignatureTest.java @@ -39,12 +39,15 @@ import javax.net.ssl.X509TrustManager; import org.junit.Assert; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link JsonWebSignature}. * * @author Yaniv Inbar */ +@RunWith(JUnit4.class) public class JsonWebSignatureTest { @Test diff --git a/google-http-client/src/test/java/com/google/api/client/testing/http/FixedClockTest.java b/google-http-client/src/test/java/com/google/api/client/testing/http/FixedClockTest.java index 002685427..ccc441fac 100644 --- a/google-http-client/src/test/java/com/google/api/client/testing/http/FixedClockTest.java +++ b/google-http-client/src/test/java/com/google/api/client/testing/http/FixedClockTest.java @@ -14,15 +14,21 @@ package com.google.api.client.testing.http; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests for the {@link FixedClock}. * * @author mlinder@google.com (Matthias Linder) */ -public class FixedClockTest extends TestCase { +@RunWith(JUnit4.class) +public class FixedClockTest { /** Tests that the {@link FixedClock#currentTimeMillis()} method will return the mocked values. */ + @Test public void testCurrentTimeMillis() { // Check that the initial value is set properly. FixedClock clock = new FixedClock(100); diff --git a/google-http-client/src/test/java/com/google/api/client/testing/http/MockHttpTransportTest.java b/google-http-client/src/test/java/com/google/api/client/testing/http/MockHttpTransportTest.java index ea5851917..a78f127da 100644 --- a/google-http-client/src/test/java/com/google/api/client/testing/http/MockHttpTransportTest.java +++ b/google-http-client/src/test/java/com/google/api/client/testing/http/MockHttpTransportTest.java @@ -19,17 +19,21 @@ import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link MockHttpTransport}. * * @author Paweł Zuzelski */ -public final class MockHttpTransportTest extends TestCase { +@RunWith(JUnit4.class) +public final class MockHttpTransportTest { // The purpose of this test is to verify, that the actual lowLevelHttpRequest used is preserved // so that the content of the request can be verified in tests. - public void testBuildGetRequest_preservesLoLevelHttpRequest() throws Exception { + @Test + public void testBuildGetRequest_preservesLowLevelHttpRequest() throws Exception { MockHttpTransport httpTransport = new MockHttpTransport(); GenericUrl url = new GenericUrl("http://example.org"); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(); diff --git a/google-http-client/src/test/java/com/google/api/client/testing/http/MockLowLevelHttpRequestTest.java b/google-http-client/src/test/java/com/google/api/client/testing/http/MockLowLevelHttpRequestTest.java index 3c887a3ef..144ff1c73 100644 --- a/google-http-client/src/test/java/com/google/api/client/testing/http/MockLowLevelHttpRequestTest.java +++ b/google-http-client/src/test/java/com/google/api/client/testing/http/MockLowLevelHttpRequestTest.java @@ -14,17 +14,23 @@ package com.google.api.client.testing.http; +import static org.junit.Assert.assertEquals; + import com.google.api.client.util.ByteArrayStreamingContent; import com.google.api.client.util.StringUtils; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link MockLowLevelHttpRequest}. * * @author Yaniv Inbar */ -public class MockLowLevelHttpRequestTest extends TestCase { +@RunWith(JUnit4.class) +public class MockLowLevelHttpRequestTest { + @Test public void testGetContentAsString() throws Exception { subtestGetContentAsString("", null); subtestGetContentAsString("hello", "hello"); diff --git a/google-http-client/src/test/java/com/google/api/client/testing/http/javanet/MockHttpUrlConnectionTest.java b/google-http-client/src/test/java/com/google/api/client/testing/http/javanet/MockHttpUrlConnectionTest.java index 4dbf2df37..5a64c1f79 100644 --- a/google-http-client/src/test/java/com/google/api/client/testing/http/javanet/MockHttpUrlConnectionTest.java +++ b/google-http-client/src/test/java/com/google/api/client/testing/http/javanet/MockHttpUrlConnectionTest.java @@ -14,6 +14,9 @@ package com.google.api.client.testing.http.javanet; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + import com.google.api.client.testing.http.HttpTesting; import com.google.api.client.util.StringUtils; import java.io.ByteArrayInputStream; @@ -23,10 +26,13 @@ import java.util.Arrays; import java.util.List; import java.util.Map; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Tests {@link MockHttpURLConnection}. */ -public class MockHttpUrlConnectionTest extends TestCase { +@RunWith(JUnit4.class) +public class MockHttpUrlConnectionTest { private static final String RESPONSE_BODY = "body"; private static final String HEADER_NAME = "Custom-Header"; @@ -37,6 +43,7 @@ public void testSetGetHeaders() throws IOException { assertEquals("100", connection.getHeaderField(HEADER_NAME)); } + @Test public void testSetGetMultipleHeaders() throws IOException { MockHttpURLConnection connection = new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL)); List values = Arrays.asList("value1", "value2", "value3"); @@ -50,11 +57,13 @@ public void testSetGetMultipleHeaders() throws IOException { } } + @Test public void testGetNonExistingHeader() throws IOException { MockHttpURLConnection connection = new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL)); assertNull(connection.getHeaderField(HEADER_NAME)); } + @Test public void testSetInputStreamAndInputStreamImmutable() throws IOException { MockHttpURLConnection connection = new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL)); connection.setInputStream(new ByteArrayInputStream(StringUtils.getBytesUtf8(RESPONSE_BODY))); diff --git a/google-http-client/src/test/java/com/google/api/client/testing/util/MockBackOffTest.java b/google-http-client/src/test/java/com/google/api/client/testing/util/MockBackOffTest.java index 9fdc66ecf..8260c2082 100644 --- a/google-http-client/src/test/java/com/google/api/client/testing/util/MockBackOffTest.java +++ b/google-http-client/src/test/java/com/google/api/client/testing/util/MockBackOffTest.java @@ -14,17 +14,23 @@ package com.google.api.client.testing.util; +import static org.junit.Assert.assertEquals; + import com.google.api.client.util.BackOff; import java.io.IOException; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link MockBackOff}. * * @author Yaniv Inbar */ -public class MockBackOffTest extends TestCase { +@RunWith(JUnit4.class) +public class MockBackOffTest { + @Test public void testNextBackOffMillis() throws IOException { subtestNextBackOffMillis(0, new MockBackOff()); subtestNextBackOffMillis(BackOff.STOP, new MockBackOff().setBackOffMillis(BackOff.STOP)); diff --git a/google-http-client/src/test/java/com/google/api/client/util/ArrayMapTest.java b/google-http-client/src/test/java/com/google/api/client/util/ArrayMapTest.java index b08c2fa29..8aa50280c 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/ArrayMapTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/ArrayMapTest.java @@ -14,28 +14,31 @@ package com.google.api.client.util; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.util.Iterator; import java.util.Map; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link ArrayMap}. * * @author Yaniv Inbar */ -public class ArrayMapTest extends TestCase { - - public ArrayMapTest() {} - - public ArrayMapTest(String testName) { - super(testName); - } +@RunWith(JUnit4.class) +public class ArrayMapTest { + @Test public void testOf_zero() { ArrayMap map = ArrayMap.of(); assertTrue(map.isEmpty()); } + @Test public void testOf_one() { ArrayMap map = ArrayMap.of("a", 1); assertEquals(1, map.size()); @@ -43,6 +46,7 @@ public void testOf_one() { assertEquals((Integer) 1, map.getValue(0)); } + @Test public void testOf_two() { ArrayMap map = ArrayMap.of("a", 1, "b", 2); assertEquals(2, map.size()); @@ -52,30 +56,35 @@ public void testOf_two() { assertEquals((Integer) 2, map.getValue(1)); } + @Test public void testRemove1() { ArrayMap map = ArrayMap.of("a", 1, "b", 2); map.remove("b"); assertEquals(ArrayMap.of("a", 1), map); } + @Test public void testRemove2() { ArrayMap map = ArrayMap.of("a", 1, "b", 2); map.remove("a"); assertEquals(ArrayMap.of("b", 2), map); } + @Test public void testRemove3() { ArrayMap map = ArrayMap.of("a", 1); map.remove("a"); assertEquals(ArrayMap.of(), map); } + @Test public void testRemove4() { ArrayMap map = ArrayMap.of("a", 1, "b", 2, "c", 3); map.remove("b"); assertEquals(ArrayMap.of("a", 1, "c", 3), map); } + @Test public void testClone_changingEntrySet() { ArrayMap map = ArrayMap.of(); assertEquals("{}", map.toString()); @@ -84,6 +93,7 @@ public void testClone_changingEntrySet() { assertEquals("{foo=bar}", clone.toString()); } + @Test public void testSet() { ArrayMap map = ArrayMap.of(); map.set(0, "a", 1); @@ -102,6 +112,7 @@ public void testSet() { } } + @Test public void testHashCode() { ArrayMap map = ArrayMap.of(); map.set(0, "a", null); @@ -111,6 +122,7 @@ public void testHashCode() { assertTrue(map.hashCode() > 0); } + @Test public void testIteratorRemove1() { ArrayMap map = new ArrayMap(); map.put("a", "a"); @@ -126,6 +138,7 @@ public void testIteratorRemove1() { assertEquals(0, map.size()); } + @Test public void testIteratorRemove2() { ArrayMap map = new ArrayMap(); map.put("a", "a"); @@ -143,6 +156,7 @@ public void testIteratorRemove2() { assertEquals("c", map.get("c")); } + @Test public void testIteratorRemove3() { ArrayMap map = new ArrayMap(); map.put("a", "a"); diff --git a/google-http-client/src/test/java/com/google/api/client/util/BackOffTest.java b/google-http-client/src/test/java/com/google/api/client/util/BackOffTest.java index b88dd780b..9e462f58b 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/BackOffTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/BackOffTest.java @@ -14,16 +14,22 @@ package com.google.api.client.util; +import static org.junit.Assert.assertEquals; + import java.io.IOException; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link BackOff}. * * @author Yaniv Inbar */ -public class BackOffTest extends TestCase { +@RunWith(JUnit4.class) +public class BackOffTest { + @Test public void testNextBackOffMillis() throws IOException { subtestNextBackOffMillis(0, BackOff.ZERO_BACKOFF); subtestNextBackOffMillis(BackOff.STOP, BackOff.STOP_BACKOFF); diff --git a/google-http-client/src/test/java/com/google/api/client/util/BackOffUtilsTest.java b/google-http-client/src/test/java/com/google/api/client/util/BackOffUtilsTest.java index 79ddc4f5e..dc07b2cf6 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/BackOffUtilsTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/BackOffUtilsTest.java @@ -14,17 +14,23 @@ package com.google.api.client.util; +import static org.junit.Assert.assertEquals; + import com.google.api.client.testing.util.MockBackOff; import com.google.api.client.testing.util.MockSleeper; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link BackOffUtils}. * * @author Yaniv Inbar */ -public class BackOffUtilsTest extends TestCase { +@RunWith(JUnit4.class) +public class BackOffUtilsTest { + @Test public void testNext() throws Exception { subtestNext(7); subtestNext(0); diff --git a/google-http-client/src/test/java/com/google/api/client/util/Base64Test.java b/google-http-client/src/test/java/com/google/api/client/util/Base64Test.java index 218dd1f1b..cfc8e937f 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/Base64Test.java +++ b/google-http-client/src/test/java/com/google/api/client/util/Base64Test.java @@ -15,27 +15,35 @@ package com.google.api.client.util; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import java.nio.charset.StandardCharsets; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link Base64}. * * @author Jeff Ching */ -public class Base64Test extends TestCase { +@RunWith(JUnit4.class) +public class Base64Test { + @Test public void test_decodeBase64_withPadding() { String encoded = "Zm9vOmJhcg=="; assertEquals("foo:bar", new String(Base64.decodeBase64(encoded), StandardCharsets.UTF_8)); } + @Test public void test_decodeBase64_withoutPadding() { String encoded = "Zm9vOmJhcg"; assertEquals("foo:bar", new String(Base64.decodeBase64(encoded), StandardCharsets.UTF_8)); } + @Test public void test_decodeBase64_withTrailingWhitespace() { // Some internal use cases append extra space characters that apache-commons base64 decoding // previously handled. @@ -43,28 +51,34 @@ public void test_decodeBase64_withTrailingWhitespace() { assertEquals("foo:bar", new String(Base64.decodeBase64(encoded), StandardCharsets.UTF_8)); } + @Test public void test_decodeBase64_withNullBytes_shouldReturnNull() { byte[] encoded = null; assertNull(Base64.decodeBase64(encoded)); } + @Test public void test_decodeBase64_withNull_shouldReturnNull() { String encoded = null; assertNull(Base64.decodeBase64(encoded)); } + @Test public void test_encodeBase64URLSafeString_withNull_shouldReturnNull() { assertNull(Base64.encodeBase64URLSafeString(null)); } + @Test public void test_encodeBase64URLSafe_withNull_shouldReturnNull() { assertNull(Base64.encodeBase64URLSafe(null)); } + @Test public void test_encodeBase64_withNull_shouldReturnNull() { assertNull(Base64.encodeBase64(null)); } + @Test public void test_decodeBase64_newline_character_invalid_length() { // The RFC 4648 (https://datatracker.ietf.org/doc/html/rfc4648#section-3.3) states that a // specification referring to the Base64 encoding may state that it ignores characters outside @@ -91,6 +105,7 @@ public void test_decodeBase64_newline_character_invalid_length() { assertEquals("abcdef", new String(Base64.decodeBase64(encodedString), StandardCharsets.UTF_8)); } + @Test public void test_decodeBase64_newline_character() { // In Base64 encoding, 2 characters (16 bits) are converted to 3 of 6-bits plus the padding // character ('="). @@ -112,6 +127,7 @@ public void test_decodeBase64_newline_character() { assertEquals("ab", new String(Base64.decodeBase64(encodedString), StandardCharsets.UTF_8)); } + @Test public void test_decodeBase64_plus_and_newline_characters() { // The plus sign is 62 in the Base64 table. So it's a valid character in encoded strings. // https://datatracker.ietf.org/doc/html/rfc4648#section-4 @@ -123,6 +139,7 @@ public void test_decodeBase64_plus_and_newline_characters() { assertThat(actual).isEqualTo(new byte[] {(byte) 0xfb}); } + @Test public void test_decodeBase64_slash_and_newline_characters() { // The slash sign is 63 in the Base64 table. So it's a valid character in encoded strings. // https://datatracker.ietf.org/doc/html/rfc4648#section-4 diff --git a/google-http-client/src/test/java/com/google/api/client/util/ClassInfoTest.java b/google-http-client/src/test/java/com/google/api/client/util/ClassInfoTest.java index 380fd6189..d5e51d120 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/ClassInfoTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/ClassInfoTest.java @@ -14,17 +14,25 @@ package com.google.api.client.util; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import java.util.Arrays; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link ClassInfo}. * * @author Yaniv Inbar */ -public class ClassInfoTest extends TestCase { +@RunWith(JUnit4.class) +public class ClassInfoTest { public enum E { @Value @@ -36,11 +44,13 @@ public enum E { IGNORED_VALUE } + @Test public void testIsEnum() { assertTrue(ClassInfo.of(E.class).isEnum()); assertFalse(ClassInfo.of(String.class).isEnum()); } + @Test public void testGetFieldInfo_enum() throws Exception { ClassInfo classInfo = ClassInfo.of(E.class); assertEquals(E.class.getField("NULL"), classInfo.getFieldInfo(null).getField()); @@ -76,21 +86,25 @@ public class A1 { String foo2; } + @Test public void testNames() { assertEquals(ImmutableList.of("AbC", "b", "oc"), ClassInfo.of(A.class).names); assertEquals(ImmutableList.of("AbC", "b", "e", "oc"), ClassInfo.of(B.class).names); } + @Test public void testNames_ignoreCase() { assertEquals(ImmutableList.of("abc", "b", "oc"), ClassInfo.of(A.class, true).names); assertEquals(ImmutableList.of("abc", "b", "e", "oc"), ClassInfo.of(B.class, true).names); } + @Test public void testNames_enum() { ClassInfo classInfo = ClassInfo.of(E.class); assertEquals(Lists.newArrayList(Arrays.asList(null, "VALUE", "other")), classInfo.names); } + @Test public void testOf() { try { ClassInfo.of(A1.class, true); diff --git a/google-http-client/src/test/java/com/google/api/client/util/ClockTest.java b/google-http-client/src/test/java/com/google/api/client/util/ClockTest.java index 8af12e19c..e87a4fc61 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/ClockTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/ClockTest.java @@ -14,15 +14,22 @@ package com.google.api.client.util; -import junit.framework.TestCase; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests for the {@link Clock}. * * @author mlinder@google.com (Matthias Linder) */ -public class ClockTest extends TestCase { +@RunWith(JUnit4.class) +public class ClockTest { /** Tests that the Clock.SYSTEM.currentTimeMillis() method returns useful values. */ + @Test public void testSystemClock() { assertNotNull(Clock.SYSTEM); diff --git a/google-http-client/src/test/java/com/google/api/client/util/DataMapTest.java b/google-http-client/src/test/java/com/google/api/client/util/DataMapTest.java index 82b7ed2a4..45f07d5c2 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/DataMapTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/DataMapTest.java @@ -14,24 +14,34 @@ package com.google.api.client.util; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import java.util.Iterator; import java.util.Map; -import junit.framework.TestCase; +import org.checkerframework.checker.units.qual.A; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link DataMap}. * * @author Yaniv Inbar */ -public class DataMapTest extends TestCase { +@RunWith(JUnit4.class) +public class DataMapTest { static class A { @Key String r; @Key String s; @Key String t; } + @Test public void testSizeAndIsEmpty() { A a = new A(); DataMap map = new DataMap(a, false); @@ -48,6 +58,7 @@ public void testSizeAndIsEmpty() { assertFalse(map.isEmpty()); } + @Test public void testIterator() { A a = new A(); a.s = "value"; @@ -62,6 +73,7 @@ public void testIterator() { assertFalse(iterator.hasNext()); } + @Test public void testValues() { A a = new A(); a.r = "r"; @@ -77,6 +89,7 @@ public void testValues() { assertEquals(ImmutableList.of(), Lists.newArrayList(map.values())); } + @Test public void testKeys() { A a = new A(); a.r = "r"; @@ -92,6 +105,7 @@ public void testKeys() { assertEquals(ImmutableList.of(), Lists.newArrayList(map.keySet())); } + @Test public void testClear() { A a = new A(); a.r = "r"; @@ -103,6 +117,7 @@ public void testClear() { assertTrue(map.isEmpty()); } + @Test public void testGetKeyAndContainsKey() { A a = new A(); a.r = "rv"; @@ -115,6 +130,7 @@ public void testGetKeyAndContainsKey() { assertTrue(map.containsKey("r")); } + @Test public void testPut() { A a = new A(); a.r = "rv"; diff --git a/google-http-client/src/test/java/com/google/api/client/util/DataTest.java b/google-http-client/src/test/java/com/google/api/client/util/DataTest.java index 5cce2816a..1d2946f25 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/DataTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/DataTest.java @@ -14,6 +14,13 @@ package com.google.api.client.util; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.common.collect.ImmutableMap; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; @@ -39,15 +46,19 @@ import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentMap; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link Data}. * * @author Yaniv Inbar */ -public class DataTest extends TestCase { +@RunWith(JUnit4.class) +public class DataTest { + @Test public void testNullOf() { assertEquals("java.lang.Object", Data.nullOf(Object.class).getClass().getName()); assertEquals("java.lang.String", Data.nullOf(String.class).getClass().getName()); @@ -69,12 +80,14 @@ public void testNullOf() { } } + @Test public void testNullOfTemplateTypes() { String nullValue = Data.nullOf(String.class); Map nullField = ImmutableMap.of("v", nullValue); assertEquals(nullValue, nullField.get("v")); } + @Test public void testIsNull() { assertTrue(Data.isNull(Data.NULL_BOOLEAN)); assertTrue(Data.isNull(Data.NULL_STRING)); @@ -102,6 +115,7 @@ public void testIsNull() { assertFalse(Data.isNull(BigInteger.ZERO)); } + @Test public void testClone_array() { String[] orig = new String[] {"a", "b", "c"}; String[] result = Data.clone(orig); @@ -109,6 +123,7 @@ public void testClone_array() { assertTrue(Arrays.equals(orig, result)); } + @Test public void testClone_intArray() { int[] orig = new int[] {1, 2, 3}; int[] result = Data.clone(orig); @@ -116,12 +131,14 @@ public void testClone_intArray() { assertTrue(Arrays.equals(orig, result)); } + @Test public void testClone_arrayMap() { ArrayMap map = ArrayMap.of(); map.add("a", 1); assertEquals(map, Data.clone(map)); } + @Test public void testClone_ArraysAsList() { { List orig = Arrays.asList("a", "b", "c", new ArrayList()); @@ -139,6 +156,7 @@ public void testClone_ArraysAsList() { } } + @Test public void testNewCollectionInstance() throws Exception { assertEquals(ArrayList.class, Data.newCollectionInstance(null).getClass()); assertEquals(ArrayList.class, Data.newCollectionInstance(String[].class).getClass()); @@ -173,6 +191,7 @@ public void testNewCollectionInstance() throws Exception { } } + @Test public void testNewMapInstance() { assertEquals(ArrayMap.class, Data.newMapInstance(Object.class).getClass()); assertEquals(ArrayMap.class, Data.newMapInstance(Map.class).getClass()); @@ -196,12 +215,14 @@ public void testNewMapInstance() { } } + @Test public void testIsPrimitive() { assertFalse(Data.isPrimitive(null)); assertTrue(Data.isPrimitive(int.class)); assertTrue(Data.isPrimitive(Integer.class)); } + @Test public void testParsePrimitiveValue() { assertNull(Data.parsePrimitiveValue(Boolean.class, null)); assertEquals("abc", Data.parsePrimitiveValue(null, "abc")); @@ -273,6 +294,7 @@ private enum MyEnum { } } + @Test public void testParsePrimitiveValueWithUnknownEnum() { try { Data.parsePrimitiveValue(MyEnum.class, "foo"); @@ -303,6 +325,7 @@ static class ParameterizedResolve extends Resolve, Integer> static class MedXResolve extends Resolve {} + @Test public void testResolveWildcardTypeOrTypeVariable() throws Exception { // t TypeVariable tTypeVar = (TypeVariable) Resolve.class.getField("t").getGenericType(); diff --git a/google-http-client/src/test/java/com/google/api/client/util/DateTimeTest.java b/google-http-client/src/test/java/com/google/api/client/util/DateTimeTest.java index ce7d2b027..66c0b7171 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/DateTimeTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/DateTimeTest.java @@ -14,30 +14,40 @@ package com.google.api.client.util; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.api.client.util.DateTime.SecondsAndNanos; import java.util.Date; import java.util.TimeZone; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link DateTime}. * * @author Yaniv Inbar */ -public class DateTimeTest extends TestCase { +@RunWith(JUnit4.class) +public class DateTimeTest { private TimeZone originalTimeZone; - @Override - protected void setUp() throws Exception { + @Before + public void setUp() throws Exception { originalTimeZone = TimeZone.getDefault(); } - @Override - protected void tearDown() throws Exception { + @Before + public void tearDown() throws Exception { TimeZone.setDefault(originalTimeZone); } + @Test public void testToStringRfc3339() { TimeZone.setDefault(TimeZone.getTimeZone("GMT-4")); @@ -69,6 +79,7 @@ public void testToStringRfc3339() { new DateTime(new Date(1352232644000L)).toStringRfc3339()); } + @Test public void testToStringRfc3339_dateOnly() { for (String timeZoneString : new String[] {"GMT-4", "UTC", "UTC-7"}) { TimeZone.setDefault(TimeZone.getTimeZone(timeZoneString)); @@ -78,6 +89,7 @@ public void testToStringRfc3339_dateOnly() { } } + @Test public void testEquals() throws InterruptedException { assertFalse( "Check equals with two different tz specified.", @@ -102,6 +114,7 @@ public void testEquals() throws InterruptedException { assertEquals(dateTime1, dateTime2); } + @Test public void testParseRfc3339() { expectExceptionForParseRfc3339(""); expectExceptionForParseRfc3339("abc"); @@ -182,6 +195,7 @@ public void testParseRfc3339() { * 2018-03-01T10:11:12.1000Z | 1519899072 | 100000000 * */ + @Test public void testParseRfc3339ToSecondsAndNanos() { assertParsedRfc3339( "2018-03-01T10:11:12.999Z", SecondsAndNanos.ofSecondsAndNanos(1519899072L, 999000000)); @@ -225,10 +239,12 @@ public void testParseRfc3339ToSecondsAndNanos() { "2018-03-01T10:11:12.1000Z", SecondsAndNanos.ofSecondsAndNanos(1519899072L, 100000000)); } + @Test public void testEpoch() { assertParsedRfc3339("1970-01-01T00:00:00.000Z", SecondsAndNanos.ofSecondsAndNanos(0, 0)); } + @Test public void testOneSecondBeforeEpoch() { assertParsedRfc3339("1969-12-31T23:59:59.000Z", SecondsAndNanos.ofSecondsAndNanos(-1, 0)); } @@ -240,6 +256,7 @@ private static void assertParsedRfc3339(String input, SecondsAndNanos expected) assertEquals("Nanos for " + input + " do not match", expected.getNanos(), actual.getNanos()); } + @Test public void testParseAndFormatRfc3339() { // .12 becomes .120 String input = "1996-12-19T16:39:57.12-08:00"; diff --git a/google-http-client/src/test/java/com/google/api/client/util/ExponentialBackOffTest.java b/google-http-client/src/test/java/com/google/api/client/util/ExponentialBackOffTest.java index 7d9fe9dff..194adbb2c 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/ExponentialBackOffTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/ExponentialBackOffTest.java @@ -14,19 +14,22 @@ package com.google.api.client.util; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link ExponentialBackOff}. * * @author Ravi Mistry */ -public class ExponentialBackOffTest extends TestCase { - - public ExponentialBackOffTest(String name) { - super(name); - } +@RunWith(JUnit4.class) +public class ExponentialBackOffTest { + @Test public void testConstructor() { ExponentialBackOff backOffPolicy = new ExponentialBackOff(); assertEquals( @@ -36,8 +39,8 @@ public void testConstructor() { ExponentialBackOff.DEFAULT_INITIAL_INTERVAL_MILLIS, backOffPolicy.getCurrentIntervalMillis()); assertEquals( - ExponentialBackOff.DEFAULT_RANDOMIZATION_FACTOR, backOffPolicy.getRandomizationFactor()); - assertEquals(ExponentialBackOff.DEFAULT_MULTIPLIER, backOffPolicy.getMultiplier()); + ExponentialBackOff.DEFAULT_RANDOMIZATION_FACTOR, backOffPolicy.getRandomizationFactor(), 0); + assertEquals(ExponentialBackOff.DEFAULT_MULTIPLIER, backOffPolicy.getMultiplier(), 0); assertEquals( ExponentialBackOff.DEFAULT_MAX_INTERVAL_MILLIS, backOffPolicy.getMaxIntervalMillis()); assertEquals( @@ -45,6 +48,7 @@ public void testConstructor() { backOffPolicy.getMaxElapsedTimeMillis()); } + @Test public void testBuilder() { ExponentialBackOff backOffPolicy = new ExponentialBackOff.Builder().build(); assertEquals( @@ -54,8 +58,8 @@ public void testBuilder() { ExponentialBackOff.DEFAULT_INITIAL_INTERVAL_MILLIS, backOffPolicy.getCurrentIntervalMillis()); assertEquals( - ExponentialBackOff.DEFAULT_RANDOMIZATION_FACTOR, backOffPolicy.getRandomizationFactor()); - assertEquals(ExponentialBackOff.DEFAULT_MULTIPLIER, backOffPolicy.getMultiplier()); + ExponentialBackOff.DEFAULT_RANDOMIZATION_FACTOR, backOffPolicy.getRandomizationFactor(), 0); + assertEquals(ExponentialBackOff.DEFAULT_MULTIPLIER, backOffPolicy.getMultiplier(), 0); assertEquals( ExponentialBackOff.DEFAULT_MAX_INTERVAL_MILLIS, backOffPolicy.getMaxIntervalMillis()); assertEquals( @@ -78,12 +82,13 @@ public void testBuilder() { .build(); assertEquals(testInitialInterval, backOffPolicy.getInitialIntervalMillis()); assertEquals(testInitialInterval, backOffPolicy.getCurrentIntervalMillis()); - assertEquals(testRandomizationFactor, backOffPolicy.getRandomizationFactor()); - assertEquals(testMultiplier, backOffPolicy.getMultiplier()); + assertEquals(testRandomizationFactor, backOffPolicy.getRandomizationFactor(), 0); + assertEquals(testMultiplier, backOffPolicy.getMultiplier(), 0); assertEquals(testMaxInterval, backOffPolicy.getMaxIntervalMillis()); assertEquals(testMaxElapsedTime, backOffPolicy.getMaxElapsedTimeMillis()); } + @Test public void testBackOff() throws Exception { int testInitialInterval = 500; double testRandomizationFactor = 0.1; @@ -110,6 +115,7 @@ public void testBackOff() throws Exception { } } + @Test public void testGetRandomizedInterval() { // 33% chance of being 1. assertEquals(1, ExponentialBackOff.getRandomValueFromInterval(0.5, 0, 2)); @@ -138,6 +144,7 @@ public long nanoTime() { } } + @Test public void testGetElapsedTimeMillis() { ExponentialBackOff backOffPolicy = new ExponentialBackOff.Builder().setNanoClock(new MyNanoClock()).build(); @@ -145,6 +152,7 @@ public void testGetElapsedTimeMillis() { assertEquals("elapsedTimeMillis=" + elapsedTimeMillis, 1000, elapsedTimeMillis); } + @Test public void testMaxElapsedTime() throws Exception { ExponentialBackOff backOffPolicy = new ExponentialBackOff.Builder().setNanoClock(new MyNanoClock(10000)).build(); @@ -155,6 +163,7 @@ public void testMaxElapsedTime() throws Exception { assertEquals(BackOff.STOP, backOffPolicy.nextBackOffMillis()); } + @Test public void testBackOffOverflow() throws Exception { int testInitialInterval = Integer.MAX_VALUE / 2; double testMultiplier = 2.1; diff --git a/google-http-client/src/test/java/com/google/api/client/util/FieldInfoTest.java b/google-http-client/src/test/java/com/google/api/client/util/FieldInfoTest.java index 0cd1c17de..03e9b3c00 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/FieldInfoTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/FieldInfoTest.java @@ -14,15 +14,21 @@ package com.google.api.client.util; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import com.google.api.client.json.GenericJson; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link FieldInfo}. * * @author Yaniv Inbar */ -public class FieldInfoTest extends TestCase { +@RunWith(JUnit4.class) +public class FieldInfoTest { public enum E { @Value @@ -34,6 +40,7 @@ public enum E { IGNORED_VALUE } + @Test public void testOf_enum() throws Exception { assertEquals(E.class.getField("VALUE"), FieldInfo.of(E.VALUE).getField()); assertEquals(E.class.getField("OTHER_VALUE"), FieldInfo.of(E.OTHER_VALUE).getField()); @@ -45,6 +52,7 @@ public void testOf_enum() throws Exception { } } + @Test public void testEnumValue() { assertEquals(E.VALUE, FieldInfo.of(E.VALUE).enumValue()); assertEquals(E.OTHER_VALUE, FieldInfo.of(E.OTHER_VALUE).enumValue()); @@ -66,6 +74,7 @@ public Data setPassCode(String passCode) { } } + @Test public void testSetValueCaseSensitivityPriority() { Data data = new Data(); data.setPasscode("pass1"); diff --git a/google-http-client/src/test/java/com/google/api/client/util/GenericDataTest.java b/google-http-client/src/test/java/com/google/api/client/util/GenericDataTest.java index 52b2b9a0a..3b823d411 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/GenericDataTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/GenericDataTest.java @@ -14,19 +14,27 @@ package com.google.api.client.util; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; + import com.google.api.client.util.GenericData.Flags; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; -import junit.framework.TestCase; import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link GenericData}. * * @author Yaniv Inbar */ -public class GenericDataTest extends TestCase { +@RunWith(JUnit4.class) +public class GenericDataTest { private class MyData extends GenericData { public MyData() { super(EnumSet.of(Flags.IGNORE_CASE)); @@ -66,6 +74,7 @@ public GenericData2() { public String fieldA; } + @Test public void testEquals_Symmetric() { GenericData actual = new GenericData1(); actual.set("fieldA", "bar"); @@ -80,6 +89,7 @@ public void testEquals_Symmetric() { assertFalse(expected.hashCode() == actual.hashCode()); } + @Test public void testEquals_SymmetricWithSameClass() { GenericData actual = new MyData(); actual.set("fieldA", "bar"); @@ -91,6 +101,7 @@ public void testEquals_SymmetricWithSameClass() { assertTrue(expected.hashCode() == expected.hashCode()); } + @Test public void testNotEquals_SymmetricWithSameClass() { GenericData actual = new MyData(); actual.set("fieldA", "bar"); @@ -102,6 +113,7 @@ public void testNotEquals_SymmetricWithSameClass() { assertFalse(expected.hashCode() == actual.hashCode()); } + @Test public void testClone_changingEntrySet() { GenericData data = new GenericData(); assertEquals("GenericData{classInfo=[], {}}", data.toString()); @@ -110,6 +122,7 @@ public void testClone_changingEntrySet() { assertEquals("GenericData{classInfo=[], {foo=bar}}", clone.toString()); } + @Test public void testSetIgnoreCase_unknownKey() { GenericData data = new GenericData(EnumSet.of(Flags.IGNORE_CASE)); data.set("Foobar", "oldValue"); @@ -122,6 +135,7 @@ public void testSetIgnoreCase_unknownKey() { assertEquals(1, data.getUnknownKeys().size()); } + @Test public void testSetIgnoreCase_class() { MyData data = new MyData(); data.set("FIELDA", "someValue"); @@ -129,6 +143,7 @@ public void testSetIgnoreCase_class() { assertEquals(0, data.getUnknownKeys().size()); } + @Test public void testPutIgnoreCase_class() { MyData data = new MyData(); data.fieldA = "123"; @@ -137,12 +152,14 @@ public void testPutIgnoreCase_class() { assertEquals(0, data.getUnknownKeys().size()); } + @Test public void testGetIgnoreCase_class() { MyData data = new MyData(); data.fieldA = "someValue"; assertEquals("someValue", data.get("FIELDA")); } + @Test public void testRemoveIgnoreCase_class() { MyData data = new MyData(); data.fieldA = "someValue"; @@ -153,6 +170,7 @@ public void testRemoveIgnoreCase_class() { } } + @Test public void testPutIgnoreCase_unknownKey() { GenericData data = new GenericData(EnumSet.of(Flags.IGNORE_CASE)); assertEquals(null, data.put("fooBAR", "oldValue")); @@ -165,6 +183,7 @@ public void testPutIgnoreCase_unknownKey() { assertEquals(1, data.getUnknownKeys().size()); } + @Test public void testGetIgnoreCase_unknownKey() { GenericData data = new GenericData(EnumSet.of(Flags.IGNORE_CASE)); data.set("One", 1); @@ -176,6 +195,7 @@ public void testGetIgnoreCase_unknownKey() { assertEquals(null, data.get("unknownKey")); } + @Test public void testRemoveIgnoreCase_unknownKey() { GenericData data = new GenericData(EnumSet.of(Flags.IGNORE_CASE)); data.set("One", 1); @@ -187,6 +207,7 @@ public void testRemoveIgnoreCase_unknownKey() { assertEquals(null, data.remove("TESTA")); } + @Test public void testPutShouldUseSetter() { MyData data = new MyData(); data.put("fieldB", "value1"); diff --git a/google-http-client/src/test/java/com/google/api/client/util/IOUtilsTest.java b/google-http-client/src/test/java/com/google/api/client/util/IOUtilsTest.java index 42166ae5d..c3c8acd17 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/IOUtilsTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/IOUtilsTest.java @@ -14,17 +14,25 @@ package com.google.api.client.util; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + import java.io.File; import java.io.IOException; import java.nio.file.Files; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link IOUtils}. * * @author Yaniv Inbar */ -public class IOUtilsTest extends TestCase { +@RunWith(JUnit4.class) +public class IOUtilsTest { static final String VALUE = "abc"; @@ -33,16 +41,19 @@ public void testSerialize() throws IOException { assertEquals(VALUE, IOUtils.deserialize(bytes)); } + @Test public void testDeserialize() throws IOException { assertNull(IOUtils.deserialize((byte[]) null)); } + @Test public void testIsSymbolicLink_false() throws IOException { File file = File.createTempFile("tmp", null); file.deleteOnExit(); assertFalse(IOUtils.isSymbolicLink(file)); } + @Test public void testIsSymbolicLink_true() throws IOException { File file = File.createTempFile("tmp", null); file.deleteOnExit(); diff --git a/google-http-client/src/test/java/com/google/api/client/util/LoggingStreamingContentTest.java b/google-http-client/src/test/java/com/google/api/client/util/LoggingStreamingContentTest.java index cfb4eca4e..6efbf19dd 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/LoggingStreamingContentTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/LoggingStreamingContentTest.java @@ -14,19 +14,25 @@ package com.google.api.client.util; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import com.google.api.client.testing.util.LogRecordingHandler; import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link LoggingStreamingContent}. * * @author Yaniv Inbar */ -public class LoggingStreamingContentTest extends TestCase { +@RunWith(JUnit4.class) +public class LoggingStreamingContentTest { static final Logger LOGGER = Logger.getLogger(LoggingStreamingContentTest.class.getName()); @@ -35,6 +41,7 @@ public class LoggingStreamingContentTest extends TestCase { private static final String SAMPLE = "123\u05D9\u05e0\u05D9\u05D1"; /** Test method for {@link LoggingStreamingContent#writeTo(java.io.OutputStream)}. */ + @Test public void testWriteTo() throws Exception { LoggingStreamingContent logContent = new LoggingStreamingContent( @@ -48,6 +55,7 @@ public void testWriteTo() throws Exception { assertEquals(Arrays.asList("Total: 11 bytes", SAMPLE), recorder.messages()); } + @Test public void testContentLoggingLimit() throws Exception { LOGGER.setLevel(Level.CONFIG); diff --git a/google-http-client/src/test/java/com/google/api/client/util/NanoClockTest.java b/google-http-client/src/test/java/com/google/api/client/util/NanoClockTest.java index 383da3f10..681fdd017 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/NanoClockTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/NanoClockTest.java @@ -14,15 +14,22 @@ package com.google.api.client.util; -import junit.framework.TestCase; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link NanoClock}. * * @author Yaniv Inbar */ -public class NanoClockTest extends TestCase { +@RunWith(JUnit4.class) +public class NanoClockTest { + @Test public void testSystemClock() { assertNotNull(NanoClock.SYSTEM); diff --git a/google-http-client/src/test/java/com/google/api/client/util/ObjectsTest.java b/google-http-client/src/test/java/com/google/api/client/util/ObjectsTest.java index 5327e9267..e4a36d4d7 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/ObjectsTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/ObjectsTest.java @@ -14,30 +14,39 @@ package com.google.api.client.util; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link Objects}. * * @author Yaniv Inbar */ -public class ObjectsTest extends TestCase { +@RunWith(JUnit4.class) +public class ObjectsTest { + @Test public void testToStringHelper() { String toTest = Objects.toStringHelper(new TestClass()).add("hello", "world").toString(); assertEquals("TestClass{hello=world}", toTest); } + @Test public void testConstructor_innerClass() { String toTest = Objects.toStringHelper(new TestClass()).toString(); assertEquals("TestClass{}", toTest); } + @Test public void testToString_oneIntegerField() { String toTest = Objects.toStringHelper(new TestClass()).add("field1", Integer.valueOf(42)).toString(); assertEquals("TestClass{field1=42}", toTest); } + @Test public void testToStringOmitNullValues_oneField() { String toTest = Objects.toStringHelper(new TestClass()).omitNullValues().add("field1", null).toString(); diff --git a/google-http-client/src/test/java/com/google/api/client/util/PemReaderTest.java b/google-http-client/src/test/java/com/google/api/client/util/PemReaderTest.java index c3d4e586f..80d9dc171 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/PemReaderTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/PemReaderTest.java @@ -16,15 +16,18 @@ import java.io.InputStream; import java.io.InputStreamReader; -import junit.framework.TestCase; import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link PemReader}. * * @author Yaniv Inbar */ -public class PemReaderTest extends TestCase { +@RunWith(JUnit4.class) +public class PemReaderTest { private static final byte[] EXPECTED_BYTES = { 48, -126, 2, 117, 2, 1, 0, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5, 0, 4, -126, 2, @@ -60,6 +63,7 @@ public class PemReaderTest extends TestCase { -28, 32, 4, 85, 69, 122, 111, 110, 100, -86, -73, 46 }; + @Test public void testReadFirstSectionAndClose() throws Exception { InputStream stream = getClass().getClassLoader().getResourceAsStream("com/google/api/client/util/secret.pem"); diff --git a/google-http-client/src/test/java/com/google/api/client/util/SecurityUtilsTest.java b/google-http-client/src/test/java/com/google/api/client/util/SecurityUtilsTest.java index 21bdd9dc3..611f2dad0 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/SecurityUtilsTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/SecurityUtilsTest.java @@ -14,6 +14,12 @@ package com.google.api.client.util; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.api.client.testing.json.webtoken.TestCertificates; import com.google.api.client.testing.util.SecurityTestUtils; import java.io.ByteArrayInputStream; @@ -25,15 +31,18 @@ import java.security.interfaces.RSAPublicKey; import java.util.ArrayList; import javax.net.ssl.X509TrustManager; -import junit.framework.TestCase; import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link SecurityUtils}. * * @author Yaniv Inbar */ -public class SecurityUtilsTest extends TestCase { +@RunWith(JUnit4.class) +public class SecurityUtilsTest { private static final byte[] ENCODED = { 48, -126, 2, 117, 2, 1, 0, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5, 0, 4, -126, 2, @@ -113,6 +122,7 @@ public class SecurityUtilsTest extends TestCase { + "22RFKkRCWD/bMD0wITAJBgUrDgMCGgUABBTypWwWM5JDub1RzIXkRwfD7oQ9XwQUbgGuCBGKiU1C" + "YAqwa61lyj/OG90CAgQA"; + @Test public void testLoadPrivateKeyFromKeyStore() throws Exception { byte[] secretP12 = Base64.decodeBase64(SECRET_P12_BASE64); ByteArrayInputStream stream = new ByteArrayInputStream(secretP12); @@ -125,6 +135,7 @@ public void testLoadPrivateKeyFromKeyStore() throws Exception { Assert.assertArrayEquals(ENCODED, actualEncoded); } + @Test public void testSign() throws Exception { byte[] actualSigned = SecurityUtils.sign( @@ -134,6 +145,7 @@ public void testSign() throws Exception { Assert.assertArrayEquals(SIGNED, actualSigned); } + @Test public void testVerify() throws Exception { Signature signatureAlgorithm = SecurityUtils.getSha256WithRsaSignatureAlgorithm(); RSAPublicKey publicKey = SecurityTestUtils.newRsaPublicKey(); @@ -155,14 +167,17 @@ public X509Certificate verifyX509(TestCertificates.CertData caCert) throws Excep signatureAlgorithm, trustManager, certChain, signature, data.getBytes("UTF-8")); } + @Test public void testVerifyX509() throws Exception { assertNotNull(verifyX509(TestCertificates.CA_CERT)); } + @Test public void testVerifyX509WrongCa() throws Exception { assertNull(verifyX509(TestCertificates.BOGUS_CA_CERT)); } + @Test public void testCreateMtlsKeyStoreNoCert() throws Exception { final InputStream certMissing = getClass() @@ -180,6 +195,7 @@ public void testCreateMtlsKeyStoreNoCert() throws Exception { assertTrue("should have caught an IllegalArgumentException", thrown); } + @Test public void testCreateMtlsKeyStoreNoPrivateKey() throws Exception { final InputStream privateKeyMissing = getClass().getClassLoader().getResourceAsStream("com/google/api/client/util/cert.pem"); @@ -195,6 +211,7 @@ public void testCreateMtlsKeyStoreNoPrivateKey() throws Exception { assertTrue("should have caught an IllegalArgumentException", thrown); } + @Test public void testCreateMtlsKeyStoreSuccess() throws Exception { InputStream certAndKey = getClass() diff --git a/google-http-client/src/test/java/com/google/api/client/util/StringUtilsTest.java b/google-http-client/src/test/java/com/google/api/client/util/StringUtilsTest.java index 3606f3ba3..5e0601b27 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/StringUtilsTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/StringUtilsTest.java @@ -14,40 +14,48 @@ package com.google.api.client.util; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link StringUtils}. * * @author Yaniv Inbar */ -public class StringUtilsTest extends TestCase { +@RunWith(JUnit4.class) +public class StringUtilsTest { private static final byte[] SAMPLE_UTF8 = new byte[] {49, 50, 51, -41, -103, -41, -96, -41, -103, -41, -111}; private static final String SAMPLE = "123\u05D9\u05e0\u05D9\u05D1"; - public StringUtilsTest(String testName) { - super(testName); - } - + @Test public void testLineSeparator() { assertNotNull(StringUtils.LINE_SEPARATOR); } + @Test public void testToBytesUtf8() { Assert.assertArrayEquals(SAMPLE_UTF8, StringUtils.getBytesUtf8(SAMPLE)); } + @Test public void testToBytesUtf8Null() { assertNull(StringUtils.getBytesUtf8(null)); } + @Test public void testFromBytesUtf8() { assertEquals(SAMPLE, StringUtils.newStringUtf8(SAMPLE_UTF8)); } + @Test public void testFromBytesUtf8Null() { assertNull(StringUtils.newStringUtf8(null)); } diff --git a/google-http-client/src/test/java/com/google/api/client/util/TypesTest.java b/google-http-client/src/test/java/com/google/api/client/util/TypesTest.java index 7cbf26bb0..595854e22 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/TypesTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/TypesTest.java @@ -14,6 +14,12 @@ package com.google.api.client.util; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; @@ -32,15 +38,19 @@ import java.util.Stack; import java.util.TreeMap; import java.util.Vector; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** * Tests {@link Types}. * * @author Yaniv Inbar */ -public class TypesTest extends TestCase { +@RunWith(JUnit4.class) +public class TypesTest { + @Test public void testIsAssignableToOrFrom() { assertTrue(Types.isAssignableToOrFrom(String.class, Object.class)); assertTrue(Types.isAssignableToOrFrom(String.class, String.class)); @@ -50,6 +60,7 @@ public void testIsAssignableToOrFrom() { static class Foo {} + @Test public void testNewInstance() { assertEquals(Object.class, Types.newInstance(Object.class).getClass()); assertEquals(String.class, Types.newInstance(String.class).getClass()); @@ -80,6 +91,7 @@ static class WildcardBounds { public Collection lower; } + @Test public void testGetBound() throws Exception { subtestGetBound(Object.class, "any"); subtestGetBound(Number.class, "upper"); @@ -112,6 +124,7 @@ static class ArrayResolve extends Resolve {} static class ParameterizedResolve extends Resolve, Integer> {} + @Test public void testResolveTypeVariable() throws Exception { // t TypeVariable tTypeVar = (TypeVariable) Resolve.class.getField("t").getGenericType(); @@ -158,6 +171,7 @@ public class A { public class B extends A {} + @Test public void testGetIterableParameter() throws Exception { assertEquals( "T", @@ -209,6 +223,7 @@ public class C { public class D extends C {} + @Test public void testGetMapParameter() throws Exception { assertEquals( "T", @@ -243,6 +258,7 @@ public void testGetMapParameter() throws Exception { .getUpperBounds()[0]); } + @Test public void testIterableOf() { List list = ImmutableList.of("a"); assertEquals(list, Types.iterableOf(list)); @@ -250,6 +266,7 @@ public void testIterableOf() { assertTrue(Iterables.elementsEqual(ImmutableList.of(1), Types.iterableOf(new int[] {1}))); } + @Test public void testToArray() { assertTrue( Arrays.equals( diff --git a/google-http-client/src/test/java/com/google/api/client/util/escape/CharEscapersTest.java b/google-http-client/src/test/java/com/google/api/client/util/escape/CharEscapersTest.java index 0a4e08809..340607f2a 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/escape/CharEscapersTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/escape/CharEscapersTest.java @@ -14,10 +14,18 @@ package com.google.api.client.util.escape; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; -public class CharEscapersTest extends TestCase { +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +@RunWith(JUnit4.class) +public class CharEscapersTest { + + @Test public void testDecodeUriPath() { subtestDecodeUriPath(null, null); subtestDecodeUriPath("", ""); @@ -31,6 +39,7 @@ private void subtestDecodeUriPath(String input, String expected) { assertEquals(expected, actual); } + @Test public void testDecodeUri_IllegalArgumentException() { subtestDecodeUri_IllegalArgumentException("abc%-1abc"); subtestDecodeUri_IllegalArgumentException("%JJ"); diff --git a/google-http-client/src/test/java/com/google/api/client/util/escape/PercentEscaperTest.java b/google-http-client/src/test/java/com/google/api/client/util/escape/PercentEscaperTest.java index fa8aeba9d..e38462ca1 100644 --- a/google-http-client/src/test/java/com/google/api/client/util/escape/PercentEscaperTest.java +++ b/google-http-client/src/test/java/com/google/api/client/util/escape/PercentEscaperTest.java @@ -16,7 +16,10 @@ import org.junit.Assert; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +@RunWith(JUnit4.class) public class PercentEscaperTest { @Test diff --git a/google-http-client/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client/native-image.properties b/google-http-client/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client/native-image.properties index 7bc87751b..be831a62d 100644 --- a/google-http-client/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client/native-image.properties +++ b/google-http-client/src/test/resources/META-INF/native-image/com.google.http-client/google-http-client/native-image.properties @@ -1,6 +1,4 @@ Args=--initialize-at-build-time=com.google.api.client.util.StringUtils \ ---initialize-at-build-time=com.google.api.client.http.HttpRequestTest \ ---initialize-at-build-time=com.google.api.client.http.ByteArrayContentTest \ ---initialize-at-build-time=com.google.api.client.http.MultipartContentTest \ ---initialize-at-build-time=com.google.api.client.util.LoggingStreamingContentTest \ ---initialize-at-build-time=com.google.api.client.util.SecurityUtilsTest \ No newline at end of file +--initialize-at-build-time=com.google.common.collect.RegularImmutableSet \ +--initialize-at-build-time=org.junit.runner.RunWith \ +--initialize-at-build-time=org.junit.runners.model.FrameworkField \ \ No newline at end of file diff --git a/pom.xml b/pom.xml index 2383dca87..54e063ea6 100644 --- a/pom.xml +++ b/pom.xml @@ -93,7 +93,7 @@ com.google.cloud native-image-shared-config - 1.13.0 + 1.14.0