diff options
author | Jisi Liu <jisi.liu@gmail.com> | 2016-03-30 11:39:59 -0700 |
---|---|---|
committer | Jisi Liu <jisi.liu@gmail.com> | 2016-03-30 11:39:59 -0700 |
commit | 3b3c8abb9635eb3ea078a821a99c9ef29d66dff7 (patch) | |
tree | 7d2ec154f15c9f9153d890e76b6cf30e471ea488 /java/core/src/test | |
parent | 78105897a8f01c7be9cf8502b6c58d47eb1ccdd7 (diff) | |
download | protobuf-3b3c8abb9635eb3ea078a821a99c9ef29d66dff7.tar.gz protobuf-3b3c8abb9635eb3ea078a821a99c9ef29d66dff7.tar.bz2 protobuf-3b3c8abb9635eb3ea078a821a99c9ef29d66dff7.zip |
Integrate google internal changes.
Diffstat (limited to 'java/core/src/test')
36 files changed, 1629 insertions, 607 deletions
diff --git a/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java b/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java index d964ef59..1e57b647 100644 --- a/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java +++ b/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java @@ -40,7 +40,6 @@ import protobuf_unittest.UnittestProto.TestPackedTypes; import protobuf_unittest.UnittestProto.TestRequired; import protobuf_unittest.UnittestProto.TestRequiredForeign; import protobuf_unittest.UnittestProto.TestUnpackedTypes; - import junit.framework.TestCase; import java.util.Map; diff --git a/java/core/src/test/java/com/google/protobuf/AnyTest.java b/java/core/src/test/java/com/google/protobuf/AnyTest.java index e169f69d..cf91ed91 100644 --- a/java/core/src/test/java/com/google/protobuf/AnyTest.java +++ b/java/core/src/test/java/com/google/protobuf/AnyTest.java @@ -75,6 +75,51 @@ public class AnyTest extends TestCase { } } + public void testCustomTypeUrls() throws Exception { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + TestUtil.setAllFields(builder); + TestAllTypes message = builder.build(); + + TestAny container = TestAny.newBuilder() + .setValue(Any.pack(message, "xxx.com")).build(); + + assertEquals( + "xxx.com/" + TestAllTypes.getDescriptor().getFullName(), + container.getValue().getTypeUrl()); + + assertTrue(container.getValue().is(TestAllTypes.class)); + assertFalse(container.getValue().is(TestAny.class)); + + TestAllTypes result = container.getValue().unpack(TestAllTypes.class); + TestUtil.assertAllFieldsSet(result); + + container = TestAny.newBuilder() + .setValue(Any.pack(message, "yyy.com/")).build(); + + assertEquals( + "yyy.com/" + TestAllTypes.getDescriptor().getFullName(), + container.getValue().getTypeUrl()); + + assertTrue(container.getValue().is(TestAllTypes.class)); + assertFalse(container.getValue().is(TestAny.class)); + + result = container.getValue().unpack(TestAllTypes.class); + TestUtil.assertAllFieldsSet(result); + + container = TestAny.newBuilder() + .setValue(Any.pack(message, "")).build(); + + assertEquals( + "/" + TestAllTypes.getDescriptor().getFullName(), + container.getValue().getTypeUrl()); + + assertTrue(container.getValue().is(TestAllTypes.class)); + assertFalse(container.getValue().is(TestAny.class)); + + result = container.getValue().unpack(TestAllTypes.class); + TestUtil.assertAllFieldsSet(result); + } + public void testCachedUnpackResult() throws Exception { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); TestUtil.setAllFields(builder); diff --git a/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java b/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java index 7a8a0a5e..db10ee74 100644 --- a/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java +++ b/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java @@ -37,7 +37,6 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.UnsupportedEncodingException; - /** * This class tests {@link BoundedByteString}, which extends {@link LiteralByteString}, * by inheriting the tests from {@link LiteralByteStringTest}. The only method which diff --git a/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java b/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java new file mode 100644 index 00000000..cbe742e5 --- /dev/null +++ b/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java @@ -0,0 +1,81 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package com.google.protobuf; + +import junit.framework.TestCase; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.Random; + +/** + * Tests for {@link ByteBufferWriter}. + */ +public class ByteBufferWriterTest extends TestCase { + + public void testHeapBuffer() throws IOException { + // Test a small and large buffer. + testWrite(ByteBuffer.allocate(100)); + testWrite(ByteBuffer.allocate(1024 * 100)); + } + + public void testDirectBuffer() throws IOException { + // Test a small and large buffer. + testWrite(ByteBuffer.allocateDirect(100)); + testWrite(ByteBuffer.allocateDirect(1024 * 100)); + } + + private void testWrite(ByteBuffer buffer) throws IOException { + fillRandom(buffer); + ByteArrayOutputStream os = new ByteArrayOutputStream(buffer.remaining()); + ByteBufferWriter.write(buffer, os); + assertEquals(0, buffer.position()); + assertTrue(Arrays.equals(toArray(buffer), os.toByteArray())); + } + + private void fillRandom(ByteBuffer buf) { + byte[] bytes = new byte[buf.remaining()]; + new Random().nextBytes(bytes); + buf.put(bytes); + buf.flip(); + return; + } + + private byte[] toArray(ByteBuffer buf) { + int originalPosition = buf.position(); + byte[] bytes = new byte[buf.remaining()]; + buf.get(bytes); + buf.position(originalPosition); + return bytes; + } +} diff --git a/java/core/src/test/java/com/google/protobuf/ByteStringTest.java b/java/core/src/test/java/com/google/protobuf/ByteStringTest.java index 5267c160..ad9f266e 100644 --- a/java/core/src/test/java/com/google/protobuf/ByteStringTest.java +++ b/java/core/src/test/java/com/google/protobuf/ByteStringTest.java @@ -39,6 +39,7 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; @@ -757,4 +758,17 @@ public class ByteStringTest extends TestCase { assertEquals((byte) 2, result[dataSize - dataSize / 2]); assertEquals((byte) 2, result[dataSize - 1]); } + + /** + * Tests ByteString uses Arrays based byte copier when running under Hotstop VM. + */ + public void testByteArrayCopier() throws Exception { + Field field = ByteString.class.getDeclaredField("byteArrayCopier"); + field.setAccessible(true); + Object byteArrayCopier = field.get(null); + assertNotNull(byteArrayCopier); + assertTrue( + byteArrayCopier.toString(), + byteArrayCopier.getClass().getSimpleName().endsWith("ArraysByteArrayCopier")); + } } diff --git a/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java b/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java index 3d6381c9..cc65d19a 100644 --- a/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java +++ b/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java @@ -34,6 +34,7 @@ import proto2_test_check_utf8.TestCheckUtf8.BytesWrapper; import proto2_test_check_utf8.TestCheckUtf8.StringWrapper; import proto2_test_check_utf8_size.TestCheckUtf8Size.BytesWrapperSize; import proto2_test_check_utf8_size.TestCheckUtf8Size.StringWrapperSize; + import junit.framework.TestCase; /** diff --git a/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java b/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java index 18d8142c..a1d6f1be 100644 --- a/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java +++ b/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java @@ -547,6 +547,56 @@ public class CodedInputStreamTest extends TestCase { } } + public void testReadString() throws Exception { + String lorem = "Lorem ipsum dolor sit amet "; + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < 4096; i += lorem.length()) { + builder.append(lorem); + } + lorem = builder.toString().substring(0, 4096); + byte[] bytes = lorem.getBytes("UTF-8"); + ByteString.Output rawOutput = ByteString.newOutput(); + CodedOutputStream output = CodedOutputStream.newInstance(rawOutput, bytes.length); + + int tag = WireFormat.makeTag(1, WireFormat.WIRETYPE_LENGTH_DELIMITED); + output.writeRawVarint32(tag); + output.writeRawVarint32(bytes.length); + output.writeRawBytes(bytes); + output.flush(); + + CodedInputStream input = + CodedInputStream.newInstance( + new ByteArrayInputStream(rawOutput.toByteString().toByteArray())); + assertEquals(tag, input.readTag()); + String text = input.readString(); + assertEquals(lorem, text); + } + + public void testReadStringRequireUtf8() throws Exception { + String lorem = "Lorem ipsum dolor sit amet "; + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < 4096; i += lorem.length()) { + builder.append(lorem); + } + lorem = builder.toString().substring(0, 4096); + byte[] bytes = lorem.getBytes("UTF-8"); + ByteString.Output rawOutput = ByteString.newOutput(); + CodedOutputStream output = CodedOutputStream.newInstance(rawOutput, bytes.length); + + int tag = WireFormat.makeTag(1, WireFormat.WIRETYPE_LENGTH_DELIMITED); + output.writeRawVarint32(tag); + output.writeRawVarint32(bytes.length); + output.writeRawBytes(bytes); + output.flush(); + + CodedInputStream input = + CodedInputStream.newInstance( + new ByteArrayInputStream(rawOutput.toByteString().toByteArray())); + assertEquals(tag, input.readTag()); + String text = input.readStringRequireUtf8(); + assertEquals(lorem, text); + } + /** * Tests that if we readString invalid UTF-8 bytes, no exception * is thrown. Instead, the invalid bytes are replaced with the Unicode diff --git a/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java b/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java index e7905f79..ce85ae2e 100644 --- a/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java +++ b/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java @@ -36,6 +36,7 @@ import junit.framework.TestCase; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; + /** * Test field deprecation * diff --git a/java/core/src/test/java/com/google/protobuf/DescriptorsTest.java b/java/core/src/test/java/com/google/protobuf/DescriptorsTest.java index 82ff34af..ef89b389 100644 --- a/java/core/src/test/java/com/google/protobuf/DescriptorsTest.java +++ b/java/core/src/test/java/com/google/protobuf/DescriptorsTest.java @@ -59,7 +59,6 @@ import protobuf_unittest.UnittestProto.TestMultipleExtensionRanges; import protobuf_unittest.UnittestProto.TestRequired; import protobuf_unittest.UnittestProto.TestReservedFields; import protobuf_unittest.UnittestProto.TestService; - import junit.framework.TestCase; import java.util.Arrays; @@ -573,6 +572,42 @@ public class DescriptorsTest extends TestCase { } } + public void testUnknownFieldsDenied() throws Exception { + FileDescriptorProto fooProto = FileDescriptorProto.newBuilder() + .setName("foo.proto") + .addMessageType(DescriptorProto.newBuilder() + .setName("Foo") + .addField(FieldDescriptorProto.newBuilder() + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setTypeName("Bar") + .setName("bar") + .setNumber(1))) + .build(); + + try { + Descriptors.FileDescriptor.buildFrom(fooProto, new FileDescriptor[0]); + fail("DescriptorValidationException expected"); + } catch (DescriptorValidationException e) { + assertTrue(e.getMessage().indexOf("Bar") != -1); + assertTrue(e.getMessage().indexOf("is not defined") != -1); + } + } + + public void testUnknownFieldsAllowed() throws Exception { + FileDescriptorProto fooProto = FileDescriptorProto.newBuilder() + .setName("foo.proto") + .addDependency("bar.proto") + .addMessageType(DescriptorProto.newBuilder() + .setName("Foo") + .addField(FieldDescriptorProto.newBuilder() + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setTypeName("Bar") + .setName("bar") + .setNumber(1))) + .build(); + Descriptors.FileDescriptor.buildFrom(fooProto, new FileDescriptor[0], true); + } + public void testHiddenDependency() throws Exception { FileDescriptorProto barProto = FileDescriptorProto.newBuilder() .setName("bar.proto") diff --git a/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java b/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java index 55144e7c..8f3a74c1 100644 --- a/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java +++ b/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java @@ -33,13 +33,13 @@ package com.google.protobuf; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.OneofDescriptor; - import protobuf_unittest.UnittestProto.TestAllExtensions; import protobuf_unittest.UnittestProto.TestAllTypes; import protobuf_unittest.UnittestProto.TestEmptyMessage; import protobuf_unittest.UnittestProto.TestPackedTypes; import junit.framework.TestCase; + import java.util.Arrays; /** diff --git a/java/core/src/test/java/com/google/protobuf/EnumTest.java b/java/core/src/test/java/com/google/protobuf/EnumTest.java new file mode 100644 index 00000000..14c7406b --- /dev/null +++ b/java/core/src/test/java/com/google/protobuf/EnumTest.java @@ -0,0 +1,76 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package com.google.protobuf; + +import com.google.protobuf.UnittestLite.ForeignEnumLite; +import com.google.protobuf.UnittestLite.TestAllTypesLite; +import protobuf_unittest.UnittestProto.ForeignEnum; +import protobuf_unittest.UnittestProto.TestAllTypes; + +import junit.framework.TestCase; + +public class EnumTest extends TestCase { + + public void testForNumber() { + ForeignEnum e = ForeignEnum.forNumber(ForeignEnum.FOREIGN_BAR.getNumber()); + assertEquals(ForeignEnum.FOREIGN_BAR, e); + + e = ForeignEnum.forNumber(1000); + assertEquals(null, e); + } + + public void testForNumber_oneof() { + TestAllTypes.OneofFieldCase e = TestAllTypes.OneofFieldCase.forNumber( + TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber()); + assertEquals(TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE, e); + + e = TestAllTypes.OneofFieldCase.forNumber(1000); + assertEquals(null, e); + } + + public void testForNumberLite() { + ForeignEnumLite e = ForeignEnumLite.forNumber(ForeignEnumLite.FOREIGN_LITE_BAR.getNumber()); + assertEquals(ForeignEnumLite.FOREIGN_LITE_BAR, e); + + e = ForeignEnumLite.forNumber(1000); + assertEquals(null, e); + } + + public void testForNumberLite_oneof() { + TestAllTypesLite.OneofFieldCase e = TestAllTypesLite.OneofFieldCase.forNumber( + TestAllTypesLite.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber()); + assertEquals(TestAllTypesLite.OneofFieldCase.ONEOF_NESTED_MESSAGE, e); + + e = TestAllTypesLite.OneofFieldCase.forNumber(1000); + assertEquals(null, e); + } +} + diff --git a/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java b/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java index eaeec0b8..304cec4f 100644 --- a/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java +++ b/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java @@ -44,9 +44,9 @@ import junit.framework.TestCase; * non-message fields. */ public class FieldPresenceTest extends TestCase { - private static boolean hasMethod(Class clazz, String name) { + private static boolean hasMethod(Class<?> clazz, String name) { try { - if (clazz.getMethod(name, new Class[]{}) != null) { + if (clazz.getMethod(name) != null) { return true; } else { return false; @@ -56,90 +56,90 @@ public class FieldPresenceTest extends TestCase { } } - private static boolean isHasMethodRemoved( - Class classWithFieldPresence, - Class classWithoutFieldPresence, + private static void assertHasMethodRemoved( + Class<?> classWithFieldPresence, + Class<?> classWithoutFieldPresence, String camelName) { - return hasMethod(classWithFieldPresence, "get" + camelName) - && hasMethod(classWithFieldPresence, "has" + camelName) - && hasMethod(classWithoutFieldPresence, "get" + camelName) - && !hasMethod(classWithoutFieldPresence, "has" + camelName); + assertTrue(hasMethod(classWithFieldPresence, "get" + camelName)); + assertTrue(hasMethod(classWithFieldPresence, "has" + camelName)); + assertTrue(hasMethod(classWithoutFieldPresence, "get" + camelName)); + assertFalse(hasMethod(classWithoutFieldPresence, "has" + camelName)); } public void testHasMethod() { // Optional non-message fields don't have a hasFoo() method generated. - assertTrue(isHasMethodRemoved( + assertHasMethodRemoved( UnittestProto.TestAllTypes.class, TestAllTypes.class, - "OptionalInt32")); - assertTrue(isHasMethodRemoved( + "OptionalInt32"); + assertHasMethodRemoved( UnittestProto.TestAllTypes.class, TestAllTypes.class, - "OptionalString")); - assertTrue(isHasMethodRemoved( + "OptionalString"); + assertHasMethodRemoved( UnittestProto.TestAllTypes.class, TestAllTypes.class, - "OptionalBytes")); - assertTrue(isHasMethodRemoved( + "OptionalBytes"); + assertHasMethodRemoved( UnittestProto.TestAllTypes.class, TestAllTypes.class, - "OptionalNestedEnum")); + "OptionalNestedEnum"); - assertTrue(isHasMethodRemoved( + assertHasMethodRemoved( UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, - "OptionalInt32")); - assertTrue(isHasMethodRemoved( + "OptionalInt32"); + assertHasMethodRemoved( UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, - "OptionalString")); - assertTrue(isHasMethodRemoved( + "OptionalString"); + assertHasMethodRemoved( UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, - "OptionalBytes")); - assertTrue(isHasMethodRemoved( + "OptionalBytes"); + assertHasMethodRemoved( UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, - "OptionalNestedEnum")); + "OptionalNestedEnum"); // message fields still have the hasFoo() method generated. assertFalse(TestAllTypes.newBuilder().build().hasOptionalNestedMessage()); assertFalse(TestAllTypes.newBuilder().hasOptionalNestedMessage()); // oneof fields don't have hasFoo() methods (even for message types). - assertTrue(isHasMethodRemoved( + assertHasMethodRemoved( UnittestProto.TestAllTypes.class, TestAllTypes.class, - "OneofUint32")); - assertTrue(isHasMethodRemoved( + "OneofUint32"); + assertHasMethodRemoved( UnittestProto.TestAllTypes.class, TestAllTypes.class, - "OneofString")); - assertTrue(isHasMethodRemoved( + "OneofString"); + assertHasMethodRemoved( UnittestProto.TestAllTypes.class, TestAllTypes.class, - "OneofBytes")); - assertTrue(isHasMethodRemoved( + "OneofBytes"); + assertHasMethodRemoved( UnittestProto.TestAllTypes.class, TestAllTypes.class, - "OneofNestedMessage")); + "OneofNestedMessage"); - assertTrue(isHasMethodRemoved( + assertHasMethodRemoved( UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, - "OneofUint32")); - assertTrue(isHasMethodRemoved( + "OneofUint32"); + assertHasMethodRemoved( UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, - "OneofString")); - assertTrue(isHasMethodRemoved( + "OneofString"); + assertHasMethodRemoved( UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, - "OneofBytes")); - assertTrue(isHasMethodRemoved( + "OneofBytes"); + assertHasMethodRemoved( UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, - "OneofNestedMessage")); + "OneofNestedMessage"); } public void testOneofEquals() throws Exception { @@ -232,24 +232,24 @@ public class FieldPresenceTest extends TestCase { assertTrue(message.hasField(optionalNestedEnumField)); assertEquals(4, message.getAllFields().size()); } - + public void testMessageField() { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); assertFalse(builder.hasOptionalNestedMessage()); assertFalse(builder.build().hasOptionalNestedMessage()); - + TestAllTypes.NestedMessage.Builder nestedBuilder = builder.getOptionalNestedMessageBuilder(); assertTrue(builder.hasOptionalNestedMessage()); assertTrue(builder.build().hasOptionalNestedMessage()); - + nestedBuilder.setValue(1); assertEquals(1, builder.build().getOptionalNestedMessage().getValue()); - + builder.clearOptionalNestedMessage(); assertFalse(builder.hasOptionalNestedMessage()); assertFalse(builder.build().hasOptionalNestedMessage()); - + // Unlike non-message fields, if we set a message field to its default value (i.e., // default instance), the field should be seen as present. builder.setOptionalNestedMessage(TestAllTypes.NestedMessage.getDefaultInstance()); @@ -340,7 +340,7 @@ public class FieldPresenceTest extends TestCase { assertTrue(builder.buildPartial().isInitialized()); } - + // Test that unknown fields are dropped. public void testUnknownFields() throws Exception { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); @@ -348,7 +348,7 @@ public class FieldPresenceTest extends TestCase { builder.addRepeatedInt32(5678); TestAllTypes message = builder.build(); ByteString data = message.toByteString(); - + TestOptionalFieldsOnly optionalOnlyMessage = TestOptionalFieldsOnly.parseFrom(data); // UnknownFieldSet should be empty. @@ -360,7 +360,7 @@ public class FieldPresenceTest extends TestCase { // The repeated field is discarded because it's unknown to the optional-only // message. assertEquals(0, message.getRepeatedInt32Count()); - + DynamicMessage dynamicOptionalOnlyMessage = DynamicMessage.getDefaultInstance( TestOptionalFieldsOnly.getDescriptor()) diff --git a/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java b/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java index 70812b95..8cd1f38d 100644 --- a/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java +++ b/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java @@ -620,6 +620,21 @@ public class GeneratedMessageTest extends TestCase { TestUtil.assertExtensionsClear(TestAllExtensions.newBuilder().build()); } + public void testUnsetRepeatedExtensionGetField() { + TestAllExtensions message = TestAllExtensions.getDefaultInstance(); + Object value; + + value = message.getField(UnittestProto.repeatedStringExtension.getDescriptor()); + assertTrue(value instanceof List); + assertTrue(((List<?>) value).isEmpty()); + assertIsUnmodifiable((List<?>) value); + + value = message.getField(UnittestProto.repeatedNestedMessageExtension.getDescriptor()); + assertTrue(value instanceof List); + assertTrue(((List<?>) value).isEmpty()); + assertIsUnmodifiable((List<?>) value); + } + public void testExtensionReflectionGetters() throws Exception { TestAllExtensions.Builder builder = TestAllExtensions.newBuilder(); TestUtil.setAllExtensions(builder); diff --git a/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java b/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java index 8751baae..756049b4 100644 --- a/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java +++ b/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java @@ -30,12 +30,18 @@ package com.google.protobuf; +import static com.google.protobuf.IsValidUtf8TestUtil.DIRECT_NIO_FACTORY; +import static com.google.protobuf.IsValidUtf8TestUtil.EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT; +import static com.google.protobuf.IsValidUtf8TestUtil.EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT; +import static com.google.protobuf.IsValidUtf8TestUtil.HEAP_NIO_FACTORY; +import static com.google.protobuf.IsValidUtf8TestUtil.LITERAL_FACTORY; +import static com.google.protobuf.IsValidUtf8TestUtil.testBytes; + +import com.google.protobuf.IsValidUtf8TestUtil.ByteStringFactory; import com.google.protobuf.IsValidUtf8TestUtil.Shard; import junit.framework.TestCase; -import java.io.UnsupportedEncodingException; - /** * Tests cases for {@link ByteString#isValidUtf8()}. This includes three * brute force tests that actually test every permutation of one byte, two byte, @@ -51,31 +57,33 @@ import java.io.UnsupportedEncodingException; * @author martinrb@google.com (Martin Buchholz) */ public class IsValidUtf8Test extends TestCase { - /** * Tests that round tripping of all two byte permutations work. */ - public void testIsValidUtf8_1Byte() throws UnsupportedEncodingException { - IsValidUtf8TestUtil.testBytes(1, - IsValidUtf8TestUtil.EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT); + public void testIsValidUtf8_1Byte() { + testBytes(LITERAL_FACTORY, 1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT); + testBytes(HEAP_NIO_FACTORY, 1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT); + testBytes(DIRECT_NIO_FACTORY, 1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT); } /** * Tests that round tripping of all two byte permutations work. */ - public void testIsValidUtf8_2Bytes() throws UnsupportedEncodingException { - IsValidUtf8TestUtil.testBytes(2, - IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT); + public void testIsValidUtf8_2Bytes() { + testBytes(LITERAL_FACTORY, 2, IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT); + testBytes(HEAP_NIO_FACTORY, 2, IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT); + testBytes(DIRECT_NIO_FACTORY, 2, IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT); } /** * Tests that round tripping of all three byte permutations work. */ - public void testIsValidUtf8_3Bytes() throws UnsupportedEncodingException { + public void testIsValidUtf8_3Bytes() { // Travis' OOM killer doesn't like this test if (System.getenv("TRAVIS") == null) { - IsValidUtf8TestUtil.testBytes(3, - IsValidUtf8TestUtil.EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT); + testBytes(LITERAL_FACTORY, 3, EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT); + testBytes(HEAP_NIO_FACTORY, 3, EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT); + testBytes(DIRECT_NIO_FACTORY, 3, EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT); } } @@ -85,8 +93,7 @@ public class IsValidUtf8Test extends TestCase { * {@link IsValidUtf8FourByteTest} is used for full coverage. This method * tests specific four-byte cases. */ - public void testIsValidUtf8_4BytesSamples() - throws UnsupportedEncodingException { + public void testIsValidUtf8_4BytesSamples() { // Valid 4 byte. assertValidUtf8(0xF0, 0xA4, 0xAD, 0xA2); @@ -119,9 +126,7 @@ public class IsValidUtf8Test extends TestCase { assertTrue(asBytes("\u024B62\u024B62").isValidUtf8()); // Mixed string - assertTrue( - asBytes("a\u020ac\u00a2b\\u024B62u020acc\u00a2de\u024B62") - .isValidUtf8()); + assertTrue(asBytes("a\u020ac\u00a2b\\u024B62u020acc\u00a2de\u024B62").isValidUtf8()); // Not a valid string assertInvalidUtf8(-1, 0, -1, 0); @@ -135,36 +140,35 @@ public class IsValidUtf8Test extends TestCase { return realBytes; } - private ByteString toByteString(int... bytes) { - return ByteString.copyFrom(toByteArray(bytes)); - } - - private void assertValidUtf8(int[] bytes, boolean not) { + private void assertValidUtf8(ByteStringFactory factory, int[] bytes, boolean not) { byte[] realBytes = toByteArray(bytes); assertTrue(not ^ Utf8.isValidUtf8(realBytes)); assertTrue(not ^ Utf8.isValidUtf8(realBytes, 0, bytes.length)); - ByteString lit = ByteString.copyFrom(realBytes); - ByteString sub = lit.substring(0, bytes.length); - assertTrue(not ^ lit.isValidUtf8()); + ByteString leaf = factory.newByteString(realBytes); + ByteString sub = leaf.substring(0, bytes.length); + assertTrue(not ^ leaf.isValidUtf8()); assertTrue(not ^ sub.isValidUtf8()); ByteString[] ropes = { - RopeByteString.newInstanceForTest(ByteString.EMPTY, lit), - RopeByteString.newInstanceForTest(ByteString.EMPTY, sub), - RopeByteString.newInstanceForTest(lit, ByteString.EMPTY), - RopeByteString.newInstanceForTest(sub, ByteString.EMPTY), - RopeByteString.newInstanceForTest(sub, lit) - }; + RopeByteString.newInstanceForTest(ByteString.EMPTY, leaf), + RopeByteString.newInstanceForTest(ByteString.EMPTY, sub), + RopeByteString.newInstanceForTest(leaf, ByteString.EMPTY), + RopeByteString.newInstanceForTest(sub, ByteString.EMPTY), + RopeByteString.newInstanceForTest(sub, leaf)}; for (ByteString rope : ropes) { assertTrue(not ^ rope.isValidUtf8()); } } private void assertValidUtf8(int... bytes) { - assertValidUtf8(bytes, false); + assertValidUtf8(LITERAL_FACTORY, bytes, false); + assertValidUtf8(HEAP_NIO_FACTORY, bytes, false); + assertValidUtf8(DIRECT_NIO_FACTORY, bytes, false); } private void assertInvalidUtf8(int... bytes) { - assertValidUtf8(bytes, true); + assertValidUtf8(LITERAL_FACTORY, bytes, true); + assertValidUtf8(HEAP_NIO_FACTORY, bytes, true); + assertValidUtf8(DIRECT_NIO_FACTORY, bytes, true); } private static ByteString asBytes(String s) { @@ -177,7 +181,6 @@ public class IsValidUtf8Test extends TestCase { for (Shard shard : IsValidUtf8TestUtil.FOUR_BYTE_SHARDS) { actual += shard.expected; } - assertEquals(IsValidUtf8TestUtil.EXPECTED_FOUR_BYTE_ROUNDTRIPPABLE_COUNT, - actual); + assertEquals(IsValidUtf8TestUtil.EXPECTED_FOUR_BYTE_ROUNDTRIPPABLE_COUNT, actual); } } diff --git a/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java b/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java index 321669f3..16a808bf 100644 --- a/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java +++ b/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java @@ -30,9 +30,13 @@ package com.google.protobuf; -import static junit.framework.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; -import java.io.UnsupportedEncodingException; +import java.lang.ref.SoftReference; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharsetDecoder; @@ -52,64 +56,105 @@ import java.util.logging.Logger; * @author jonp@google.com (Jon Perlow) * @author martinrb@google.com (Martin Buchholz) */ -class IsValidUtf8TestUtil { - private static Logger logger = Logger.getLogger( - IsValidUtf8TestUtil.class.getName()); +final class IsValidUtf8TestUtil { + private static Logger logger = Logger.getLogger(IsValidUtf8TestUtil.class.getName()); + + private IsValidUtf8TestUtil() {} + + static interface ByteStringFactory { + ByteString newByteString(byte[] bytes); + } + + static final ByteStringFactory LITERAL_FACTORY = new ByteStringFactory() { + @Override + public ByteString newByteString(byte[] bytes) { + return ByteString.wrap(bytes); + } + }; + + static final ByteStringFactory HEAP_NIO_FACTORY = new ByteStringFactory() { + @Override + public ByteString newByteString(byte[] bytes) { + return new NioByteString(ByteBuffer.wrap(bytes)); + } + }; + + private static ThreadLocal<SoftReference<ByteBuffer>> directBuffer = + new ThreadLocal<SoftReference<ByteBuffer>>(); + + /** + * Factory for direct {@link ByteBuffer} instances. To reduce direct memory usage, this + * uses a thread local direct buffer. This means that each call will overwrite the buffer's + * contents from the previous call, so the calling code must be careful not to continue using + * a buffer returned from a previous invocation. + */ + static final ByteStringFactory DIRECT_NIO_FACTORY = new ByteStringFactory() { + @Override + public ByteString newByteString(byte[] bytes) { + SoftReference<ByteBuffer> ref = directBuffer.get(); + ByteBuffer buffer = ref == null ? null : ref.get(); + if (buffer == null || buffer.capacity() < bytes.length) { + buffer = ByteBuffer.allocateDirect(bytes.length); + directBuffer.set(new SoftReference<ByteBuffer>(buffer)); + } + buffer.clear(); + buffer.put(bytes); + buffer.flip(); + return new NioByteString(buffer); + } + }; // 128 - [chars 0x0000 to 0x007f] - static long ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x007f - 0x0000 + 1; + static final long ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x007f - 0x0000 + 1; // 128 - static long EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT = - ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS; + static final long EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT = ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS; // 1920 [chars 0x0080 to 0x07FF] - static long TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x07FF - 0x0080 + 1; + static final long TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x07FF - 0x0080 + 1; // 18,304 - static long EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT = + static final long EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT = // Both bytes are one byte characters (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 2) + // The possible number of two byte characters TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS; // 2048 - static long THREE_BYTE_SURROGATES = 2 * 1024; + static final long THREE_BYTE_SURROGATES = 2 * 1024; // 61,440 [chars 0x0800 to 0xFFFF, minus surrogates] - static long THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS = + static final long THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0xFFFF - 0x0800 + 1 - THREE_BYTE_SURROGATES; // 2,650,112 - static long EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT = + static final long EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT = // All one byte characters (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 3) + // One two byte character and a one byte character - 2 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * - ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + - // Three byte characters + 2 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + + // Three byte characters THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS; // 1,048,576 [chars 0x10000L to 0x10FFFF] - static long FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x10FFFF - 0x10000L + 1; + static final long FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x10FFFF - 0x10000L + 1; // 289,571,839 - static long EXPECTED_FOUR_BYTE_ROUNDTRIPPABLE_COUNT = + static final long EXPECTED_FOUR_BYTE_ROUNDTRIPPABLE_COUNT = // All one byte characters (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 4) + // One and three byte characters - 2 * THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS * - ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + + 2 * THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + // Two two byte characters TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS + // Permutations of one and two byte characters - 3 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * - ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS * - ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + + 3 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + + // Four byte characters FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS; - static class Shard { + static final class Shard { final long index; final long start; final long lim; @@ -138,7 +183,7 @@ class IsValidUtf8TestUtil { // 97-111 are all 2342912 for (int i = 97; i <= 111; i++) { - expected[i] = 2342912; + expected[i] = 2342912; } // 113-117 are all 1048576 @@ -158,22 +203,18 @@ class IsValidUtf8TestUtil { return expected; } - static final List<Shard> FOUR_BYTE_SHARDS = generateFourByteShards( - 128, FOUR_BYTE_SHARDS_EXPECTED_ROUNTRIPPABLES); + static final List<Shard> FOUR_BYTE_SHARDS = + generateFourByteShards(128, FOUR_BYTE_SHARDS_EXPECTED_ROUNTRIPPABLES); - private static List<Shard> generateFourByteShards( - int numShards, long[] expected) { + private static List<Shard> generateFourByteShards(int numShards, long[] expected) { assertEquals(numShards, expected.length); List<Shard> shards = new ArrayList<Shard>(numShards); long LIM = 1L << 32; long increment = LIM / numShards; assertTrue(LIM % numShards == 0); for (int i = 0; i < numShards; i++) { - shards.add(new Shard(i, - increment * i, - increment * (i + 1), - expected[i])); + shards.add(new Shard(i, increment * i, increment * (i + 1), expected[i])); } return shards; } @@ -182,12 +223,12 @@ class IsValidUtf8TestUtil { * Helper to run the loop to test all the permutations for the number of bytes * specified. * + * @param factory the factory for {@link ByteString} instances. * @param numBytes the number of bytes in the byte array * @param expectedCount the expected number of roundtrippable permutations */ - static void testBytes(int numBytes, long expectedCount) - throws UnsupportedEncodingException { - testBytes(numBytes, expectedCount, 0, -1); + static void testBytes(ByteStringFactory factory, int numBytes, long expectedCount) { + testBytes(factory, numBytes, expectedCount, 0, -1); } /** @@ -195,14 +236,15 @@ class IsValidUtf8TestUtil { * specified. This overload is useful for debugging to get the loop to start * at a certain character. * + * @param factory the factory for {@link ByteString} instances. * @param numBytes the number of bytes in the byte array * @param expectedCount the expected number of roundtrippable permutations * @param start the starting bytes encoded as a long as big-endian * @param lim the limit of bytes to process encoded as a long as big-endian, * or -1 to mean the max limit for numBytes */ - static void testBytes(int numBytes, long expectedCount, long start, long lim) - throws UnsupportedEncodingException { + static void testBytes( + ByteStringFactory factory, int numBytes, long expectedCount, long start, long lim) { Random rnd = new Random(); byte[] bytes = new byte[numBytes]; @@ -217,7 +259,7 @@ class IsValidUtf8TestUtil { bytes[bytes.length - i - 1] = (byte) tmpByteChar; tmpByteChar = tmpByteChar >> 8; } - ByteString bs = ByteString.copyFrom(bytes); + ByteString bs = factory.newByteString(bytes); boolean isRoundTrippable = bs.isValidUtf8(); String s = new String(bytes, Internal.UTF_8); byte[] bytesReencoded = s.getBytes(Internal.UTF_8); @@ -236,14 +278,15 @@ class IsValidUtf8TestUtil { int i = rnd.nextInt(numBytes); int j = rnd.nextInt(numBytes); if (j < i) { - int tmp = i; i = j; j = tmp; + int tmp = i; + i = j; + j = tmp; } int state1 = Utf8.partialIsValidUtf8(Utf8.COMPLETE, bytes, 0, i); int state2 = Utf8.partialIsValidUtf8(state1, bytes, i, j); int state3 = Utf8.partialIsValidUtf8(state2, bytes, j, numBytes); if (isRoundTrippable != (state3 == Utf8.COMPLETE)) { - System.out.printf("state=%04x %04x %04x i=%d j=%d%n", - state1, state2, state3, i, j); + System.out.printf("state=%04x %04x %04x i=%d j=%d%n", state1, state2, state3, i, j); outputFailure(byteChar, bytes, bytesReencoded); } assertEquals(isRoundTrippable, (state3 == Utf8.COMPLETE)); @@ -251,36 +294,24 @@ class IsValidUtf8TestUtil { // Test ropes built out of small partial sequences ByteString rope = RopeByteString.newInstanceForTest( bs.substring(0, i), - RopeByteString.newInstanceForTest( - bs.substring(i, j), - bs.substring(j, numBytes))); + RopeByteString.newInstanceForTest(bs.substring(i, j), bs.substring(j, numBytes))); assertSame(RopeByteString.class, rope.getClass()); - ByteString[] byteStrings = { bs, bs.substring(0, numBytes), rope }; + ByteString[] byteStrings = {bs, bs.substring(0, numBytes), rope}; for (ByteString x : byteStrings) { - assertEquals(isRoundTrippable, - x.isValidUtf8()); - assertEquals(state3, - x.partialIsValidUtf8(Utf8.COMPLETE, 0, numBytes)); - - assertEquals(state1, - x.partialIsValidUtf8(Utf8.COMPLETE, 0, i)); - assertEquals(state1, - x.substring(0, i).partialIsValidUtf8(Utf8.COMPLETE, 0, i)); - assertEquals(state2, - x.partialIsValidUtf8(state1, i, j - i)); - assertEquals(state2, - x.substring(i, j).partialIsValidUtf8(state1, 0, j - i)); - assertEquals(state3, - x.partialIsValidUtf8(state2, j, numBytes - j)); - assertEquals(state3, - x.substring(j, numBytes) - .partialIsValidUtf8(state2, 0, numBytes - j)); + assertEquals(isRoundTrippable, x.isValidUtf8()); + assertEquals(state3, x.partialIsValidUtf8(Utf8.COMPLETE, 0, numBytes)); + + assertEquals(state1, x.partialIsValidUtf8(Utf8.COMPLETE, 0, i)); + assertEquals(state1, x.substring(0, i).partialIsValidUtf8(Utf8.COMPLETE, 0, i)); + assertEquals(state2, x.partialIsValidUtf8(state1, i, j - i)); + assertEquals(state2, x.substring(i, j).partialIsValidUtf8(state1, 0, j - i)); + assertEquals(state3, x.partialIsValidUtf8(state2, j, numBytes - j)); + assertEquals(state3, x.substring(j, numBytes).partialIsValidUtf8(state2, 0, numBytes - j)); } // ByteString reduplication should not affect its UTF-8 validity. - ByteString ropeADope = - RopeByteString.newInstanceForTest(bs, bs.substring(0, numBytes)); + ByteString ropeADope = RopeByteString.newInstanceForTest(bs, bs.substring(0, numBytes)); assertEquals(isRoundTrippable, ropeADope.isValidUtf8()); if (isRoundTrippable) { @@ -288,8 +319,7 @@ class IsValidUtf8TestUtil { } count++; if (byteChar != 0 && byteChar % 1000000L == 0) { - logger.info("Processed " + (byteChar / 1000000L) + - " million characters"); + logger.info("Processed " + (byteChar / 1000000L) + " million characters"); } } logger.info("Round tripped " + countRoundTripped + " of " + count); @@ -303,25 +333,26 @@ class IsValidUtf8TestUtil { * actual String class, it's possible for incompatibilities to develop * (although unlikely). * + * @param factory the factory for {@link ByteString} instances. * @param numBytes the number of bytes in the byte array * @param expectedCount the expected number of roundtrippable permutations * @param start the starting bytes encoded as a long as big-endian * @param lim the limit of bytes to process encoded as a long as big-endian, * or -1 to mean the max limit for numBytes */ - void testBytesUsingByteBuffers( - int numBytes, long expectedCount, long start, long lim) - throws UnsupportedEncodingException { - CharsetDecoder decoder = Internal.UTF_8.newDecoder() - .onMalformedInput(CodingErrorAction.REPLACE) - .onUnmappableCharacter(CodingErrorAction.REPLACE); - CharsetEncoder encoder = Internal.UTF_8.newEncoder() - .onMalformedInput(CodingErrorAction.REPLACE) - .onUnmappableCharacter(CodingErrorAction.REPLACE); + static void testBytesUsingByteBuffers( + ByteStringFactory factory, int numBytes, long expectedCount, long start, long lim) { + CharsetDecoder decoder = + Internal.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE); + CharsetEncoder encoder = + Internal.UTF_8.newEncoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE); byte[] bytes = new byte[numBytes]; int maxChars = (int) (decoder.maxCharsPerByte() * numBytes) + 1; - char[] charsDecoded = - new char[(int) (decoder.maxCharsPerByte() * numBytes) + 1]; + char[] charsDecoded = new char[(int) (decoder.maxCharsPerByte() * numBytes) + 1]; int maxBytes = (int) (encoder.maxBytesPerChar() * maxChars) + 1; byte[] bytesReencoded = new byte[maxBytes]; @@ -347,7 +378,7 @@ class IsValidUtf8TestUtil { bytes[bytes.length - i - 1] = (byte) tmpByteChar; tmpByteChar = tmpByteChar >> 8; } - boolean isRoundTrippable = ByteString.copyFrom(bytes).isValidUtf8(); + boolean isRoundTrippable = factory.newByteString(bytes).isValidUtf8(); CoderResult result = decoder.decode(bb, cb, true); assertFalse(result.isError()); result = decoder.flush(cb); @@ -382,8 +413,7 @@ class IsValidUtf8TestUtil { countRoundTripped++; } if (byteChar != 0 && byteChar % 1000000 == 0) { - logger.info("Processed " + (byteChar / 1000000) + - " million characters"); + logger.info("Processed " + (byteChar / 1000000) + " million characters"); } } logger.info("Round tripped " + countRoundTripped + " of " + count); @@ -394,10 +424,9 @@ class IsValidUtf8TestUtil { outputFailure(byteChar, bytes, after, after.length); } - private static void outputFailure(long byteChar, byte[] bytes, byte[] after, - int len) { - fail("Failure: (" + Long.toHexString(byteChar) + ") " + - toHexString(bytes) + " => " + toHexString(after, len)); + private static void outputFailure(long byteChar, byte[] bytes, byte[] after, int len) { + fail("Failure: (" + Long.toHexString(byteChar) + ") " + toHexString(bytes) + " => " + + toHexString(after, len)); } private static String toHexString(byte[] b) { @@ -416,5 +445,4 @@ class IsValidUtf8TestUtil { s.append("\""); return s.toString(); } - } diff --git a/java/core/src/test/java/com/google/protobuf/LazyFieldLiteTest.java b/java/core/src/test/java/com/google/protobuf/LazyFieldLiteTest.java index 211b5697..8d1de6dc 100644 --- a/java/core/src/test/java/com/google/protobuf/LazyFieldLiteTest.java +++ b/java/core/src/test/java/com/google/protobuf/LazyFieldLiteTest.java @@ -36,9 +36,10 @@ import static protobuf_unittest.UnittestProto.optionalInt64Extension; import protobuf_unittest.UnittestProto.TestAllExtensions; import protobuf_unittest.UnittestProto.TestAllTypes; -import java.io.IOException; import junit.framework.TestCase; +import java.io.IOException; + /** * Unit test for {@link LazyFieldLite}. * diff --git a/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java b/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java index 2b900065..ce473ae9 100644 --- a/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java +++ b/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java @@ -33,9 +33,10 @@ package com.google.protobuf; import protobuf_unittest.UnittestProto.TestAllExtensions; import protobuf_unittest.UnittestProto.TestAllTypes; -import java.io.IOException; import junit.framework.TestCase; +import java.io.IOException; + /** * Unit test for {@link LazyField}. * diff --git a/java/core/src/test/java/com/google/protobuf/LiteEqualsAndHashTest.java b/java/core/src/test/java/com/google/protobuf/LiteEqualsAndHashTest.java index 035917c8..29e8d875 100644 --- a/java/core/src/test/java/com/google/protobuf/LiteEqualsAndHashTest.java +++ b/java/core/src/test/java/com/google/protobuf/LiteEqualsAndHashTest.java @@ -33,6 +33,8 @@ package com.google.protobuf; import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.Bar; import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.BarPrime; import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.Foo; +import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.TestOneofEquals; +import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.TestRecursiveOneof; import junit.framework.TestCase; @@ -83,6 +85,16 @@ public class LiteEqualsAndHashTest extends TestCase { assertFalse(bar.equals(barPrime)); } + public void testOneofEquals() throws Exception { + TestOneofEquals.Builder builder = TestOneofEquals.newBuilder(); + TestOneofEquals message1 = builder.build(); + // Set message2's name field to default value. The two messages should be different when we + // check with the oneof case. + builder.setName(""); + TestOneofEquals message2 = builder.build(); + assertFalse(message1.equals(message2)); + } + public void testEqualsAndHashCodeWithUnknownFields() throws InvalidProtocolBufferException { Foo fooWithOnlyValue = Foo.newBuilder() .setValue(1) @@ -105,4 +117,9 @@ public class LiteEqualsAndHashTest extends TestCase { assertFalse(o1.equals(o2)); assertFalse(o1.hashCode() == o2.hashCode()); } + + public void testRecursiveHashcode() { + // This tests that we don't infinite loop. + TestRecursiveOneof.getDefaultInstance().hashCode(); + } } diff --git a/java/core/src/test/java/com/google/protobuf/LiteTest.java b/java/core/src/test/java/com/google/protobuf/LiteTest.java index b1f298ff..9e503cc3 100644 --- a/java/core/src/test/java/com/google/protobuf/LiteTest.java +++ b/java/core/src/test/java/com/google/protobuf/LiteTest.java @@ -49,6 +49,7 @@ import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.NotSerializableException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -128,33 +129,7 @@ public class LiteTest extends TestCase { assertEquals(7, message2.getExtension( UnittestLite.optionalNestedMessageExtensionLite).getBb()); } - - public void testSerialize() throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - TestAllTypesLite expected = - TestAllTypesLite.newBuilder() - .setOptionalInt32(123) - .addRepeatedString("hello") - .setOptionalNestedMessage( - TestAllTypesLite.NestedMessage.newBuilder().setBb(7)) - .build(); - ObjectOutputStream out = new ObjectOutputStream(baos); - try { - out.writeObject(expected); - } finally { - out.close(); - } - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - ObjectInputStream in = new ObjectInputStream(bais); - TestAllTypesLite actual = (TestAllTypesLite) in.readObject(); - assertEquals(expected.getOptionalInt32(), actual.getOptionalInt32()); - assertEquals(expected.getRepeatedStringCount(), - actual.getRepeatedStringCount()); - assertEquals(expected.getRepeatedString(0), - actual.getRepeatedString(0)); - assertEquals(expected.getOptionalNestedMessage().getBb(), - actual.getOptionalNestedMessage().getBb()); - } + public void testClone() { TestAllTypesLite.Builder expected = TestAllTypesLite.newBuilder() @@ -1459,4 +1434,168 @@ public class LiteTest extends TestCase { 11, (int) extendableMessage.getExtension( UnittestLite.optionalFixed32ExtensionLite)); } + + public void testToStringDefaultInstance() throws Exception { + assertToStringEquals("", TestAllTypesLite.getDefaultInstance()); + } + + public void testToStringPrimitives() throws Exception { + TestAllTypesLite proto = TestAllTypesLite.newBuilder() + .setOptionalInt32(1) + .setOptionalInt64(9223372036854775807L) + .build(); + assertToStringEquals("optional_int32: 1\noptional_int64: 9223372036854775807", proto); + + proto = TestAllTypesLite.newBuilder() + .setOptionalBool(true) + .setOptionalNestedEnum(TestAllTypesLite.NestedEnum.BAZ) + .build(); + assertToStringEquals("optional_bool: true\noptional_nested_enum: BAZ", proto); + + proto = TestAllTypesLite.newBuilder() + .setOptionalFloat(2.72f) + .setOptionalDouble(3.14) + .build(); + assertToStringEquals("optional_float: 2.72\noptional_double: 3.14", proto); + } + + public void testToStringStringFields() throws Exception { + TestAllTypesLite proto = TestAllTypesLite.newBuilder() + .setOptionalString("foo\"bar\nbaz\\") + .build(); + assertToStringEquals("optional_string: \"foo\\\"bar\\nbaz\\\\\"", proto); + + proto = TestAllTypesLite.newBuilder() + .setOptionalString("\u6587") + .build(); + assertToStringEquals("optional_string: \"\\346\\226\\207\"", proto); + } + + public void testToStringNestedMessage() throws Exception { + TestAllTypesLite proto = TestAllTypesLite.newBuilder() + .setOptionalNestedMessage(TestAllTypesLite.NestedMessage.getDefaultInstance()) + .build(); + assertToStringEquals("optional_nested_message {\n}", proto); + + proto = TestAllTypesLite.newBuilder() + .setOptionalNestedMessage( + TestAllTypesLite.NestedMessage.newBuilder().setBb(7)) + .build(); + assertToStringEquals("optional_nested_message {\n bb: 7\n}", proto); + } + + public void testToStringRepeatedFields() throws Exception { + TestAllTypesLite proto = TestAllTypesLite.newBuilder() + .addRepeatedInt32(32) + .addRepeatedInt32(32) + .addRepeatedInt64(64) + .build(); + assertToStringEquals("repeated_int32: 32\nrepeated_int32: 32\nrepeated_int64: 64", proto); + + proto = TestAllTypesLite.newBuilder() + .addRepeatedLazyMessage( + TestAllTypesLite.NestedMessage.newBuilder().setBb(7)) + .addRepeatedLazyMessage( + TestAllTypesLite.NestedMessage.newBuilder().setBb(8)) + .build(); + assertToStringEquals( + "repeated_lazy_message {\n bb: 7\n}\nrepeated_lazy_message {\n bb: 8\n}", + proto); + } + + public void testToStringForeignFields() throws Exception { + TestAllTypesLite proto = TestAllTypesLite.newBuilder() + .setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR) + .setOptionalForeignMessage( + ForeignMessageLite.newBuilder() + .setC(3)) + .build(); + assertToStringEquals( + "optional_foreign_message {\n c: 3\n}\noptional_foreign_enum: FOREIGN_LITE_BAR", + proto); + } + + public void testToStringExtensions() throws Exception { + TestAllExtensionsLite message = TestAllExtensionsLite.newBuilder() + .setExtension(UnittestLite.optionalInt32ExtensionLite, 123) + .addExtension(UnittestLite.repeatedStringExtensionLite, "spam") + .addExtension(UnittestLite.repeatedStringExtensionLite, "eggs") + .setExtension(UnittestLite.optionalNestedEnumExtensionLite, + TestAllTypesLite.NestedEnum.BAZ) + .setExtension(UnittestLite.optionalNestedMessageExtensionLite, + TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build()) + .build(); + assertToStringEquals( + "[1]: 123\n[18] {\n bb: 7\n}\n[21]: 3\n[44]: \"spam\"\n[44]: \"eggs\"", + message); + } + + public void testToStringUnknownFields() throws Exception { + TestAllExtensionsLite messageWithExtensions = TestAllExtensionsLite.newBuilder() + .setExtension(UnittestLite.optionalInt32ExtensionLite, 123) + .addExtension(UnittestLite.repeatedStringExtensionLite, "spam") + .addExtension(UnittestLite.repeatedStringExtensionLite, "eggs") + .setExtension(UnittestLite.optionalNestedEnumExtensionLite, + TestAllTypesLite.NestedEnum.BAZ) + .setExtension(UnittestLite.optionalNestedMessageExtensionLite, + TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build()) + .build(); + TestAllExtensionsLite messageWithUnknownFields = TestAllExtensionsLite.parseFrom( + messageWithExtensions.toByteArray()); + assertToStringEquals( + "1: 123\n18: \"\\b\\a\"\n21: 3\n44: \"spam\"\n44: \"eggs\"", + messageWithUnknownFields); + } + + // Asserts that the toString() representation of the message matches the expected. This verifies + // the first line starts with a comment; but, does not factor in said comment as part of the + // comparison as it contains unstable addresses. + private static void assertToStringEquals(String expected, MessageLite message) { + String toString = message.toString(); + assertEquals('#', toString.charAt(0)); + if (toString.indexOf("\n") >= 0) { + toString = toString.substring(toString.indexOf("\n") + 1); + } else { + toString = ""; + } + assertEquals(expected, toString); + } + + public void testParseLazy() throws Exception { + ByteString bb = TestAllTypesLite.newBuilder() + .setOptionalLazyMessage(NestedMessage.newBuilder() + .setBb(11) + .build()) + .build().toByteString(); + ByteString cc = TestAllTypesLite.newBuilder() + .setOptionalLazyMessage(NestedMessage.newBuilder() + .setCc(22) + .build()) + .build().toByteString(); + + ByteString concat = bb.concat(cc); + TestAllTypesLite message = TestAllTypesLite.parseFrom(concat); + + assertEquals(11, message.getOptionalLazyMessage().getBb()); + assertEquals(22L, message.getOptionalLazyMessage().getCc()); + } + + public void testParseLazy_oneOf() throws Exception { + ByteString bb = TestAllTypesLite.newBuilder() + .setOneofLazyNestedMessage(NestedMessage.newBuilder() + .setBb(11) + .build()) + .build().toByteString(); + ByteString cc = TestAllTypesLite.newBuilder() + .setOneofLazyNestedMessage(NestedMessage.newBuilder() + .setCc(22) + .build()) + .build().toByteString(); + + ByteString concat = bb.concat(cc); + TestAllTypesLite message = TestAllTypesLite.parseFrom(concat); + + assertEquals(11, message.getOneofLazyNestedMessage().getBb()); + assertEquals(22L, message.getOneofLazyNestedMessage().getCc()); + } } diff --git a/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java b/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java index 68b55ceb..2e7792a8 100644 --- a/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java +++ b/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java @@ -47,9 +47,9 @@ import java.util.List; import java.util.NoSuchElementException; /** - * Test {@link LiteralByteString} by setting up a reference string in {@link #setUp()}. - * This class is designed to be extended for testing extensions of {@link LiteralByteString} - * such as {@link BoundedByteString}, see {@link BoundedByteStringTest}. + * Test {@code LiteralByteString} by setting up a reference string in {@link #setUp()}. + * This class is designed to be extended for testing extensions of {@code LiteralByteString} + * such as {@code BoundedByteString}, see {@link BoundedByteStringTest}. * * @author carlanton@google.com (Carl Haverl) */ @@ -304,25 +304,75 @@ public class LiteralByteStringTest extends TestCase { Arrays.equals(referenceBytes, roundTripBytes)); } - public void testWriteTo_mutating() throws IOException { + public void testWriteToShouldNotExposeInternalBufferToOutputStream() throws IOException { OutputStream os = new OutputStream() { @Override public void write(byte[] b, int off, int len) { - for (int x = 0; x < len; ++x) { - b[off + x] = (byte) 0; - } + Arrays.fill(b, off, off + len, (byte) 0); } @Override public void write(int b) { - // Purposefully left blank. + throw new UnsupportedOperationException(); } }; stringUnderTest.writeTo(os); - byte[] newBytes = stringUnderTest.toByteArray(); assertTrue(classUnderTest + ".writeTo() must not grant access to underlying array", - Arrays.equals(referenceBytes, newBytes)); + Arrays.equals(referenceBytes, stringUnderTest.toByteArray())); + } + + public void testWriteToInternalShouldExposeInternalBufferToOutputStream() throws IOException { + OutputStream os = new OutputStream() { + @Override + public void write(byte[] b, int off, int len) { + Arrays.fill(b, off, off + len, (byte) 0); + } + + @Override + public void write(int b) { + throw new UnsupportedOperationException(); + } + }; + + stringUnderTest.writeToInternal(os, 0, stringUnderTest.size()); + byte[] allZeros = new byte[stringUnderTest.size()]; + assertTrue(classUnderTest + ".writeToInternal() must grant access to underlying array", + Arrays.equals(allZeros, stringUnderTest.toByteArray())); + } + + public void testWriteToShouldExposeInternalBufferToByteOutput() throws IOException { + ByteOutput out = new ByteOutput() { + @Override + public void write(byte value) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void write(byte[] value, int offset, int length) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void writeLazy(byte[] value, int offset, int length) throws IOException { + Arrays.fill(value, offset, offset + length, (byte) 0); + } + + @Override + public void write(ByteBuffer value) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void writeLazy(ByteBuffer value) throws IOException { + throw new UnsupportedOperationException(); + } + }; + + stringUnderTest.writeTo(out); + byte[] allZeros = new byte[stringUnderTest.size()]; + assertTrue(classUnderTest + ".writeToInternal() must grant access to underlying array", + Arrays.equals(allZeros, stringUnderTest.toByteArray())); } public void testNewOutput() throws IOException { diff --git a/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java b/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java index 3d8c9bc4..d79d0029 100644 --- a/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java +++ b/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java @@ -432,7 +432,7 @@ public class MapForProto2LiteTest extends TestCase { assertEquals(1, messageWithUnknownEnums.getInt32ToInt32Field().get(1).intValue()); assertEquals(54321, messageWithUnknownEnums.getInt32ToInt32Field().get(2).intValue()); } - + public void testIterationOrder() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); diff --git a/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java b/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java index 1fa3cbdb..73154c0f 100644 --- a/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java +++ b/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java @@ -36,7 +36,6 @@ import map_test.MapForProto2TestProto.TestMap.MessageValue; import map_test.MapForProto2TestProto.TestMap.MessageWithRequiredFields; import map_test.MapForProto2TestProto.TestRecursiveMap; import map_test.MapForProto2TestProto.TestUnknownEnumValue; - import junit.framework.TestCase; import java.util.ArrayList; diff --git a/java/core/src/test/java/com/google/protobuf/MapTest.java b/java/core/src/test/java/com/google/protobuf/MapTest.java index 0e5c1284..1dc5787d 100644 --- a/java/core/src/test/java/com/google/protobuf/MapTest.java +++ b/java/core/src/test/java/com/google/protobuf/MapTest.java @@ -37,7 +37,6 @@ import com.google.protobuf.Descriptors.FieldDescriptor; import map_test.MapTestProto.TestMap; import map_test.MapTestProto.TestMap.MessageValue; import map_test.MapTestProto.TestOnChangeEventPropagation; - import junit.framework.TestCase; import java.util.ArrayList; diff --git a/java/core/src/test/java/com/google/protobuf/MessageTest.java b/java/core/src/test/java/com/google/protobuf/MessageTest.java index abcd3a1d..dcd1aba7 100644 --- a/java/core/src/test/java/com/google/protobuf/MessageTest.java +++ b/java/core/src/test/java/com/google/protobuf/MessageTest.java @@ -30,11 +30,11 @@ package com.google.protobuf; -import protobuf_unittest.UnittestProto.TestAllTypes; +import protobuf_unittest.UnittestProto.ForeignMessage; import protobuf_unittest.UnittestProto.TestAllExtensions; +import protobuf_unittest.UnittestProto.TestAllTypes; import protobuf_unittest.UnittestProto.TestRequired; import protobuf_unittest.UnittestProto.TestRequiredForeign; -import protobuf_unittest.UnittestProto.ForeignMessage; import junit.framework.TestCase; diff --git a/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java b/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java index 23653126..542e28c0 100644 --- a/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java +++ b/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java @@ -35,8 +35,8 @@ import protobuf_unittest.Wheel; import junit.framework.TestCase; -import java.util.List; import java.util.ArrayList; +import java.util.List; /** * Test cases that exercise end-to-end use cases involving diff --git a/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java b/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java index e40a3662..6be5b93c 100644 --- a/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java +++ b/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java @@ -41,6 +41,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; @@ -56,11 +57,12 @@ public class NioByteStringTest extends TestCase { private static final String CLASSNAME = NioByteString.class.getSimpleName(); private static final byte[] BYTES = ByteStringTest.getTestBytes(1234, 11337766L); private static final int EXPECTED_HASH = ByteString.wrap(BYTES).hashCode(); - private static final ByteBuffer BUFFER = ByteBuffer.wrap(BYTES.clone()); - private static final ByteString TEST_STRING = new NioByteString(BUFFER); + + private final ByteBuffer backingBuffer = ByteBuffer.wrap(BYTES.clone()); + private final ByteString testString = new NioByteString(backingBuffer); public void testExpectedType() { - String actualClassName = getActualClassName(TEST_STRING); + String actualClassName = getActualClassName(testString); assertEquals(CLASSNAME + " should match type exactly", CLASSNAME, actualClassName); } @@ -73,14 +75,14 @@ public class NioByteStringTest extends TestCase { public void testByteAt() { boolean stillEqual = true; for (int i = 0; stillEqual && i < BYTES.length; ++i) { - stillEqual = (BYTES[i] == TEST_STRING.byteAt(i)); + stillEqual = (BYTES[i] == testString.byteAt(i)); } assertTrue(CLASSNAME + " must capture the right bytes", stillEqual); } public void testByteIterator() { boolean stillEqual = true; - ByteString.ByteIterator iter = TEST_STRING.iterator(); + ByteString.ByteIterator iter = testString.iterator(); for (int i = 0; stillEqual && i < BYTES.length; ++i) { stillEqual = (iter.hasNext() && BYTES[i] == iter.nextByte()); } @@ -98,7 +100,7 @@ public class NioByteStringTest extends TestCase { public void testByteIterable() { boolean stillEqual = true; int j = 0; - for (byte quantum : TEST_STRING) { + for (byte quantum : testString) { stillEqual = (BYTES[j] == quantum); ++j; } @@ -108,15 +110,15 @@ public class NioByteStringTest extends TestCase { public void testSize() { assertEquals(CLASSNAME + " must have the expected size", BYTES.length, - TEST_STRING.size()); + testString.size()); } public void testGetTreeDepth() { - assertEquals(CLASSNAME + " must have depth 0", 0, TEST_STRING.getTreeDepth()); + assertEquals(CLASSNAME + " must have depth 0", 0, testString.getTreeDepth()); } public void testIsBalanced() { - assertTrue(CLASSNAME + " is technically balanced", TEST_STRING.isBalanced()); + assertTrue(CLASSNAME + " is technically balanced", testString.isBalanced()); } public void testCopyTo_ByteArrayOffsetLength() { @@ -124,7 +126,7 @@ public class NioByteStringTest extends TestCase { int length = 100; byte[] destination = new byte[destinationOffset + length]; int sourceOffset = 213; - TEST_STRING.copyTo(destination, sourceOffset, destinationOffset, length); + testString.copyTo(destination, sourceOffset, destinationOffset, length); boolean stillEqual = true; for (int i = 0; stillEqual && i < length; ++i) { stillEqual = BYTES[i + sourceOffset] == destination[i + destinationOffset]; @@ -139,7 +141,7 @@ public class NioByteStringTest extends TestCase { try { // Copy one too many bytes - TEST_STRING.copyTo(destination, TEST_STRING.size() + 1 - length, + testString.copyTo(destination, testString.size() + 1 - length, destinationOffset, length); fail("Should have thrown an exception when copying too many bytes of a " + CLASSNAME); @@ -149,7 +151,7 @@ public class NioByteStringTest extends TestCase { try { // Copy with illegal negative sourceOffset - TEST_STRING.copyTo(destination, -1, destinationOffset, length); + testString.copyTo(destination, -1, destinationOffset, length); fail("Should have thrown an exception when given a negative sourceOffset in " + CLASSNAME); } catch (IndexOutOfBoundsException expected) { @@ -158,7 +160,7 @@ public class NioByteStringTest extends TestCase { try { // Copy with illegal negative destinationOffset - TEST_STRING.copyTo(destination, 0, -1, length); + testString.copyTo(destination, 0, -1, length); fail("Should have thrown an exception when given a negative destinationOffset in " + CLASSNAME); } catch (IndexOutOfBoundsException expected) { @@ -167,7 +169,7 @@ public class NioByteStringTest extends TestCase { try { // Copy with illegal negative size - TEST_STRING.copyTo(destination, 0, 0, -1); + testString.copyTo(destination, 0, 0, -1); fail("Should have thrown an exception when given a negative size in " + CLASSNAME); } catch (IndexOutOfBoundsException expected) { @@ -176,7 +178,7 @@ public class NioByteStringTest extends TestCase { try { // Copy with illegal too-large sourceOffset - TEST_STRING.copyTo(destination, 2 * TEST_STRING.size(), 0, length); + testString.copyTo(destination, 2 * testString.size(), 0, length); fail("Should have thrown an exception when the destinationOffset is too large in " + CLASSNAME); } catch (IndexOutOfBoundsException expected) { @@ -185,7 +187,7 @@ public class NioByteStringTest extends TestCase { try { // Copy with illegal too-large destinationOffset - TEST_STRING.copyTo(destination, 0, 2 * destination.length, length); + testString.copyTo(destination, 0, 2 * destination.length, length); fail("Should have thrown an exception when the destinationOffset is too large in " + CLASSNAME); } catch (IndexOutOfBoundsException expected) { @@ -196,21 +198,21 @@ public class NioByteStringTest extends TestCase { public void testCopyTo_ByteBuffer() { // Same length. ByteBuffer myBuffer = ByteBuffer.allocate(BYTES.length); - TEST_STRING.copyTo(myBuffer); + testString.copyTo(myBuffer); myBuffer.flip(); assertEquals(CLASSNAME + ".copyTo(ByteBuffer) must give back the same bytes", - BUFFER, myBuffer); + backingBuffer, myBuffer); // Target buffer bigger than required. - myBuffer = ByteBuffer.allocate(TEST_STRING.size() + 1); - TEST_STRING.copyTo(myBuffer); + myBuffer = ByteBuffer.allocate(testString.size() + 1); + testString.copyTo(myBuffer); myBuffer.flip(); - assertEquals(BUFFER, myBuffer); + assertEquals(backingBuffer, myBuffer); // Target buffer has no space. myBuffer = ByteBuffer.allocate(0); try { - TEST_STRING.copyTo(myBuffer); + testString.copyTo(myBuffer); fail("Should have thrown an exception when target ByteBuffer has insufficient capacity"); } catch (BufferOverflowException e) { // Expected. @@ -219,7 +221,7 @@ public class NioByteStringTest extends TestCase { // Target buffer too small. myBuffer = ByteBuffer.allocate(1); try { - TEST_STRING.copyTo(myBuffer); + testString.copyTo(myBuffer); fail("Should have thrown an exception when target ByteBuffer has insufficient capacity"); } catch (BufferOverflowException e) { // Expected. @@ -227,26 +229,26 @@ public class NioByteStringTest extends TestCase { } public void testMarkSupported() { - InputStream stream = TEST_STRING.newInput(); + InputStream stream = testString.newInput(); assertTrue(CLASSNAME + ".newInput() must support marking", stream.markSupported()); } public void testMarkAndReset() throws IOException { - int fraction = TEST_STRING.size() / 3; + int fraction = testString.size() / 3; - InputStream stream = TEST_STRING.newInput(); - stream.mark(TEST_STRING.size()); // First, mark() the end. + InputStream stream = testString.newInput(); + stream.mark(testString.size()); // First, mark() the end. skipFully(stream, fraction); // Skip a large fraction, but not all. assertEquals( CLASSNAME + ": after skipping to the 'middle', half the bytes are available", - (TEST_STRING.size() - fraction), stream.available()); + (testString.size() - fraction), stream.available()); stream.reset(); assertEquals( CLASSNAME + ": after resetting, all bytes are available", - TEST_STRING.size(), stream.available()); + testString.size(), stream.available()); - skipFully(stream, TEST_STRING.size()); // Skip to the end. + skipFully(stream, testString.size()); // Skip to the end. assertEquals( CLASSNAME + ": after skipping to the end, no more bytes are available", 0, stream.available()); @@ -284,7 +286,7 @@ public class NioByteStringTest extends TestCase { } public void testAsReadOnlyByteBuffer() { - ByteBuffer byteBuffer = TEST_STRING.asReadOnlyByteBuffer(); + ByteBuffer byteBuffer = testString.asReadOnlyByteBuffer(); byte[] roundTripBytes = new byte[BYTES.length]; assertTrue(byteBuffer.remaining() == BYTES.length); assertTrue(byteBuffer.isReadOnly()); @@ -294,7 +296,7 @@ public class NioByteStringTest extends TestCase { } public void testAsReadOnlyByteBufferList() { - List<ByteBuffer> byteBuffers = TEST_STRING.asReadOnlyByteBufferList(); + List<ByteBuffer> byteBuffers = testString.asReadOnlyByteBufferList(); int bytesSeen = 0; byte[] roundTripBytes = new byte[BYTES.length]; for (ByteBuffer byteBuffer : byteBuffers) { @@ -310,25 +312,98 @@ public class NioByteStringTest extends TestCase { } public void testToByteArray() { - byte[] roundTripBytes = TEST_STRING.toByteArray(); + byte[] roundTripBytes = testString.toByteArray(); assertTrue(CLASSNAME + ".toByteArray() must give back the same bytes", Arrays.equals(BYTES, roundTripBytes)); } public void testWriteTo() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); - TEST_STRING.writeTo(bos); + testString.writeTo(bos); byte[] roundTripBytes = bos.toByteArray(); assertTrue(CLASSNAME + ".writeTo() must give back the same bytes", Arrays.equals(BYTES, roundTripBytes)); } + public void testWriteToShouldNotExposeInternalBufferToOutputStream() throws IOException { + OutputStream os = new OutputStream() { + @Override + public void write(byte[] b, int off, int len) { + Arrays.fill(b, off, off + len, (byte) 0); + } + + @Override + public void write(int b) { + throw new UnsupportedOperationException(); + } + }; + + byte[] original = Arrays.copyOf(BYTES, BYTES.length); + testString.writeTo(os); + assertTrue(CLASSNAME + ".writeTo() must NOT grant access to underlying buffer", + Arrays.equals(original, BYTES)); + } + + public void testWriteToInternalShouldExposeInternalBufferToOutputStream() throws IOException { + OutputStream os = new OutputStream() { + @Override + public void write(byte[] b, int off, int len) { + Arrays.fill(b, off, off + len, (byte) 0); + } + + @Override + public void write(int b) { + throw new UnsupportedOperationException(); + } + }; + + testString.writeToInternal(os, 0, testString.size()); + byte[] allZeros = new byte[testString.size()]; + assertTrue(CLASSNAME + ".writeToInternal() must grant access to underlying buffer", + Arrays.equals(allZeros, backingBuffer.array())); + } + + public void testWriteToShouldExposeInternalBufferToByteOutput() throws IOException { + ByteOutput out = new ByteOutput() { + @Override + public void write(byte value) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void write(byte[] value, int offset, int length) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void writeLazy(byte[] value, int offset, int length) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void write(ByteBuffer value) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void writeLazy(ByteBuffer value) throws IOException { + Arrays.fill(value.array(), value.arrayOffset(), value.arrayOffset() + value.limit(), + (byte) 0); + } + }; + + testString.writeTo(out); + byte[] allZeros = new byte[testString.size()]; + assertTrue(CLASSNAME + ".writeTo() must grant access to underlying buffer", + Arrays.equals(allZeros, backingBuffer.array())); + } + public void testNewOutput() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteString.Output output = ByteString.newOutput(); - TEST_STRING.writeTo(output); + testString.writeTo(output); assertEquals("Output Size returns correct result", - output.size(), TEST_STRING.size()); + output.size(), testString.size()); output.writeTo(bos); assertTrue("Output.writeTo() must give back the same bytes", Arrays.equals(BYTES, bos.toByteArray())); @@ -336,7 +411,7 @@ public class NioByteStringTest extends TestCase { // write the output stream to itself! This should cause it to double output.writeTo(output); assertEquals("Writing an output stream to itself is successful", - TEST_STRING.concat(TEST_STRING), output.toByteString()); + testString.concat(testString), output.toByteString()); output.reset(); assertEquals("Output.reset() resets the output", 0, output.size()); @@ -373,7 +448,7 @@ public class NioByteStringTest extends TestCase { } try { - TEST_STRING.toString("invalid"); + testString.toString("invalid"); fail("Should have thrown an exception."); } catch (UnsupportedEncodingException expected) { // This is success @@ -381,36 +456,36 @@ public class NioByteStringTest extends TestCase { } public void testEquals() { - assertEquals(CLASSNAME + " must not equal null", false, TEST_STRING.equals(null)); - assertEquals(CLASSNAME + " must equal self", TEST_STRING, TEST_STRING); + assertEquals(CLASSNAME + " must not equal null", false, testString.equals(null)); + assertEquals(CLASSNAME + " must equal self", testString, testString); assertFalse(CLASSNAME + " must not equal the empty string", - TEST_STRING.equals(EMPTY)); + testString.equals(EMPTY)); assertEquals(CLASSNAME + " empty strings must be equal", - EMPTY, TEST_STRING.substring(55, 55)); + EMPTY, testString.substring(55, 55)); assertEquals(CLASSNAME + " must equal another string with the same value", - TEST_STRING, new NioByteString(BUFFER)); + testString, new NioByteString(backingBuffer)); byte[] mungedBytes = mungedBytes(); assertFalse(CLASSNAME + " must not equal every string with the same length", - TEST_STRING.equals(new NioByteString(ByteBuffer.wrap(mungedBytes)))); + testString.equals(new NioByteString(ByteBuffer.wrap(mungedBytes)))); } public void testEqualsLiteralByteString() { ByteString literal = ByteString.copyFrom(BYTES); assertEquals(CLASSNAME + " must equal LiteralByteString with same value", literal, - TEST_STRING); - assertEquals(CLASSNAME + " must equal LiteralByteString with same value", TEST_STRING, + testString); + assertEquals(CLASSNAME + " must equal LiteralByteString with same value", testString, literal); assertFalse(CLASSNAME + " must not equal the empty string", - TEST_STRING.equals(ByteString.EMPTY)); + testString.equals(ByteString.EMPTY)); assertEquals(CLASSNAME + " empty strings must be equal", - ByteString.EMPTY, TEST_STRING.substring(55, 55)); + ByteString.EMPTY, testString.substring(55, 55)); literal = ByteString.copyFrom(mungedBytes()); assertFalse(CLASSNAME + " must not equal every LiteralByteString with the same length", - TEST_STRING.equals(literal)); + testString.equals(literal)); assertFalse(CLASSNAME + " must not equal every LiteralByteString with the same length", - literal.equals(TEST_STRING)); + literal.equals(testString)); } public void testEqualsRopeByteString() { @@ -419,22 +494,22 @@ public class NioByteStringTest extends TestCase { ByteString rope = p1.concat(p2); assertEquals(CLASSNAME + " must equal RopeByteString with same value", rope, - TEST_STRING); - assertEquals(CLASSNAME + " must equal RopeByteString with same value", TEST_STRING, + testString); + assertEquals(CLASSNAME + " must equal RopeByteString with same value", testString, rope); assertFalse(CLASSNAME + " must not equal the empty string", - TEST_STRING.equals(ByteString.EMPTY.concat(ByteString.EMPTY))); + testString.equals(ByteString.EMPTY.concat(ByteString.EMPTY))); assertEquals(CLASSNAME + " empty strings must be equal", - ByteString.EMPTY.concat(ByteString.EMPTY), TEST_STRING.substring(55, 55)); + ByteString.EMPTY.concat(ByteString.EMPTY), testString.substring(55, 55)); byte[] mungedBytes = mungedBytes(); p1 = ByteString.copyFrom(mungedBytes, 0, 5); p2 = ByteString.copyFrom(mungedBytes, 5, mungedBytes.length - 5); rope = p1.concat(p2); assertFalse(CLASSNAME + " must not equal every RopeByteString with the same length", - TEST_STRING.equals(rope)); + testString.equals(rope)); assertFalse(CLASSNAME + " must not equal every RopeByteString with the same length", - rope.equals(TEST_STRING)); + rope.equals(testString)); } private byte[] mungedBytes() { @@ -445,12 +520,12 @@ public class NioByteStringTest extends TestCase { } public void testHashCode() { - int hash = TEST_STRING.hashCode(); + int hash = testString.hashCode(); assertEquals(CLASSNAME + " must have expected hashCode", EXPECTED_HASH, hash); } public void testPeekCachedHashCode() { - ByteString newString = new NioByteString(BUFFER); + ByteString newString = new NioByteString(backingBuffer); assertEquals(CLASSNAME + ".peekCachedHashCode() should return zero at first", 0, newString.peekCachedHashCode()); newString.hashCode(); @@ -461,15 +536,15 @@ public class NioByteStringTest extends TestCase { public void testPartialHash() { // partialHash() is more strenuously tested elsewhere by testing hashes of substrings. // This test would fail if the expected hash were 1. It's not. - int hash = TEST_STRING.partialHash(TEST_STRING.size(), 0, TEST_STRING.size()); + int hash = testString.partialHash(testString.size(), 0, testString.size()); assertEquals(CLASSNAME + ".partialHash() must yield expected hashCode", EXPECTED_HASH, hash); } public void testNewInput() throws IOException { - InputStream input = TEST_STRING.newInput(); + InputStream input = testString.newInput(); assertEquals("InputStream.available() returns correct value", - TEST_STRING.size(), input.available()); + testString.size(), input.available()); boolean stillEqual = true; for (byte referenceByte : BYTES) { int expectedInt = (referenceByte & 0xFF); @@ -482,8 +557,8 @@ public class NioByteStringTest extends TestCase { } public void testNewInput_skip() throws IOException { - InputStream input = TEST_STRING.newInput(); - int stringSize = TEST_STRING.size(); + InputStream input = testString.newInput(); + int stringSize = testString.size(); int nearEndIndex = stringSize * 2 / 3; long skipped1 = input.skip(nearEndIndex); assertEquals("InputStream.skip()", skipped1, nearEndIndex); @@ -492,7 +567,7 @@ public class NioByteStringTest extends TestCase { assertTrue("InputStream.mark() is available", input.markSupported()); input.mark(0); assertEquals("InputStream.skip(), read()", - TEST_STRING.byteAt(nearEndIndex) & 0xFF, input.read()); + testString.byteAt(nearEndIndex) & 0xFF, input.read()); assertEquals("InputStream.available()", stringSize - skipped1 - 1, input.available()); long skipped2 = input.skip(stringSize); @@ -504,11 +579,11 @@ public class NioByteStringTest extends TestCase { assertEquals("InputStream.reset() succeded", stringSize - skipped1, input.available()); assertEquals("InputStream.reset(), read()", - TEST_STRING.byteAt(nearEndIndex) & 0xFF, input.read()); + testString.byteAt(nearEndIndex) & 0xFF, input.read()); } public void testNewCodedInput() throws IOException { - CodedInputStream cis = TEST_STRING.newCodedInput(); + CodedInputStream cis = testString.newCodedInput(); byte[] roundTripBytes = cis.readRawBytes(BYTES.length); assertTrue(CLASSNAME + " must give the same bytes back from the CodedInputStream", Arrays.equals(BYTES, roundTripBytes)); @@ -521,22 +596,22 @@ public class NioByteStringTest extends TestCase { */ public void testConcat_empty() { assertSame(CLASSNAME + " concatenated with empty must give " + CLASSNAME, - TEST_STRING.concat(EMPTY), TEST_STRING); + testString.concat(EMPTY), testString); assertSame("empty concatenated with " + CLASSNAME + " must give " + CLASSNAME, - EMPTY.concat(TEST_STRING), TEST_STRING); + EMPTY.concat(testString), testString); } public void testJavaSerialization() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); - oos.writeObject(TEST_STRING); + oos.writeObject(testString); oos.close(); byte[] pickled = out.toByteArray(); InputStream in = new ByteArrayInputStream(pickled); ObjectInputStream ois = new ObjectInputStream(in); Object o = ois.readObject(); assertTrue("Didn't get a ByteString back", o instanceof ByteString); - assertEquals("Should get an equal ByteString back", TEST_STRING, o); + assertEquals("Should get an equal ByteString back", testString, o); } private static ByteString forString(String str) { diff --git a/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java b/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java index 37fa242d..bf1f1d71 100644 --- a/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java +++ b/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java @@ -1,17 +1,51 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + package com.google.protobuf; +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.protobuf.DescriptorProtos.DescriptorProto; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Tests the exceptions thrown when parsing from a stream. The methods on the {@link Parser} @@ -22,6 +56,7 @@ import static org.junit.Assert.fail; * * @author jh@squareup.com (Joshua Humphries) */ +@RunWith(JUnit4.class) public class ParseExceptionsTest { private interface ParseTester { @@ -46,116 +81,143 @@ public class ParseExceptionsTest { @Test public void message_parseFrom_InputStream() { setup(); - verifyExceptions(new ParseTester() { - public DescriptorProto parse(InputStream in) throws IOException { - return DescriptorProto.parseFrom(in); - } - }); + verifyExceptions( + new ParseTester() { + @Override + public DescriptorProto parse(InputStream in) throws IOException { + return DescriptorProto.parseFrom(in); + } + }); } @Test public void message_parseFrom_InputStreamAndExtensionRegistry() { setup(); - verifyExceptions(new ParseTester() { - public DescriptorProto parse(InputStream in) throws IOException { - return DescriptorProto.parseFrom(in, ExtensionRegistry.newInstance()); - } - }); + verifyExceptions( + new ParseTester() { + @Override + public DescriptorProto parse(InputStream in) throws IOException { + return DescriptorProto.parseFrom(in, ExtensionRegistry.newInstance()); + } + }); } @Test public void message_parseFrom_CodedInputStream() { setup(); - verifyExceptions(new ParseTester() { - public DescriptorProto parse(InputStream in) throws IOException { - return DescriptorProto.parseFrom(CodedInputStream.newInstance(in)); - } - }); + verifyExceptions( + new ParseTester() { + @Override + public DescriptorProto parse(InputStream in) throws IOException { + return DescriptorProto.parseFrom(CodedInputStream.newInstance(in)); + } + }); } @Test public void message_parseFrom_CodedInputStreamAndExtensionRegistry() { setup(); - verifyExceptions(new ParseTester() { - public DescriptorProto parse(InputStream in) throws IOException { - return DescriptorProto.parseFrom(CodedInputStream.newInstance(in), - ExtensionRegistry.newInstance()); - } - }); + verifyExceptions( + new ParseTester() { + @Override + public DescriptorProto parse(InputStream in) throws IOException { + return DescriptorProto.parseFrom( + CodedInputStream.newInstance(in), ExtensionRegistry.newInstance()); + } + }); } @Test public void message_parseDelimitedFrom_InputStream() { setupDelimited(); - verifyExceptions(new ParseTester() { - public DescriptorProto parse(InputStream in) throws IOException { - return DescriptorProto.parseDelimitedFrom(in); - } - }); + verifyExceptions( + new ParseTester() { + @Override + public DescriptorProto parse(InputStream in) throws IOException { + return DescriptorProto.parseDelimitedFrom(in); + } + }); } @Test public void message_parseDelimitedFrom_InputStreamAndExtensionRegistry() { setupDelimited(); - verifyExceptions(new ParseTester() { - public DescriptorProto parse(InputStream in) throws IOException { - return DescriptorProto.parseDelimitedFrom(in, ExtensionRegistry.newInstance()); - } - }); + verifyExceptions( + new ParseTester() { + @Override + public DescriptorProto parse(InputStream in) throws IOException { + return DescriptorProto.parseDelimitedFrom(in, ExtensionRegistry.newInstance()); + } + }); } @Test public void messageBuilder_mergeFrom_InputStream() { setup(); - verifyExceptions(new ParseTester() { - public DescriptorProto parse(InputStream in) throws IOException { - return DescriptorProto.newBuilder().mergeFrom(in).build(); - } - }); + verifyExceptions( + new ParseTester() { + @Override + public DescriptorProto parse(InputStream in) throws IOException { + return DescriptorProto.newBuilder().mergeFrom(in).build(); + } + }); } @Test public void messageBuilder_mergeFrom_InputStreamAndExtensionRegistry() { setup(); - verifyExceptions(new ParseTester() { - public DescriptorProto parse(InputStream in) throws IOException { - return DescriptorProto.newBuilder().mergeFrom(in, ExtensionRegistry.newInstance()).build(); - } - }); + verifyExceptions( + new ParseTester() { + @Override + public DescriptorProto parse(InputStream in) throws IOException { + return DescriptorProto.newBuilder() + .mergeFrom(in, ExtensionRegistry.newInstance()) + .build(); + } + }); } @Test public void messageBuilder_mergeFrom_CodedInputStream() { setup(); - verifyExceptions(new ParseTester() { - public DescriptorProto parse(InputStream in) throws IOException { - return DescriptorProto.newBuilder().mergeFrom(CodedInputStream.newInstance(in)).build(); - } - }); + verifyExceptions( + new ParseTester() { + @Override + public DescriptorProto parse(InputStream in) throws IOException { + return DescriptorProto.newBuilder().mergeFrom(CodedInputStream.newInstance(in)).build(); + } + }); } @Test public void messageBuilder_mergeFrom_CodedInputStreamAndExtensionRegistry() { setup(); - verifyExceptions(new ParseTester() { - public DescriptorProto parse(InputStream in) throws IOException { - return DescriptorProto.newBuilder() - .mergeFrom(CodedInputStream.newInstance(in), ExtensionRegistry.newInstance()).build(); - } - }); + verifyExceptions( + new ParseTester() { + @Override + public DescriptorProto parse(InputStream in) throws IOException { + return DescriptorProto.newBuilder() + .mergeFrom(CodedInputStream.newInstance(in), ExtensionRegistry.newInstance()) + .build(); + } + }); } @Test public void messageBuilder_mergeDelimitedFrom_InputStream() { setupDelimited(); - verifyExceptions(new ParseTester() { - public DescriptorProto parse(InputStream in) throws IOException { - DescriptorProto.Builder builder = DescriptorProto.newBuilder(); - builder.mergeDelimitedFrom(in); - return builder.build(); - } - }); + verifyExceptions( + new ParseTester() { + @Override + public DescriptorProto parse(InputStream in) throws IOException { + DescriptorProto.Builder builder = DescriptorProto.newBuilder(); + builder.mergeDelimitedFrom(in); + return builder.build(); + } + }); } @Test public void messageBuilder_mergeDelimitedFrom_InputStreamAndExtensionRegistry() { setupDelimited(); - verifyExceptions(new ParseTester() { - public DescriptorProto parse(InputStream in) throws IOException { - DescriptorProto.Builder builder = DescriptorProto.newBuilder(); - builder.mergeDelimitedFrom(in, ExtensionRegistry.newInstance()); - return builder.build(); - } - }); + verifyExceptions( + new ParseTester() { + @Override + public DescriptorProto parse(InputStream in) throws IOException { + DescriptorProto.Builder builder = DescriptorProto.newBuilder(); + builder.mergeDelimitedFrom(in, ExtensionRegistry.newInstance()); + return builder.build(); + } + }); } private void verifyExceptions(ParseTester parseTester) { diff --git a/java/core/src/test/java/com/google/protobuf/ParserTest.java b/java/core/src/test/java/com/google/protobuf/ParserTest.java index 5a92bacf..9d4b6b94 100644 --- a/java/core/src/test/java/com/google/protobuf/ParserTest.java +++ b/java/core/src/test/java/com/google/protobuf/ParserTest.java @@ -33,15 +33,15 @@ package com.google.protobuf; import com.google.protobuf.UnittestLite.TestAllTypesLite; import com.google.protobuf.UnittestLite.TestPackedExtensionsLite; import com.google.protobuf.UnittestLite.TestParsingMergeLite; +import protobuf_unittest.UnittestOptimizeFor; import protobuf_unittest.UnittestOptimizeFor.TestOptimizedForSize; import protobuf_unittest.UnittestOptimizeFor.TestRequiredOptimizedForSize; -import protobuf_unittest.UnittestOptimizeFor; +import protobuf_unittest.UnittestProto; import protobuf_unittest.UnittestProto.ForeignMessage; import protobuf_unittest.UnittestProto.TestAllTypes; import protobuf_unittest.UnittestProto.TestEmptyMessage; import protobuf_unittest.UnittestProto.TestParsingMerge; import protobuf_unittest.UnittestProto.TestRequired; -import protobuf_unittest.UnittestProto; import junit.framework.TestCase; diff --git a/java/core/src/test/java/com/google/protobuf/ServiceTest.java b/java/core/src/test/java/com/google/protobuf/ServiceTest.java index ff980d66..7f3439d0 100644 --- a/java/core/src/test/java/com/google/protobuf/ServiceTest.java +++ b/java/core/src/test/java/com/google/protobuf/ServiceTest.java @@ -35,22 +35,22 @@ import com.google.protobuf.Descriptors.MethodDescriptor; import google.protobuf.no_generic_services_test.UnittestNoGenericServices; import protobuf_unittest.MessageWithNoOuter; import protobuf_unittest.ServiceWithNoOuter; -import protobuf_unittest.UnittestProto.TestAllTypes; -import protobuf_unittest.UnittestProto.TestService; -import protobuf_unittest.UnittestProto.FooRequest; -import protobuf_unittest.UnittestProto.FooResponse; import protobuf_unittest.UnittestProto.BarRequest; import protobuf_unittest.UnittestProto.BarResponse; +import protobuf_unittest.UnittestProto.FooRequest; +import protobuf_unittest.UnittestProto.FooResponse; +import protobuf_unittest.UnittestProto.TestAllTypes; +import protobuf_unittest.UnittestProto.TestService; + +import junit.framework.TestCase; import org.easymock.classextension.EasyMock; -import org.easymock.classextension.IMocksControl; import org.easymock.IArgumentMatcher; +import org.easymock.classextension.IMocksControl; import java.util.HashSet; import java.util.Set; -import junit.framework.TestCase; - /** * Tests services and stubs. * diff --git a/java/core/src/test/java/com/google/protobuf/TestUtil.java b/java/core/src/test/java/com/google/protobuf/TestUtil.java index 01acb884..53d65428 100644 --- a/java/core/src/test/java/com/google/protobuf/TestUtil.java +++ b/java/core/src/test/java/com/google/protobuf/TestUtil.java @@ -30,205 +30,207 @@ package com.google.protobuf; -import protobuf_unittest.UnittestProto; -import com.google.protobuf.UnittestLite; - +import static com.google.protobuf.UnittestLite.OptionalGroup_extension_lite; +import static com.google.protobuf.UnittestLite.RepeatedGroup_extension_lite; +import static com.google.protobuf.UnittestLite.defaultBoolExtensionLite; +import static com.google.protobuf.UnittestLite.defaultBytesExtensionLite; +import static com.google.protobuf.UnittestLite.defaultCordExtensionLite; +import static com.google.protobuf.UnittestLite.defaultDoubleExtensionLite; +import static com.google.protobuf.UnittestLite.defaultFixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultFixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultFloatExtensionLite; +import static com.google.protobuf.UnittestLite.defaultForeignEnumExtensionLite; +import static com.google.protobuf.UnittestLite.defaultImportEnumExtensionLite; +import static com.google.protobuf.UnittestLite.defaultInt32ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultInt64ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultNestedEnumExtensionLite; +import static com.google.protobuf.UnittestLite.defaultSfixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultSfixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultSint32ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultSint64ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultStringExtensionLite; +import static com.google.protobuf.UnittestLite.defaultStringPieceExtensionLite; +import static com.google.protobuf.UnittestLite.defaultUint32ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultUint64ExtensionLite; +import static com.google.protobuf.UnittestLite.oneofBytesExtensionLite; +import static com.google.protobuf.UnittestLite.oneofNestedMessageExtensionLite; +import static com.google.protobuf.UnittestLite.oneofStringExtensionLite; +import static com.google.protobuf.UnittestLite.oneofUint32ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalBoolExtensionLite; +import static com.google.protobuf.UnittestLite.optionalBytesExtensionLite; +import static com.google.protobuf.UnittestLite.optionalCordExtensionLite; +import static com.google.protobuf.UnittestLite.optionalDoubleExtensionLite; +import static com.google.protobuf.UnittestLite.optionalFixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalFixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalFloatExtensionLite; +import static com.google.protobuf.UnittestLite.optionalForeignEnumExtensionLite; +import static com.google.protobuf.UnittestLite.optionalForeignMessageExtensionLite; +import static com.google.protobuf.UnittestLite.optionalGroupExtensionLite; +import static com.google.protobuf.UnittestLite.optionalImportEnumExtensionLite; +import static com.google.protobuf.UnittestLite.optionalImportMessageExtensionLite; +import static com.google.protobuf.UnittestLite.optionalInt32ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalInt64ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalLazyMessageExtensionLite; +import static com.google.protobuf.UnittestLite.optionalNestedEnumExtensionLite; +import static com.google.protobuf.UnittestLite.optionalNestedMessageExtensionLite; +import static com.google.protobuf.UnittestLite.optionalPublicImportMessageExtensionLite; +import static com.google.protobuf.UnittestLite.optionalSfixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalSfixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalSint32ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalSint64ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalStringExtensionLite; +import static com.google.protobuf.UnittestLite.optionalStringPieceExtensionLite; +import static com.google.protobuf.UnittestLite.optionalUint32ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalUint64ExtensionLite; +import static com.google.protobuf.UnittestLite.packedBoolExtensionLite; +import static com.google.protobuf.UnittestLite.packedDoubleExtensionLite; +import static com.google.protobuf.UnittestLite.packedEnumExtensionLite; +import static com.google.protobuf.UnittestLite.packedFixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.packedFixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.packedFloatExtensionLite; +import static com.google.protobuf.UnittestLite.packedInt32ExtensionLite; +import static com.google.protobuf.UnittestLite.packedInt64ExtensionLite; +import static com.google.protobuf.UnittestLite.packedSfixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.packedSfixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.packedSint32ExtensionLite; +import static com.google.protobuf.UnittestLite.packedSint64ExtensionLite; +import static com.google.protobuf.UnittestLite.packedUint32ExtensionLite; +import static com.google.protobuf.UnittestLite.packedUint64ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedBoolExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedBytesExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedCordExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedDoubleExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedFixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedFixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedFloatExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedForeignEnumExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedForeignMessageExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedGroupExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedImportEnumExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedImportMessageExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedInt32ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedInt64ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedLazyMessageExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedNestedEnumExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedNestedMessageExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedSfixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedSfixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedSint32ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedSint64ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedStringExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedStringPieceExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedUint32ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedUint64ExtensionLite; +import static protobuf_unittest.UnittestProto.OptionalGroup_extension; +import static protobuf_unittest.UnittestProto.RepeatedGroup_extension; +import static protobuf_unittest.UnittestProto.defaultBoolExtension; +import static protobuf_unittest.UnittestProto.defaultBytesExtension; +import static protobuf_unittest.UnittestProto.defaultCordExtension; +import static protobuf_unittest.UnittestProto.defaultDoubleExtension; +import static protobuf_unittest.UnittestProto.defaultFixed32Extension; +import static protobuf_unittest.UnittestProto.defaultFixed64Extension; +import static protobuf_unittest.UnittestProto.defaultFloatExtension; +import static protobuf_unittest.UnittestProto.defaultForeignEnumExtension; +import static protobuf_unittest.UnittestProto.defaultImportEnumExtension; // The static imports are to avoid 100+ char lines. The following is roughly equivalent to // import static protobuf_unittest.UnittestProto.*; import static protobuf_unittest.UnittestProto.defaultInt32Extension; import static protobuf_unittest.UnittestProto.defaultInt64Extension; -import static protobuf_unittest.UnittestProto.defaultUint32Extension; -import static protobuf_unittest.UnittestProto.defaultUint64Extension; -import static protobuf_unittest.UnittestProto.defaultSint32Extension; -import static protobuf_unittest.UnittestProto.defaultSint64Extension; -import static protobuf_unittest.UnittestProto.defaultFixed32Extension; -import static protobuf_unittest.UnittestProto.defaultFixed64Extension; +import static protobuf_unittest.UnittestProto.defaultNestedEnumExtension; import static protobuf_unittest.UnittestProto.defaultSfixed32Extension; import static protobuf_unittest.UnittestProto.defaultSfixed64Extension; -import static protobuf_unittest.UnittestProto.defaultFloatExtension; -import static protobuf_unittest.UnittestProto.defaultDoubleExtension; -import static protobuf_unittest.UnittestProto.defaultBoolExtension; +import static protobuf_unittest.UnittestProto.defaultSint32Extension; +import static protobuf_unittest.UnittestProto.defaultSint64Extension; import static protobuf_unittest.UnittestProto.defaultStringExtension; -import static protobuf_unittest.UnittestProto.defaultBytesExtension; -import static protobuf_unittest.UnittestProto.defaultNestedEnumExtension; -import static protobuf_unittest.UnittestProto.defaultForeignEnumExtension; -import static protobuf_unittest.UnittestProto.defaultImportEnumExtension; import static protobuf_unittest.UnittestProto.defaultStringPieceExtension; -import static protobuf_unittest.UnittestProto.defaultCordExtension; - -import static protobuf_unittest.UnittestProto.oneofUint32Extension; +import static protobuf_unittest.UnittestProto.defaultUint32Extension; +import static protobuf_unittest.UnittestProto.defaultUint64Extension; +import static protobuf_unittest.UnittestProto.oneofBytesExtension; import static protobuf_unittest.UnittestProto.oneofNestedMessageExtension; import static protobuf_unittest.UnittestProto.oneofStringExtension; -import static protobuf_unittest.UnittestProto.oneofBytesExtension; - -import static protobuf_unittest.UnittestProto.optionalInt32Extension; -import static protobuf_unittest.UnittestProto.optionalInt64Extension; -import static protobuf_unittest.UnittestProto.optionalUint32Extension; -import static protobuf_unittest.UnittestProto.optionalUint64Extension; -import static protobuf_unittest.UnittestProto.optionalSint32Extension; -import static protobuf_unittest.UnittestProto.optionalSint64Extension; -import static protobuf_unittest.UnittestProto.optionalFixed32Extension; -import static protobuf_unittest.UnittestProto.optionalFixed64Extension; -import static protobuf_unittest.UnittestProto.optionalSfixed32Extension; -import static protobuf_unittest.UnittestProto.optionalSfixed64Extension; -import static protobuf_unittest.UnittestProto.optionalFloatExtension; -import static protobuf_unittest.UnittestProto.optionalDoubleExtension; +import static protobuf_unittest.UnittestProto.oneofUint32Extension; import static protobuf_unittest.UnittestProto.optionalBoolExtension; -import static protobuf_unittest.UnittestProto.optionalStringExtension; import static protobuf_unittest.UnittestProto.optionalBytesExtension; -import static protobuf_unittest.UnittestProto.optionalGroupExtension; import static protobuf_unittest.UnittestProto.optionalCordExtension; +import static protobuf_unittest.UnittestProto.optionalDoubleExtension; +import static protobuf_unittest.UnittestProto.optionalFixed32Extension; +import static protobuf_unittest.UnittestProto.optionalFixed64Extension; +import static protobuf_unittest.UnittestProto.optionalFloatExtension; import static protobuf_unittest.UnittestProto.optionalForeignEnumExtension; import static protobuf_unittest.UnittestProto.optionalForeignMessageExtension; +import static protobuf_unittest.UnittestProto.optionalGroupExtension; import static protobuf_unittest.UnittestProto.optionalImportEnumExtension; import static protobuf_unittest.UnittestProto.optionalImportMessageExtension; +import static protobuf_unittest.UnittestProto.optionalInt32Extension; +import static protobuf_unittest.UnittestProto.optionalInt64Extension; +import static protobuf_unittest.UnittestProto.optionalLazyMessageExtension; import static protobuf_unittest.UnittestProto.optionalNestedEnumExtension; import static protobuf_unittest.UnittestProto.optionalNestedMessageExtension; import static protobuf_unittest.UnittestProto.optionalPublicImportMessageExtension; -import static protobuf_unittest.UnittestProto.optionalLazyMessageExtension; +import static protobuf_unittest.UnittestProto.optionalSfixed32Extension; +import static protobuf_unittest.UnittestProto.optionalSfixed64Extension; +import static protobuf_unittest.UnittestProto.optionalSint32Extension; +import static protobuf_unittest.UnittestProto.optionalSint64Extension; +import static protobuf_unittest.UnittestProto.optionalStringExtension; import static protobuf_unittest.UnittestProto.optionalStringPieceExtension; - -import static protobuf_unittest.UnittestProto.repeatedInt32Extension; -import static protobuf_unittest.UnittestProto.repeatedInt64Extension; -import static protobuf_unittest.UnittestProto.repeatedUint32Extension; -import static protobuf_unittest.UnittestProto.repeatedUint64Extension; -import static protobuf_unittest.UnittestProto.repeatedSint32Extension; -import static protobuf_unittest.UnittestProto.repeatedSint64Extension; +import static protobuf_unittest.UnittestProto.optionalUint32Extension; +import static protobuf_unittest.UnittestProto.optionalUint64Extension; +import static protobuf_unittest.UnittestProto.packedBoolExtension; +import static protobuf_unittest.UnittestProto.packedDoubleExtension; +import static protobuf_unittest.UnittestProto.packedEnumExtension; +import static protobuf_unittest.UnittestProto.packedFixed32Extension; +import static protobuf_unittest.UnittestProto.packedFixed64Extension; +import static protobuf_unittest.UnittestProto.packedFloatExtension; +import static protobuf_unittest.UnittestProto.packedInt32Extension; +import static protobuf_unittest.UnittestProto.packedInt64Extension; +import static protobuf_unittest.UnittestProto.packedSfixed32Extension; +import static protobuf_unittest.UnittestProto.packedSfixed64Extension; +import static protobuf_unittest.UnittestProto.packedSint32Extension; +import static protobuf_unittest.UnittestProto.packedSint64Extension; +import static protobuf_unittest.UnittestProto.packedUint32Extension; +import static protobuf_unittest.UnittestProto.packedUint64Extension; +import static protobuf_unittest.UnittestProto.repeatedBoolExtension; +import static protobuf_unittest.UnittestProto.repeatedBytesExtension; +import static protobuf_unittest.UnittestProto.repeatedCordExtension; +import static protobuf_unittest.UnittestProto.repeatedDoubleExtension; import static protobuf_unittest.UnittestProto.repeatedFixed32Extension; import static protobuf_unittest.UnittestProto.repeatedFixed64Extension; -import static protobuf_unittest.UnittestProto.repeatedSfixed32Extension; -import static protobuf_unittest.UnittestProto.repeatedSfixed64Extension; import static protobuf_unittest.UnittestProto.repeatedFloatExtension; -import static protobuf_unittest.UnittestProto.repeatedDoubleExtension; -import static protobuf_unittest.UnittestProto.repeatedBoolExtension; -import static protobuf_unittest.UnittestProto.repeatedStringExtension; -import static protobuf_unittest.UnittestProto.repeatedBytesExtension; -import static protobuf_unittest.UnittestProto.repeatedGroupExtension; -import static protobuf_unittest.UnittestProto.repeatedNestedMessageExtension; +import static protobuf_unittest.UnittestProto.repeatedForeignEnumExtension; import static protobuf_unittest.UnittestProto.repeatedForeignMessageExtension; +import static protobuf_unittest.UnittestProto.repeatedGroupExtension; +import static protobuf_unittest.UnittestProto.repeatedImportEnumExtension; import static protobuf_unittest.UnittestProto.repeatedImportMessageExtension; +import static protobuf_unittest.UnittestProto.repeatedInt32Extension; +import static protobuf_unittest.UnittestProto.repeatedInt64Extension; import static protobuf_unittest.UnittestProto.repeatedLazyMessageExtension; import static protobuf_unittest.UnittestProto.repeatedNestedEnumExtension; -import static protobuf_unittest.UnittestProto.repeatedForeignEnumExtension; -import static protobuf_unittest.UnittestProto.repeatedImportEnumExtension; +import static protobuf_unittest.UnittestProto.repeatedNestedMessageExtension; +import static protobuf_unittest.UnittestProto.repeatedSfixed32Extension; +import static protobuf_unittest.UnittestProto.repeatedSfixed64Extension; +import static protobuf_unittest.UnittestProto.repeatedSint32Extension; +import static protobuf_unittest.UnittestProto.repeatedSint64Extension; +import static protobuf_unittest.UnittestProto.repeatedStringExtension; import static protobuf_unittest.UnittestProto.repeatedStringPieceExtension; -import static protobuf_unittest.UnittestProto.repeatedCordExtension; - -import static protobuf_unittest.UnittestProto.OptionalGroup_extension; -import static protobuf_unittest.UnittestProto.RepeatedGroup_extension; - -import static protobuf_unittest.UnittestProto.packedInt32Extension; -import static protobuf_unittest.UnittestProto.packedInt64Extension; -import static protobuf_unittest.UnittestProto.packedUint32Extension; -import static protobuf_unittest.UnittestProto.packedUint64Extension; -import static protobuf_unittest.UnittestProto.packedSint32Extension; -import static protobuf_unittest.UnittestProto.packedSint64Extension; -import static protobuf_unittest.UnittestProto.packedFixed32Extension; -import static protobuf_unittest.UnittestProto.packedFixed64Extension; -import static protobuf_unittest.UnittestProto.packedSfixed32Extension; -import static protobuf_unittest.UnittestProto.packedSfixed64Extension; -import static protobuf_unittest.UnittestProto.packedFloatExtension; -import static protobuf_unittest.UnittestProto.packedDoubleExtension; -import static protobuf_unittest.UnittestProto.packedBoolExtension; -import static protobuf_unittest.UnittestProto.packedEnumExtension; - -import static com.google.protobuf.UnittestLite.defaultInt32ExtensionLite; -import static com.google.protobuf.UnittestLite.defaultInt64ExtensionLite; -import static com.google.protobuf.UnittestLite.defaultUint32ExtensionLite; -import static com.google.protobuf.UnittestLite.defaultUint64ExtensionLite; -import static com.google.protobuf.UnittestLite.defaultSint32ExtensionLite; -import static com.google.protobuf.UnittestLite.defaultSint64ExtensionLite; -import static com.google.protobuf.UnittestLite.defaultFixed32ExtensionLite; -import static com.google.protobuf.UnittestLite.defaultFixed64ExtensionLite; -import static com.google.protobuf.UnittestLite.defaultSfixed32ExtensionLite; -import static com.google.protobuf.UnittestLite.defaultSfixed64ExtensionLite; -import static com.google.protobuf.UnittestLite.defaultFloatExtensionLite; -import static com.google.protobuf.UnittestLite.defaultDoubleExtensionLite; -import static com.google.protobuf.UnittestLite.defaultBoolExtensionLite; -import static com.google.protobuf.UnittestLite.defaultStringExtensionLite; -import static com.google.protobuf.UnittestLite.defaultBytesExtensionLite; -import static com.google.protobuf.UnittestLite.defaultNestedEnumExtensionLite; -import static com.google.protobuf.UnittestLite.defaultForeignEnumExtensionLite; -import static com.google.protobuf.UnittestLite.defaultImportEnumExtensionLite; -import static com.google.protobuf.UnittestLite.defaultStringPieceExtensionLite; -import static com.google.protobuf.UnittestLite.defaultCordExtensionLite; - -import static com.google.protobuf.UnittestLite.oneofUint32ExtensionLite; -import static com.google.protobuf.UnittestLite.oneofNestedMessageExtensionLite; -import static com.google.protobuf.UnittestLite.oneofStringExtensionLite; -import static com.google.protobuf.UnittestLite.oneofBytesExtensionLite; - -import static com.google.protobuf.UnittestLite.optionalInt32ExtensionLite; -import static com.google.protobuf.UnittestLite.optionalInt64ExtensionLite; -import static com.google.protobuf.UnittestLite.optionalUint32ExtensionLite; -import static com.google.protobuf.UnittestLite.optionalUint64ExtensionLite; -import static com.google.protobuf.UnittestLite.optionalSint32ExtensionLite; -import static com.google.protobuf.UnittestLite.optionalSint64ExtensionLite; -import static com.google.protobuf.UnittestLite.optionalFixed32ExtensionLite; -import static com.google.protobuf.UnittestLite.optionalFixed64ExtensionLite; -import static com.google.protobuf.UnittestLite.optionalSfixed32ExtensionLite; -import static com.google.protobuf.UnittestLite.optionalSfixed64ExtensionLite; -import static com.google.protobuf.UnittestLite.optionalFloatExtensionLite; -import static com.google.protobuf.UnittestLite.optionalDoubleExtensionLite; -import static com.google.protobuf.UnittestLite.optionalBoolExtensionLite; -import static com.google.protobuf.UnittestLite.optionalStringExtensionLite; -import static com.google.protobuf.UnittestLite.optionalBytesExtensionLite; -import static com.google.protobuf.UnittestLite.optionalGroupExtensionLite; -import static com.google.protobuf.UnittestLite.optionalNestedMessageExtensionLite; -import static com.google.protobuf.UnittestLite.optionalForeignEnumExtensionLite; -import static com.google.protobuf.UnittestLite.optionalForeignMessageExtensionLite; -import static com.google.protobuf.UnittestLite.optionalImportEnumExtensionLite; -import static com.google.protobuf.UnittestLite.optionalImportMessageExtensionLite; -import static com.google.protobuf.UnittestLite.optionalNestedEnumExtensionLite; -import static com.google.protobuf.UnittestLite.optionalPublicImportMessageExtensionLite; -import static com.google.protobuf.UnittestLite.optionalLazyMessageExtensionLite; -import static com.google.protobuf.UnittestLite.optionalStringPieceExtensionLite; -import static com.google.protobuf.UnittestLite.optionalCordExtensionLite; - -import static com.google.protobuf.UnittestLite.repeatedInt32ExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedInt64ExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedUint32ExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedUint64ExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedSint32ExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedSint64ExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedFixed32ExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedFixed64ExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedSfixed32ExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedSfixed64ExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedFloatExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedDoubleExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedBoolExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedStringExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedBytesExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedGroupExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedNestedMessageExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedForeignMessageExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedImportMessageExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedLazyMessageExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedNestedEnumExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedForeignEnumExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedImportEnumExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedStringPieceExtensionLite; -import static com.google.protobuf.UnittestLite.repeatedCordExtensionLite; - -import static com.google.protobuf.UnittestLite.OptionalGroup_extension_lite; -import static com.google.protobuf.UnittestLite.RepeatedGroup_extension_lite; - -import static com.google.protobuf.UnittestLite.packedInt32ExtensionLite; -import static com.google.protobuf.UnittestLite.packedInt64ExtensionLite; -import static com.google.protobuf.UnittestLite.packedUint32ExtensionLite; -import static com.google.protobuf.UnittestLite.packedUint64ExtensionLite; -import static com.google.protobuf.UnittestLite.packedSint32ExtensionLite; -import static com.google.protobuf.UnittestLite.packedSint64ExtensionLite; -import static com.google.protobuf.UnittestLite.packedFixed32ExtensionLite; -import static com.google.protobuf.UnittestLite.packedFixed64ExtensionLite; -import static com.google.protobuf.UnittestLite.packedSfixed32ExtensionLite; -import static com.google.protobuf.UnittestLite.packedSfixed64ExtensionLite; -import static com.google.protobuf.UnittestLite.packedFloatExtensionLite; -import static com.google.protobuf.UnittestLite.packedDoubleExtensionLite; -import static com.google.protobuf.UnittestLite.packedBoolExtensionLite; -import static com.google.protobuf.UnittestLite.packedEnumExtensionLite; +import static protobuf_unittest.UnittestProto.repeatedUint32Extension; +import static protobuf_unittest.UnittestProto.repeatedUint64Extension; +import com.google.protobuf.UnittestImportLite.ImportEnumLite; +import com.google.protobuf.UnittestImportLite.ImportMessageLite; +import com.google.protobuf.UnittestImportPublicLite.PublicImportMessageLite; +import com.google.protobuf.UnittestLite; +import com.google.protobuf.UnittestLite.ForeignEnumLite; +import com.google.protobuf.UnittestLite.ForeignMessageLite; +import com.google.protobuf.UnittestLite.TestAllExtensionsLite; +import com.google.protobuf.UnittestLite.TestAllExtensionsLiteOrBuilder; +import com.google.protobuf.UnittestLite.TestAllTypesLite; +import com.google.protobuf.UnittestLite.TestPackedExtensionsLite; +import com.google.protobuf.test.UnittestImport.ImportEnum; +import com.google.protobuf.test.UnittestImport.ImportMessage; +import com.google.protobuf.test.UnittestImportPublic.PublicImportMessage; +import protobuf_unittest.UnittestProto; +import protobuf_unittest.UnittestProto.ForeignEnum; +import protobuf_unittest.UnittestProto.ForeignMessage; import protobuf_unittest.UnittestProto.TestAllExtensions; import protobuf_unittest.UnittestProto.TestAllExtensionsOrBuilder; import protobuf_unittest.UnittestProto.TestAllTypes; @@ -237,21 +239,6 @@ import protobuf_unittest.UnittestProto.TestOneof2; import protobuf_unittest.UnittestProto.TestPackedExtensions; import protobuf_unittest.UnittestProto.TestPackedTypes; import protobuf_unittest.UnittestProto.TestUnpackedTypes; -import protobuf_unittest.UnittestProto.ForeignMessage; -import protobuf_unittest.UnittestProto.ForeignEnum; -import com.google.protobuf.test.UnittestImport.ImportEnum; -import com.google.protobuf.test.UnittestImport.ImportMessage; -import com.google.protobuf.test.UnittestImportPublic.PublicImportMessage; - -import com.google.protobuf.UnittestLite.TestAllTypesLite; -import com.google.protobuf.UnittestLite.TestAllExtensionsLite; -import com.google.protobuf.UnittestLite.TestAllExtensionsLiteOrBuilder; -import com.google.protobuf.UnittestLite.TestPackedExtensionsLite; -import com.google.protobuf.UnittestLite.ForeignMessageLite; -import com.google.protobuf.UnittestLite.ForeignEnumLite; -import com.google.protobuf.UnittestImportLite.ImportEnumLite; -import com.google.protobuf.UnittestImportLite.ImportMessageLite; -import com.google.protobuf.UnittestImportPublicLite.PublicImportMessageLite; import junit.framework.Assert; diff --git a/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java b/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java new file mode 100644 index 00000000..e338af21 --- /dev/null +++ b/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java @@ -0,0 +1,182 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package com.google.protobuf; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import protobuf_unittest.UnittestProto.TestAllTypes; + +import junit.framework.TestCase; + +/** + * Test @{link TextFormatParseInfoTree}. + */ +public class TextFormatParseInfoTreeTest extends TestCase { + + private static final Descriptor DESCRIPTOR = TestAllTypes.getDescriptor(); + private static final FieldDescriptor OPTIONAL_INT32 = + DESCRIPTOR.findFieldByName("optional_int32"); + private static final FieldDescriptor OPTIONAL_BOOLEAN = + DESCRIPTOR.findFieldByName("optional_boolean"); + private static final FieldDescriptor REPEATED_INT32 = + DESCRIPTOR.findFieldByName("repeated_int32"); + private static final FieldDescriptor OPTIONAL_NESTED_MESSAGE = + DESCRIPTOR.findFieldByName("optional_nested_message"); + private static final FieldDescriptor REPEATED_NESTED_MESSAGE = + DESCRIPTOR.findFieldByName("repeated_nested_message"); + private static final FieldDescriptor FIELD_BB = + TestAllTypes.NestedMessage.getDescriptor().findFieldByName("bb"); + + private static final TextFormatParseLocation LOC0 = TextFormatParseLocation.create(1, 2); + private static final TextFormatParseLocation LOC1 = TextFormatParseLocation.create(2, 3); + + private TextFormatParseInfoTree.Builder rootBuilder; + + @Override + public void setUp() { + rootBuilder = TextFormatParseInfoTree.builder(); + } + + public void testBuildEmptyParseTree() { + TextFormatParseInfoTree tree = rootBuilder.build(); + assertTrue(tree.getLocations(null).isEmpty()); + } + + public void testGetLocationReturnsSingleLocation() { + rootBuilder.setLocation(OPTIONAL_INT32, LOC0); + TextFormatParseInfoTree root = rootBuilder.build(); + assertEquals(LOC0, root.getLocation(OPTIONAL_INT32, 0)); + assertEquals(1, root.getLocations(OPTIONAL_INT32).size()); + } + + public void testGetLocationsReturnsNoParseLocationsForUnknownField() { + assertTrue(rootBuilder.build().getLocations(OPTIONAL_INT32).isEmpty()); + rootBuilder.setLocation(OPTIONAL_BOOLEAN, LOC0); + TextFormatParseInfoTree root = rootBuilder.build(); + assertTrue(root.getLocations(OPTIONAL_INT32).isEmpty()); + assertEquals(LOC0, root.getLocations(OPTIONAL_BOOLEAN).get(0)); + } + + public void testGetLocationThrowsIllegalArgumentExceptionForUnknownField() { + rootBuilder.setLocation(REPEATED_INT32, LOC0); + TextFormatParseInfoTree root = rootBuilder.build(); + try { + root.getNestedTree(OPTIONAL_INT32, 0); + fail("Did not detect unknown field"); + } catch (IllegalArgumentException expected) { + // pass + } + } + + public void testGetLocationThrowsIllegalArgumentExceptionForInvalidIndex() { + TextFormatParseInfoTree root = rootBuilder.setLocation(OPTIONAL_INT32, LOC0).build(); + try { + root.getLocation(OPTIONAL_INT32, 1); + fail("Invalid index not detected"); + } catch (IllegalArgumentException expected) { + // pass + } + try { + root.getLocation(OPTIONAL_INT32, -1); + fail("Negative index not detected"); + } catch (IllegalArgumentException expected) { + // pass + } + } + + public void testGetLocationsReturnsMultipleLocations() { + rootBuilder.setLocation(REPEATED_INT32, LOC0); + rootBuilder.setLocation(REPEATED_INT32, LOC1); + TextFormatParseInfoTree root = rootBuilder.build(); + assertEquals(LOC0, root.getLocation(REPEATED_INT32, 0)); + assertEquals(LOC1, root.getLocation(REPEATED_INT32, 1)); + assertEquals(2, root.getLocations(REPEATED_INT32).size()); + } + + public void testGetNestedTreeThrowsIllegalArgumentExceptionForUnknownField() { + rootBuilder.setLocation(REPEATED_INT32, LOC0); + TextFormatParseInfoTree root = rootBuilder.build(); + try { + root.getNestedTree(OPTIONAL_NESTED_MESSAGE, 0); + fail("Did not detect unknown field"); + } catch (IllegalArgumentException expected) { + // pass + } + } + + public void testGetNestedTreesReturnsNoParseInfoTreesForUnknownField() { + rootBuilder.setLocation(REPEATED_INT32, LOC0); + TextFormatParseInfoTree root = rootBuilder.build(); + assertTrue(root.getNestedTrees(OPTIONAL_NESTED_MESSAGE).isEmpty()); + } + + public void testGetNestedTreeThrowsIllegalArgumentExceptionForInvalidIndex() { + rootBuilder.setLocation(REPEATED_INT32, LOC0); + rootBuilder.getBuilderForSubMessageField(OPTIONAL_NESTED_MESSAGE); + TextFormatParseInfoTree root = rootBuilder.build(); + try { + root.getNestedTree(OPTIONAL_NESTED_MESSAGE, 1); + fail("Submessage index that is too large not detected"); + } catch (IllegalArgumentException expected) { + // pass + } + try { + rootBuilder.build().getNestedTree(OPTIONAL_NESTED_MESSAGE, -1); + fail("Invalid submessage index (-1) not detected"); + } catch (IllegalArgumentException expected) { + // pass + } + } + + public void testGetNestedTreesReturnsSingleTree() { + rootBuilder.getBuilderForSubMessageField(OPTIONAL_NESTED_MESSAGE); + TextFormatParseInfoTree root = rootBuilder.build(); + assertEquals(1, root.getNestedTrees(OPTIONAL_NESTED_MESSAGE).size()); + TextFormatParseInfoTree subtree = root.getNestedTrees(OPTIONAL_NESTED_MESSAGE).get(0); + assertNotNull(subtree); + } + + public void testGetNestedTreesReturnsMultipleTrees() { + TextFormatParseInfoTree.Builder subtree1Builder = + rootBuilder.getBuilderForSubMessageField(REPEATED_NESTED_MESSAGE); + subtree1Builder.getBuilderForSubMessageField(FIELD_BB); + subtree1Builder.getBuilderForSubMessageField(FIELD_BB); + TextFormatParseInfoTree.Builder subtree2Builder = + rootBuilder.getBuilderForSubMessageField(REPEATED_NESTED_MESSAGE); + subtree2Builder.getBuilderForSubMessageField(FIELD_BB); + TextFormatParseInfoTree root = rootBuilder.build(); + assertEquals(2, root.getNestedTrees(REPEATED_NESTED_MESSAGE).size()); + assertEquals( + 2, root.getNestedTrees(REPEATED_NESTED_MESSAGE).get(0).getNestedTrees(FIELD_BB).size()); + assertEquals( + 1, root.getNestedTrees(REPEATED_NESTED_MESSAGE).get(1).getNestedTrees(FIELD_BB).size()); + } +} diff --git a/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java b/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java new file mode 100644 index 00000000..c42bfa6e --- /dev/null +++ b/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java @@ -0,0 +1,86 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package com.google.protobuf; + +import junit.framework.TestCase; + +/** + * Test @{link TextFormatParseLocation}. + */ +public class TextFormatParseLocationTest extends TestCase { + + public void testCreateEmpty() { + TextFormatParseLocation location = TextFormatParseLocation.create(-1, -1); + assertEquals(TextFormatParseLocation.EMPTY, location); + } + + public void testCreate() { + TextFormatParseLocation location = TextFormatParseLocation.create(2, 1); + assertEquals(2, location.getLine()); + assertEquals(1, location.getColumn()); + } + + public void testCreateThrowsIllegalArgumentExceptionForInvalidIndex() { + try { + TextFormatParseLocation.create(-1, 0); + fail("Should throw IllegalArgumentException if line is less than 0"); + } catch (IllegalArgumentException unused) { + // pass + } + try { + TextFormatParseLocation.create(0, -1); + fail("Should throw, column < 0"); + } catch (IllegalArgumentException unused) { + // pass + } + } + + public void testHashCode() { + TextFormatParseLocation loc0 = TextFormatParseLocation.create(2, 1); + TextFormatParseLocation loc1 = TextFormatParseLocation.create(2, 1); + + assertEquals(loc0.hashCode(), loc1.hashCode()); + assertEquals( + TextFormatParseLocation.EMPTY.hashCode(), TextFormatParseLocation.EMPTY.hashCode()); + } + + public void testEquals() { + TextFormatParseLocation loc0 = TextFormatParseLocation.create(2, 1); + TextFormatParseLocation loc1 = TextFormatParseLocation.create(1, 2); + TextFormatParseLocation loc2 = TextFormatParseLocation.create(2, 2); + TextFormatParseLocation loc3 = TextFormatParseLocation.create(2, 1); + + assertEquals(loc0, loc3); + assertNotSame(loc0, loc1); + assertNotSame(loc0, loc2); + assertNotSame(loc1, loc2); + } +} diff --git a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java index 1df4fad7..3f47d924 100644 --- a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java +++ b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java @@ -30,6 +30,7 @@ package com.google.protobuf; +import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.TextFormat.Parser.SingularOverwritePolicy; import protobuf_unittest.UnittestMset.TestMessageSetExtension1; @@ -45,6 +46,7 @@ import proto2_wireformat_unittest.UnittestMsetWireFormat.TestMessageSet; import junit.framework.TestCase; import java.io.StringReader; +import java.util.List; /** * Test case for {@link TextFormat}. @@ -568,6 +570,16 @@ public class TextFormatTest extends TestCase { assertEquals(kEscapeTestString, TextFormat.unescapeText(kEscapeTestStringEscaped)); + // Invariant + assertEquals("hello", + TextFormat.escapeBytes(bytes("hello"))); + assertEquals("hello", + TextFormat.escapeText("hello")); + assertEquals(bytes("hello"), + TextFormat.unescapeBytes("hello")); + assertEquals("hello", + TextFormat.unescapeText("hello")); + // Unicode handling. assertEquals("\\341\\210\\264", TextFormat.escapeText("\u1234")); assertEquals("\\341\\210\\264", @@ -811,7 +823,6 @@ public class TextFormatTest extends TestCase { private void assertPrintFieldValue(String expect, Object value, String fieldName) throws Exception { - TestAllTypes.Builder builder = TestAllTypes.newBuilder(); StringBuilder sb = new StringBuilder(); TextFormat.printFieldValue( TestAllTypes.getDescriptor().findFieldByName(fieldName), @@ -1018,4 +1029,98 @@ public class TextFormatTest extends TestCase { assertFalse(oneof.hasFooString()); assertTrue(oneof.hasFooInt()); } + + // ======================================================================= + // test location information + + public void testParseInfoTreeBuilding() throws Exception { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + + Descriptor descriptor = TestAllTypes.getDescriptor(); + TextFormatParseInfoTree.Builder treeBuilder = TextFormatParseInfoTree.builder(); + // Set to allow unknown fields + TextFormat.Parser parser = + TextFormat.Parser.newBuilder() + .setParseInfoTreeBuilder(treeBuilder) + .build(); + + final String stringData = + "optional_int32: 1\n" + + "optional_int64: 2\n" + + " optional_double: 2.4\n" + + "repeated_int32: 5\n" + + "repeated_int32: 10\n" + + "optional_nested_message <\n" + + " bb: 78\n" + + ">\n" + + "repeated_nested_message <\n" + + " bb: 79\n" + + ">\n" + + "repeated_nested_message <\n" + + " bb: 80\n" + + ">"; + + parser.merge(stringData, builder); + TextFormatParseInfoTree tree = treeBuilder.build(); + + // Verify that the tree has the correct positions. + assertLocation(tree, descriptor, "optional_int32", 0, 0, 0); + assertLocation(tree, descriptor, "optional_int64", 0, 1, 0); + assertLocation(tree, descriptor, "optional_double", 0, 2, 2); + + assertLocation(tree, descriptor, "repeated_int32", 0, 3, 0); + assertLocation(tree, descriptor, "repeated_int32", 1, 4, 0); + + assertLocation(tree, descriptor, "optional_nested_message", 0, 5, 0); + assertLocation(tree, descriptor, "repeated_nested_message", 0, 8, 0); + assertLocation(tree, descriptor, "repeated_nested_message", 1, 11, 0); + + // Check for fields not set. For an invalid field, the location returned should be -1, -1. + assertLocation(tree, descriptor, "repeated_int64", 0, -1, -1); + assertLocation(tree, descriptor, "repeated_int32", 6, -1, -1); + + // Verify inside the nested message. + FieldDescriptor nestedField = descriptor.findFieldByName("optional_nested_message"); + + TextFormatParseInfoTree nestedTree = tree.getNestedTrees(nestedField).get(0); + assertLocation(nestedTree, nestedField.getMessageType(), "bb", 0, 6, 2); + + // Verify inside another nested message. + nestedField = descriptor.findFieldByName("repeated_nested_message"); + nestedTree = tree.getNestedTrees(nestedField).get(0); + assertLocation(nestedTree, nestedField.getMessageType(), "bb", 0, 9, 2); + + nestedTree = tree.getNestedTrees(nestedField).get(1); + assertLocation(nestedTree, nestedField.getMessageType(), "bb", 0, 12, 2); + + // Verify a NULL tree for an unknown nested field. + try { + tree.getNestedTree(nestedField, 2); + fail("unknown nested field should throw"); + } catch (IllegalArgumentException unused) { + // pass + } + } + + private void assertLocation( + TextFormatParseInfoTree tree, + final Descriptor descriptor, + final String fieldName, + int index, + int line, + int column) { + List<TextFormatParseLocation> locs = tree.getLocations(descriptor.findFieldByName(fieldName)); + if (index < locs.size()) { + TextFormatParseLocation location = locs.get(index); + TextFormatParseLocation expected = TextFormatParseLocation.create(line, column); + assertEquals(expected, location); + } else if (line != -1 && column != -1) { + fail( + String.format( + "Tree/descriptor/fieldname did not contain index %d, line %d column %d expected", + index, + line, + column)); + } + } } diff --git a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java index dc987379..573cd665 100644 --- a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java +++ b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java @@ -47,46 +47,6 @@ import java.io.IOException; * @author dweis@google.com (Daniel Weis) */ public class UnknownFieldSetLiteTest extends TestCase { - - public void testNoDataIsDefaultInstance() { - assertSame( - UnknownFieldSetLite.getDefaultInstance(), - UnknownFieldSetLite.newBuilder() - .build()); - } - - public void testBuilderReuse() throws IOException { - UnknownFieldSetLite.Builder builder = UnknownFieldSetLite.newBuilder(); - builder.mergeVarintField(10, 2); - builder.build(); - - try { - builder.build(); - fail(); - } catch (UnsupportedOperationException e) { - // Expected. - } - - try { - builder.mergeFieldFrom(0, CodedInputStream.newInstance(new byte[0])); - fail(); - } catch (UnsupportedOperationException e) { - // Expected. - } - - try { - builder.mergeVarintField(5, 1); - fail(); - } catch (UnsupportedOperationException e) { - // Expected. - } - } - - public void testBuilderReuse_empty() { - UnknownFieldSetLite.Builder builder = UnknownFieldSetLite.newBuilder(); - builder.build(); - builder.build(); - } public void testDefaultInstance() { UnknownFieldSetLite unknownFields = UnknownFieldSetLite.getDefaultInstance(); diff --git a/java/core/src/test/java/com/google/protobuf/WireFormatTest.java b/java/core/src/test/java/com/google/protobuf/WireFormatTest.java index 0175005d..b3aabb8f 100644 --- a/java/core/src/test/java/com/google/protobuf/WireFormatTest.java +++ b/java/core/src/test/java/com/google/protobuf/WireFormatTest.java @@ -30,12 +30,11 @@ package com.google.protobuf; -import junit.framework.TestCase; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.List; - +import com.google.protobuf.UnittestLite.TestAllExtensionsLite; +import com.google.protobuf.UnittestLite.TestPackedExtensionsLite; +import protobuf_unittest.UnittestMset.RawMessageSet; +import protobuf_unittest.UnittestMset.TestMessageSetExtension1; +import protobuf_unittest.UnittestMset.TestMessageSetExtension2; import protobuf_unittest.UnittestProto; import protobuf_unittest.UnittestProto.TestAllExtensions; import protobuf_unittest.UnittestProto.TestAllTypes; @@ -44,12 +43,13 @@ import protobuf_unittest.UnittestProto.TestOneof2; import protobuf_unittest.UnittestProto.TestOneofBackwardsCompatible; import protobuf_unittest.UnittestProto.TestPackedExtensions; import protobuf_unittest.UnittestProto.TestPackedTypes; -import protobuf_unittest.UnittestMset.RawMessageSet; -import protobuf_unittest.UnittestMset.TestMessageSetExtension1; -import protobuf_unittest.UnittestMset.TestMessageSetExtension2; import proto2_wireformat_unittest.UnittestMsetWireFormat.TestMessageSet; -import com.google.protobuf.UnittestLite.TestAllExtensionsLite; -import com.google.protobuf.UnittestLite.TestPackedExtensionsLite; + +import junit.framework.TestCase; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.List; /** * Tests related to parsing and serialization. diff --git a/java/core/src/test/proto/com/google/protobuf/lite_equals_and_hash.proto b/java/core/src/test/proto/com/google/protobuf/lite_equals_and_hash.proto index 86837250..f75484de 100644 --- a/java/core/src/test/proto/com/google/protobuf/lite_equals_and_hash.proto +++ b/java/core/src/test/proto/com/google/protobuf/lite_equals_and_hash.proto @@ -39,6 +39,13 @@ package protobuf_unittest.lite_equals_and_hash; option java_generate_equals_and_hash = true; option optimize_for = LITE_RUNTIME; +message TestOneofEquals { + oneof oneof_field { + string name = 1; + int32 value = 2; + } +} + message Foo { optional int32 value = 1; repeated Bar bar = 2; @@ -70,3 +77,8 @@ extend Foo { } } +message TestRecursiveOneof { + oneof Foo { + TestRecursiveOneof r = 1; + } +} |