Cleanup kokoro usages of java_compatibility and eliminate java/compatibility_tests. (#8504)

pull/8519/head
Derek Perez 4 years ago committed by GitHub
parent 32af37aa38
commit d1b2eff440
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 50
      java/compatibility_tests/README.md
  2. 43
      java/compatibility_tests/v2.5.0/deps/pom.xml
  3. 69
      java/compatibility_tests/v2.5.0/more_protos/pom.xml
  4. 71
      java/compatibility_tests/v2.5.0/more_protos/src/proto/com/google/protobuf/multiple_files_test.proto
  5. 53
      java/compatibility_tests/v2.5.0/more_protos/src/proto/com/google/protobuf/nested_builders_test.proto
  6. 45
      java/compatibility_tests/v2.5.0/more_protos/src/proto/com/google/protobuf/nested_extension.proto
  7. 48
      java/compatibility_tests/v2.5.0/more_protos/src/proto/com/google/protobuf/nested_extension_lite.proto
  8. 48
      java/compatibility_tests/v2.5.0/more_protos/src/proto/com/google/protobuf/non_nested_extension.proto
  9. 50
      java/compatibility_tests/v2.5.0/more_protos/src/proto/com/google/protobuf/non_nested_extension_lite.proto
  10. 108
      java/compatibility_tests/v2.5.0/more_protos/src/proto/com/google/protobuf/test_bad_identifiers.proto
  11. 620
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/descriptor.proto
  12. 719
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest.proto
  13. 387
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_custom_options.proto
  14. 50
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_embed_optimize_for.proto
  15. 37
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_empty.proto
  16. 1046
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_enormous_descriptor.proto
  17. 64
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_import.proto
  18. 51
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_import_lite.proto
  19. 40
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_import_public.proto
  20. 42
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_import_public_lite.proto
  21. 360
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_lite.proto
  22. 43
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_lite_imports_nonlite.proto
  23. 72
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_mset.proto
  24. 52
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_no_generic_services.proto
  25. 61
      java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_optimize_for.proto
  26. 30
      java/compatibility_tests/v2.5.0/pom.xml
  27. 71
      java/compatibility_tests/v2.5.0/protos/pom.xml
  28. 71
      java/compatibility_tests/v2.5.0/protos/src/proto/com/google/protobuf/multiple_files_test.proto
  29. 53
      java/compatibility_tests/v2.5.0/protos/src/proto/com/google/protobuf/nested_builders_test.proto
  30. 45
      java/compatibility_tests/v2.5.0/protos/src/proto/com/google/protobuf/nested_extension.proto
  31. 48
      java/compatibility_tests/v2.5.0/protos/src/proto/com/google/protobuf/nested_extension_lite.proto
  32. 48
      java/compatibility_tests/v2.5.0/protos/src/proto/com/google/protobuf/non_nested_extension.proto
  33. 50
      java/compatibility_tests/v2.5.0/protos/src/proto/com/google/protobuf/non_nested_extension_lite.proto
  34. 108
      java/compatibility_tests/v2.5.0/protos/src/proto/com/google/protobuf/test_bad_identifiers.proto
  35. 620
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/descriptor.proto
  36. 719
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest.proto
  37. 387
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_custom_options.proto
  38. 50
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_embed_optimize_for.proto
  39. 37
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_empty.proto
  40. 1046
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_enormous_descriptor.proto
  41. 64
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import.proto
  42. 51
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import_lite.proto
  43. 40
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import_public.proto
  44. 42
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import_public_lite.proto
  45. 360
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_lite.proto
  46. 43
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_lite_imports_nonlite.proto
  47. 72
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_mset.proto
  48. 52
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_no_generic_services.proto
  49. 61
      java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_optimize_for.proto
  50. 115
      java/compatibility_tests/v2.5.0/test.sh
  51. 73
      java/compatibility_tests/v2.5.0/tests/pom.xml
  52. 510
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/AbstractMessageTest.java
  53. 56
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/BoundedByteStringTest.java
  54. 590
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/ByteStringTest.java
  55. 469
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/CodedInputStreamTest.java
  56. 318
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/CodedOutputStreamTest.java
  57. 81
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/DeprecatedFieldTest.java
  58. 649
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/DescriptorsTest.java
  59. 265
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/DynamicMessageTest.java
  60. 49
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/ForceFieldBuildersPreRun.java
  61. 961
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/GeneratedMessageTest.java
  62. 163
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/LazyStringArrayListTest.java
  63. 108
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/LazyStringEndToEndTest.java
  64. 344
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/LiteralByteStringTest.java
  65. 354
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/MessageTest.java
  66. 186
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/NestedBuildersTest.java
  67. 278
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/ParserTest.java
  68. 62
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/RopeByteStringSubstringTest.java
  69. 84
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/RopeByteStringTest.java
  70. 321
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/ServiceTest.java
  71. 64
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/TestBadIdentifiers.java
  72. 3068
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/TestUtil.java
  73. 536
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/TextFormatTest.java
  74. 438
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/UnknownFieldSetTest.java
  75. 153
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/UnmodifiableLazyStringListTest.java
  76. 465
      java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/WireFormatTest.java
  77. 17
      kokoro/linux/java_compatibility/build.sh
  78. 5
      kokoro/linux/java_compatibility/continuous.cfg
  79. 5
      kokoro/linux/java_compatibility/presubmit.cfg
  80. 14
      tests.sh

@ -1,50 +0,0 @@
# Protobuf Java Compatibility Tests
This directory contains tests to ensure protobuf library is compatible with
previously released versions.
## Directory Layout
For each released protobuf version we are testing compatibility with, there
is a sub-directory with the following layout (take v2.5.0 as an example):
* v2.5.0
* test.sh
* pom.xml
* protos/ - unittest protos.
* more_protos/ - unittest protos that import the ones in "protos".
* tests/ - actual Java test classes.
The testing code is extracted from regular protobuf unittests by removing:
* tests that access package private methods/classes.
* tests that are known to be broken by an intended behavior change (e.g., we
changed the parsing recursion limit from 64 to 100).
* all lite runtime tests.
It's also divided into 3 submodule with tests depending on more_protos and
more_protos depending on protos. This way we can test scenarios where only part
of the dependency is upgraded to the new version.
## How to Run The Tests
We use a shell script to drive the test of different scenarios so the test
will only run on unix-like environments. The script expects a few command
line tools to be available on PATH: git, mvn, wget, grep, sed, java.
Before running the tests, make sure you have already built the protoc binary
following [the C++ installation instructions](../../src/README.md). The test
scripts will use the built binary located at ${protobuf}/src/protoc.
To start a test, simply run the test.sh script in each version directory. For
example:
$ v2.5.0/test.sh
For each version, the test script will test:
* only upgrading protos to the new version
* only upgrading more_protos to the new version
and see whether everything builds/runs fine. Both source compatibility and
binary compatibility will be tested.

@ -1,43 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.protobuf.compatibility</groupId>
<artifactId>compatibility-test-deps</artifactId>
<version>2.5.0</version>
<name>Compatibility Test Dependencies</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymockclassextension</artifactId>
<version>2.2.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -1,69 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.google.protobuf.compatibility</groupId>
<artifactId>compatibility-test-suite</artifactId>
<version>2.5.0</version>
<relativePath>..</relativePath>
</parent>
<groupId>com.google.protobuf.compatibility</groupId>
<artifactId>compatibility-more-protos</artifactId>
<version>2.5.0</version>
<name>More protos for Compatibility test</name>
<dependencies>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${more_protos.protobuf.version}</version>
</dependency>
<dependency>
<groupId>com.google.protobuf.compatibility</groupId>
<artifactId>compatibility-protos</artifactId>
<version>2.5.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<tasks>
<mkdir dir="target/generated-sources" />
<exec executable="${more_protos.protoc.path}">
<arg value="--java_out=target/generated-sources" />
<arg value="--proto_path=src/proto" />
<arg value="src/proto/google/protobuf/unittest.proto" />
<arg value="src/proto/google/protobuf/unittest_optimize_for.proto" />
<arg value="src/proto/com/google/protobuf/multiple_files_test.proto" />
</exec>
</tasks>
<sourceRoot>target/generated-sources</sourceRoot>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,71 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
//
// A proto file which tests the java_multiple_files option.
// Some generic_services option(s) added automatically.
// See: http://go/proto2-generic-services-default
option java_generic_services = true; // auto-added
import "google/protobuf/unittest.proto";
package protobuf_unittest;
option java_multiple_files = true;
option java_outer_classname = "MultipleFilesTestProto";
message MessageWithNoOuter {
message NestedMessage {
optional int32 i = 1;
}
enum NestedEnum {
BAZ = 3;
}
optional NestedMessage nested = 1;
repeated TestAllTypes foreign = 2;
optional NestedEnum nested_enum = 3;
optional EnumWithNoOuter foreign_enum = 4;
}
enum EnumWithNoOuter {
FOO = 1;
BAR = 2;
}
service ServiceWithNoOuter {
rpc Foo(MessageWithNoOuter) returns(TestAllTypes);
}
extend TestAllExtensions {
optional int32 extension_with_outer = 1234567;
}

@ -1,53 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: jonp@google.com (Jon Perlow)
//
package protobuf_unittest;
option java_multiple_files = true;
option java_outer_classname = "NestedBuilders";
message Vehicle {
optional Engine engine = 1;
repeated Wheel wheel = 2;
}
message Engine {
optional int32 cylinder = 1;
optional int32 liters = 2;
}
message Wheel {
optional int32 radius = 1;
optional int32 width = 2;
}

@ -1,45 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: Darick Tong (darick@google.com)
//
// A proto file with nested extensions. Note that this must be defined in
// a separate file to properly test the initialization of the outer class.
import "com/google/protobuf/non_nested_extension.proto";
package protobuf_unittest;
message MyNestedExtension {
extend MessageToBeExtended {
optional MessageToBeExtended recursiveExtension = 2;
}
}

@ -1,48 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: Darick Tong (darick@google.com)
//
// A proto file with nested extensions for a MessageLite messages. Note that
// this must be defined in a separate file to properly test the initialization
// of the outer class.
package protobuf_unittest;
option optimize_for = LITE_RUNTIME;
import "com/google/protobuf/non_nested_extension_lite.proto";
message MyNestedExtensionLite {
extend MessageLiteToBeExtended {
optional MessageLiteToBeExtended recursiveExtensionLite = 3;
}
}

@ -1,48 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: Darick Tong (darick@google.com)
//
// A proto file with extensions.
package protobuf_unittest;
message MessageToBeExtended {
extensions 1 to max;
}
message MyNonNestedExtension {
}
extend MessageToBeExtended {
optional MyNonNestedExtension nonNestedExtension = 1;
}

@ -1,50 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: Darick Tong (darick@google.com)
//
// A proto file with extensions for a MessageLite messages.
package protobuf_unittest;
option optimize_for = LITE_RUNTIME;
message MessageLiteToBeExtended {
extensions 1 to max;
}
message MyNonNestedExtensionLite {
}
extend MessageLiteToBeExtended {
optional MyNonNestedExtensionLite nonNestedExtensionLite = 1;
}

@ -1,108 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: jonp@google.com (Jon Perlow)
// This file tests that various identifiers work as field and type names even
// though the same identifiers are used internally by the java code generator.
// Some generic_services option(s) added automatically.
// See: http://go/proto2-generic-services-default
option java_generic_services = true; // auto-added
package io_protocol_tests;
option java_package = "com.google.protobuf";
option java_outer_classname = "TestBadIdentifiersProto";
message TestMessage {
}
message Descriptor {
option no_standard_descriptor_accessor = true;
optional string descriptor = 1;
message NestedDescriptor {
option no_standard_descriptor_accessor = true;
optional string descriptor = 1;
}
optional NestedDescriptor nested_descriptor = 2;
}
message Parser {
enum ParserEnum {
PARSER = 1;
}
optional ParserEnum parser = 1;
}
message Deprecated {
enum TestEnum {
FOO = 1;
}
optional int32 field1 = 1 [deprecated=true];
optional TestEnum field2 = 2 [deprecated=true];
optional TestMessage field3 = 3 [deprecated=true];
}
message Override {
optional int32 override = 1;
}
message Object {
optional int32 object = 1;
optional string string_object = 2;
}
message String {
optional string string = 1;
}
message Integer {
optional int32 integer = 1;
}
message Long {
optional int32 long = 1;
}
message Float {
optional float float = 1;
}
message Double {
optional double double = 1;
}
service TestConflictingMethodNames {
rpc Override(TestMessage) returns (TestMessage);
}

@ -1,620 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// The messages in this file describe the definitions found in .proto files.
// A valid .proto file can be translated directly to a FileDescriptorProto
// without any other information (e.g. without reading its imports).
package google.protobuf;
option java_package = "com.google.protobuf";
option java_outer_classname = "DescriptorProtos";
// descriptor.proto must be optimized for speed because reflection-based
// algorithms don't work during bootstrapping.
option optimize_for = SPEED;
// The protocol compiler can output a FileDescriptorSet containing the .proto
// files it parses.
message FileDescriptorSet {
repeated FileDescriptorProto file = 1;
}
// Describes a complete .proto file.
message FileDescriptorProto {
optional string name = 1; // file name, relative to root of source tree
optional string package = 2; // e.g. "foo", "foo.bar", etc.
// Names of files imported by this file.
repeated string dependency = 3;
// Indexes of the public imported files in the dependency list above.
repeated int32 public_dependency = 10;
// Indexes of the weak imported files in the dependency list.
// For Google-internal migration only. Do not use.
repeated int32 weak_dependency = 11;
// All top-level definitions in this file.
repeated DescriptorProto message_type = 4;
repeated EnumDescriptorProto enum_type = 5;
repeated ServiceDescriptorProto service = 6;
repeated FieldDescriptorProto extension = 7;
optional FileOptions options = 8;
// This field contains optional information about the original source code.
// You may safely remove this entire field without harming runtime
// functionality of the descriptors -- the information is needed only by
// development tools.
optional SourceCodeInfo source_code_info = 9;
}
// Describes a message type.
message DescriptorProto {
optional string name = 1;
repeated FieldDescriptorProto field = 2;
repeated FieldDescriptorProto extension = 6;
repeated DescriptorProto nested_type = 3;
repeated EnumDescriptorProto enum_type = 4;
message ExtensionRange {
optional int32 start = 1;
optional int32 end = 2;
}
repeated ExtensionRange extension_range = 5;
optional MessageOptions options = 7;
}
// Describes a field within a message.
message FieldDescriptorProto {
enum Type {
// 0 is reserved for errors.
// Order is weird for historical reasons.
TYPE_DOUBLE = 1;
TYPE_FLOAT = 2;
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
// negative values are likely.
TYPE_INT64 = 3;
TYPE_UINT64 = 4;
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
// negative values are likely.
TYPE_INT32 = 5;
TYPE_FIXED64 = 6;
TYPE_FIXED32 = 7;
TYPE_BOOL = 8;
TYPE_STRING = 9;
TYPE_GROUP = 10; // Tag-delimited aggregate.
TYPE_MESSAGE = 11; // Length-delimited aggregate.
// New in version 2.
TYPE_BYTES = 12;
TYPE_UINT32 = 13;
TYPE_ENUM = 14;
TYPE_SFIXED32 = 15;
TYPE_SFIXED64 = 16;
TYPE_SINT32 = 17; // Uses ZigZag encoding.
TYPE_SINT64 = 18; // Uses ZigZag encoding.
};
enum Label {
// 0 is reserved for errors
LABEL_OPTIONAL = 1;
LABEL_REQUIRED = 2;
LABEL_REPEATED = 3;
// TODO(sanjay): Should we add LABEL_MAP?
};
optional string name = 1;
optional int32 number = 3;
optional Label label = 4;
// If type_name is set, this need not be set. If both this and type_name
// are set, this must be either TYPE_ENUM or TYPE_MESSAGE.
optional Type type = 5;
// For message and enum types, this is the name of the type. If the name
// starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
// rules are used to find the type (i.e. first the nested types within this
// message are searched, then within the parent, on up to the root
// namespace).
optional string type_name = 6;
// For extensions, this is the name of the type being extended. It is
// resolved in the same manner as type_name.
optional string extendee = 2;
// For numeric types, contains the original text representation of the value.
// For booleans, "true" or "false".
// For strings, contains the default text contents (not escaped in any way).
// For bytes, contains the C escaped value. All bytes >= 128 are escaped.
// TODO(kenton): Base-64 encode?
optional string default_value = 7;
optional FieldOptions options = 8;
}
// Describes an enum type.
message EnumDescriptorProto {
optional string name = 1;
repeated EnumValueDescriptorProto value = 2;
optional EnumOptions options = 3;
}
// Describes a value within an enum.
message EnumValueDescriptorProto {
optional string name = 1;
optional int32 number = 2;
optional EnumValueOptions options = 3;
}
// Describes a service.
message ServiceDescriptorProto {
optional string name = 1;
repeated MethodDescriptorProto method = 2;
optional ServiceOptions options = 3;
}
// Describes a method of a service.
message MethodDescriptorProto {
optional string name = 1;
// Input and output type names. These are resolved in the same way as
// FieldDescriptorProto.type_name, but must refer to a message type.
optional string input_type = 2;
optional string output_type = 3;
optional MethodOptions options = 4;
}
// ===================================================================
// Options
// Each of the definitions above may have "options" attached. These are
// just annotations which may cause code to be generated slightly differently
// or may contain hints for code that manipulates protocol messages.
//
// Clients may define custom options as extensions of the *Options messages.
// These extensions may not yet be known at parsing time, so the parser cannot
// store the values in them. Instead it stores them in a field in the *Options
// message called uninterpreted_option. This field must have the same name
// across all *Options messages. We then use this field to populate the
// extensions when we build a descriptor, at which point all protos have been
// parsed and so all extensions are known.
//
// Extension numbers for custom options may be chosen as follows:
// * For options which will only be used within a single application or
// organization, or for experimental options, use field numbers 50000
// through 99999. It is up to you to ensure that you do not use the
// same number for multiple options.
// * For options which will be published and used publicly by multiple
// independent entities, e-mail protobuf-global-extension-registry@google.com
// to reserve extension numbers. Simply provide your project name (e.g.
// Object-C plugin) and your project website (if available) -- there's no need
// to explain how you intend to use them. Usually you only need one extension
// number. You can declare multiple options with only one extension number by
// putting them in a sub-message. See the Custom Options section of the docs
// for examples:
// http://code.google.com/apis/protocolbuffers/docs/proto.html#options
// If this turns out to be popular, a web service will be set up
// to automatically assign option numbers.
message FileOptions {
// Sets the Java package where classes generated from this .proto will be
// placed. By default, the proto package is used, but this is often
// inappropriate because proto packages do not normally start with backwards
// domain names.
optional string java_package = 1;
// If set, all the classes from the .proto file are wrapped in a single
// outer class with the given name. This applies to both Proto1
// (equivalent to the old "--one_java_file" option) and Proto2 (where
// a .proto always translates to a single class, but you may want to
// explicitly choose the class name).
optional string java_outer_classname = 8;
// If set true, then the Java code generator will generate a separate .java
// file for each top-level message, enum, and service defined in the .proto
// file. Thus, these types will *not* be nested inside the outer class
// named by java_outer_classname. However, the outer class will still be
// generated to contain the file's getDescriptor() method as well as any
// top-level extensions defined in the file.
optional bool java_multiple_files = 10 [default=false];
// If set true, then the Java code generator will generate equals() and
// hashCode() methods for all messages defined in the .proto file. This is
// purely a speed optimization, as the AbstractMessage base class includes
// reflection-based implementations of these methods.
optional bool java_generate_equals_and_hash = 20 [default=false];
// Generated classes can be optimized for speed or code size.
enum OptimizeMode {
SPEED = 1; // Generate complete code for parsing, serialization,
// etc.
CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
}
optional OptimizeMode optimize_for = 9 [default=SPEED];
// Sets the Go package where structs generated from this .proto will be
// placed. There is no default.
optional string go_package = 11;
// Should generic services be generated in each language? "Generic" services
// are not specific to any particular RPC system. They are generated by the
// main code generators in each language (without additional plugins).
// Generic services were the only kind of service generation supported by
// early versions of proto2.
//
// Generic services are now considered deprecated in favor of using plugins
// that generate code specific to your particular RPC system. Therefore,
// these default to false. Old code which depends on generic services should
// explicitly set them to true.
optional bool cc_generic_services = 16 [default=false];
optional bool java_generic_services = 17 [default=false];
optional bool py_generic_services = 18 [default=false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message MessageOptions {
// Set true to use the old proto1 MessageSet wire format for extensions.
// This is provided for backwards-compatibility with the MessageSet wire
// format. You should not use this for any other reason: It's less
// efficient, has fewer features, and is more complicated.
//
// The message must be defined exactly as follows:
// message Foo {
// option message_set_wire_format = true;
// extensions 4 to max;
// }
// Note that the message cannot have any defined fields; MessageSets only
// have extensions.
//
// All extensions of your type must be singular messages; e.g. they cannot
// be int32s, enums, or repeated messages.
//
// Because this is an option, the above two restrictions are not enforced by
// the protocol compiler.
optional bool message_set_wire_format = 1 [default=false];
// Disables the generation of the standard "descriptor()" accessor, which can
// conflict with a field of the same name. This is meant to make migration
// from proto1 easier; new code should avoid fields named "descriptor".
optional bool no_standard_descriptor_accessor = 2 [default=false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message FieldOptions {
// The ctype option instructs the C++ code generator to use a different
// representation of the field than it normally would. See the specific
// options below. This option is not yet implemented in the open source
// release -- sorry, we'll try to include it in a future version!
optional CType ctype = 1 [default = STRING];
enum CType {
// Default mode.
STRING = 0;
CORD = 1;
STRING_PIECE = 2;
}
// The packed option can be enabled for repeated primitive fields to enable
// a more efficient representation on the wire. Rather than repeatedly
// writing the tag and type for each element, the entire array is encoded as
// a single length-delimited blob.
optional bool packed = 2;
// Should this field be parsed lazily? Lazy applies only to message-type
// fields. It means that when the outer message is initially parsed, the
// inner message's contents will not be parsed but instead stored in encoded
// form. The inner message will actually be parsed when it is first accessed.
//
// This is only a hint. Implementations are free to choose whether to use
// eager or lazy parsing regardless of the value of this option. However,
// setting this option true suggests that the protocol author believes that
// using lazy parsing on this field is worth the additional bookkeeping
// overhead typically needed to implement it.
//
// This option does not affect the public interface of any generated code;
// all method signatures remain the same. Furthermore, thread-safety of the
// interface is not affected by this option; const methods remain safe to
// call from multiple threads concurrently, while non-const methods continue
// to require exclusive access.
//
//
// Note that implementations may choose not to check required fields within
// a lazy sub-message. That is, calling IsInitialized() on the outher message
// may return true even if the inner message has missing required fields.
// This is necessary because otherwise the inner message would have to be
// parsed in order to perform the check, defeating the purpose of lazy
// parsing. An implementation which chooses not to check required fields
// must be consistent about it. That is, for any particular sub-message, the
// implementation must either *always* check its required fields, or *never*
// check its required fields, regardless of whether or not the message has
// been parsed.
optional bool lazy = 5 [default=false];
// Is this field deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for accessors, or it will be completely ignored; in the very least, this
// is a formalization for deprecating fields.
optional bool deprecated = 3 [default=false];
// EXPERIMENTAL. DO NOT USE.
// For "map" fields, the name of the field in the enclosed type that
// is the key for this map. For example, suppose we have:
// message Item {
// required string name = 1;
// required string value = 2;
// }
// message Config {
// repeated Item items = 1 [experimental_map_key="name"];
// }
// In this situation, the map key for Item will be set to "name".
// TODO: Fully-implement this, then remove the "experimental_" prefix.
optional string experimental_map_key = 9;
// For Google-internal migration only. Do not use.
optional bool weak = 10 [default=false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message EnumOptions {
// Set this option to false to disallow mapping different tag names to a same
// value.
optional bool allow_alias = 2 [default=true];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message EnumValueOptions {
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message ServiceOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message MethodOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
// A message representing a option the parser does not recognize. This only
// appears in options protos created by the compiler::Parser class.
// DescriptorPool resolves these when building Descriptor objects. Therefore,
// options protos in descriptor objects (e.g. returned by Descriptor::options(),
// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
// in them.
message UninterpretedOption {
// The name of the uninterpreted option. Each string represents a segment in
// a dot-separated name. is_extension is true iff a segment represents an
// extension (denoted with parentheses in options specs in .proto files).
// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
// "foo.(bar.baz).qux".
message NamePart {
required string name_part = 1;
required bool is_extension = 2;
}
repeated NamePart name = 2;
// The value of the uninterpreted option, in whatever type the tokenizer
// identified it as during parsing. Exactly one of these should be set.
optional string identifier_value = 3;
optional uint64 positive_int_value = 4;
optional int64 negative_int_value = 5;
optional double double_value = 6;
optional bytes string_value = 7;
optional string aggregate_value = 8;
}
// ===================================================================
// Optional source code info
// Encapsulates information about the original source file from which a
// FileDescriptorProto was generated.
message SourceCodeInfo {
// A Location identifies a piece of source code in a .proto file which
// corresponds to a particular definition. This information is intended
// to be useful to IDEs, code indexers, documentation generators, and similar
// tools.
//
// For example, say we have a file like:
// message Foo {
// optional string foo = 1;
// }
// Let's look at just the field definition:
// optional string foo = 1;
// ^ ^^ ^^ ^ ^^^
// a bc de f ghi
// We have the following locations:
// span path represents
// [a,i) [ 4, 0, 2, 0 ] The whole field definition.
// [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
// [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
// [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
// [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
//
// Notes:
// - A location may refer to a repeated field itself (i.e. not to any
// particular index within it). This is used whenever a set of elements are
// logically enclosed in a single code segment. For example, an entire
// extend block (possibly containing multiple extension definitions) will
// have an outer location whose path refers to the "extensions" repeated
// field without an index.
// - Multiple locations may have the same path. This happens when a single
// logical declaration is spread out across multiple places. The most
// obvious example is the "extend" block again -- there may be multiple
// extend blocks in the same scope, each of which will have the same path.
// - A location's span is not always a subset of its parent's span. For
// example, the "extendee" of an extension declaration appears at the
// beginning of the "extend" block and is shared by all extensions within
// the block.
// - Just because a location's span is a subset of some other location's span
// does not mean that it is a descendent. For example, a "group" defines
// both a type and a field in a single declaration. Thus, the locations
// corresponding to the type and field and their components will overlap.
// - Code which tries to interpret locations should probably be designed to
// ignore those that it doesn't understand, as more types of locations could
// be recorded in the future.
repeated Location location = 1;
message Location {
// Identifies which part of the FileDescriptorProto was defined at this
// location.
//
// Each element is a field number or an index. They form a path from
// the root FileDescriptorProto to the place where the definition. For
// example, this path:
// [ 4, 3, 2, 7, 1 ]
// refers to:
// file.message_type(3) // 4, 3
// .field(7) // 2, 7
// .name() // 1
// This is because FileDescriptorProto.message_type has field number 4:
// repeated DescriptorProto message_type = 4;
// and DescriptorProto.field has field number 2:
// repeated FieldDescriptorProto field = 2;
// and FieldDescriptorProto.name has field number 1:
// optional string name = 1;
//
// Thus, the above path gives the location of a field name. If we removed
// the last element:
// [ 4, 3, 2, 7 ]
// this path refers to the whole field declaration (from the beginning
// of the label to the terminating semicolon).
repeated int32 path = 1 [packed=true];
// Always has exactly three or four elements: start line, start column,
// end line (optional, otherwise assumed same as start line), end column.
// These are packed into a single field for efficiency. Note that line
// and column numbers are zero-based -- typically you will want to add
// 1 to each before displaying to a user.
repeated int32 span = 2 [packed=true];
// If this SourceCodeInfo represents a complete declaration, these are any
// comments appearing before and after the declaration which appear to be
// attached to the declaration.
//
// A series of line comments appearing on consecutive lines, with no other
// tokens appearing on those lines, will be treated as a single comment.
//
// Only the comment content is provided; comment markers (e.g. //) are
// stripped out. For block comments, leading whitespace and an asterisk
// will be stripped from the beginning of each line other than the first.
// Newlines are included in the output.
//
// Examples:
//
// optional int32 foo = 1; // Comment attached to foo.
// // Comment attached to bar.
// optional int32 bar = 2;
//
// optional string baz = 3;
// // Comment attached to baz.
// // Another line attached to baz.
//
// // Comment attached to qux.
// //
// // Another line attached to qux.
// optional double qux = 4;
//
// optional string corge = 5;
// /* Block comment attached
// * to corge. Leading asterisks
// * will be removed. */
// /* Block comment attached to
// * grault. */
// optional int32 grault = 6;
optional string leading_comments = 3;
optional string trailing_comments = 4;
}
}

@ -1,719 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file we will use for unit testing.
// Some generic_services option(s) added automatically.
// See: http://go/proto2-generic-services-default
option cc_generic_services = true; // auto-added
option java_generic_services = true; // auto-added
option py_generic_services = true; // auto-added
import "google/protobuf/unittest_import.proto";
// We don't put this in a package within proto2 because we need to make sure
// that the generated code doesn't depend on being in the proto2 namespace.
// In test_util.h we do "using namespace unittest = protobuf_unittest".
package protobuf_unittest;
// Protos optimized for SPEED use a strict superset of the generated code
// of equivalent ones optimized for CODE_SIZE, so we should optimize all our
// tests for speed unless explicitly testing code size optimization.
option optimize_for = SPEED;
option java_outer_classname = "UnittestProto";
// This proto includes every type of field in both singular and repeated
// forms.
message TestAllTypes {
message NestedMessage {
// The field name "b" fails to compile in proto1 because it conflicts with
// a local variable named "b" in one of the generated methods. Doh.
// This file needs to compile in proto1 to test backwards-compatibility.
optional int32 bb = 1;
}
enum NestedEnum {
FOO = 1;
BAR = 2;
BAZ = 3;
}
// Singular
optional int32 optional_int32 = 1;
optional int64 optional_int64 = 2;
optional uint32 optional_uint32 = 3;
optional uint64 optional_uint64 = 4;
optional sint32 optional_sint32 = 5;
optional sint64 optional_sint64 = 6;
optional fixed32 optional_fixed32 = 7;
optional fixed64 optional_fixed64 = 8;
optional sfixed32 optional_sfixed32 = 9;
optional sfixed64 optional_sfixed64 = 10;
optional float optional_float = 11;
optional double optional_double = 12;
optional bool optional_bool = 13;
optional string optional_string = 14;
optional bytes optional_bytes = 15;
optional group OptionalGroup = 16 {
optional int32 a = 17;
}
optional NestedMessage optional_nested_message = 18;
optional ForeignMessage optional_foreign_message = 19;
optional protobuf_unittest_import.ImportMessage optional_import_message = 20;
optional NestedEnum optional_nested_enum = 21;
optional ForeignEnum optional_foreign_enum = 22;
optional protobuf_unittest_import.ImportEnum optional_import_enum = 23;
optional string optional_string_piece = 24 [ctype=STRING_PIECE];
optional string optional_cord = 25 [ctype=CORD];
// Defined in unittest_import_public.proto
optional protobuf_unittest_import.PublicImportMessage
optional_public_import_message = 26;
optional NestedMessage optional_lazy_message = 27 [lazy=true];
// Repeated
repeated int32 repeated_int32 = 31;
repeated int64 repeated_int64 = 32;
repeated uint32 repeated_uint32 = 33;
repeated uint64 repeated_uint64 = 34;
repeated sint32 repeated_sint32 = 35;
repeated sint64 repeated_sint64 = 36;
repeated fixed32 repeated_fixed32 = 37;
repeated fixed64 repeated_fixed64 = 38;
repeated sfixed32 repeated_sfixed32 = 39;
repeated sfixed64 repeated_sfixed64 = 40;
repeated float repeated_float = 41;
repeated double repeated_double = 42;
repeated bool repeated_bool = 43;
repeated string repeated_string = 44;
repeated bytes repeated_bytes = 45;
repeated group RepeatedGroup = 46 {
optional int32 a = 47;
}
repeated NestedMessage repeated_nested_message = 48;
repeated ForeignMessage repeated_foreign_message = 49;
repeated protobuf_unittest_import.ImportMessage repeated_import_message = 50;
repeated NestedEnum repeated_nested_enum = 51;
repeated ForeignEnum repeated_foreign_enum = 52;
repeated protobuf_unittest_import.ImportEnum repeated_import_enum = 53;
repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
repeated string repeated_cord = 55 [ctype=CORD];
repeated NestedMessage repeated_lazy_message = 57 [lazy=true];
// Singular with defaults
optional int32 default_int32 = 61 [default = 41 ];
optional int64 default_int64 = 62 [default = 42 ];
optional uint32 default_uint32 = 63 [default = 43 ];
optional uint64 default_uint64 = 64 [default = 44 ];
optional sint32 default_sint32 = 65 [default = -45 ];
optional sint64 default_sint64 = 66 [default = 46 ];
optional fixed32 default_fixed32 = 67 [default = 47 ];
optional fixed64 default_fixed64 = 68 [default = 48 ];
optional sfixed32 default_sfixed32 = 69 [default = 49 ];
optional sfixed64 default_sfixed64 = 70 [default = -50 ];
optional float default_float = 71 [default = 51.5 ];
optional double default_double = 72 [default = 52e3 ];
optional bool default_bool = 73 [default = true ];
optional string default_string = 74 [default = "hello"];
optional bytes default_bytes = 75 [default = "world"];
optional NestedEnum default_nested_enum = 81 [default = BAR ];
optional ForeignEnum default_foreign_enum = 82 [default = FOREIGN_BAR];
optional protobuf_unittest_import.ImportEnum
default_import_enum = 83 [default = IMPORT_BAR];
optional string default_string_piece = 84 [ctype=STRING_PIECE,default="abc"];
optional string default_cord = 85 [ctype=CORD,default="123"];
}
message TestDeprecatedFields {
optional int32 deprecated_int32 = 1 [deprecated=true];
}
// Define these after TestAllTypes to make sure the compiler can handle
// that.
message ForeignMessage {
optional int32 c = 1;
}
enum ForeignEnum {
FOREIGN_FOO = 4;
FOREIGN_BAR = 5;
FOREIGN_BAZ = 6;
}
message TestAllExtensions {
extensions 1 to max;
}
extend TestAllExtensions {
// Singular
optional int32 optional_int32_extension = 1;
optional int64 optional_int64_extension = 2;
optional uint32 optional_uint32_extension = 3;
optional uint64 optional_uint64_extension = 4;
optional sint32 optional_sint32_extension = 5;
optional sint64 optional_sint64_extension = 6;
optional fixed32 optional_fixed32_extension = 7;
optional fixed64 optional_fixed64_extension = 8;
optional sfixed32 optional_sfixed32_extension = 9;
optional sfixed64 optional_sfixed64_extension = 10;
optional float optional_float_extension = 11;
optional double optional_double_extension = 12;
optional bool optional_bool_extension = 13;
optional string optional_string_extension = 14;
optional bytes optional_bytes_extension = 15;
optional group OptionalGroup_extension = 16 {
optional int32 a = 17;
}
optional TestAllTypes.NestedMessage optional_nested_message_extension = 18;
optional ForeignMessage optional_foreign_message_extension = 19;
optional protobuf_unittest_import.ImportMessage
optional_import_message_extension = 20;
optional TestAllTypes.NestedEnum optional_nested_enum_extension = 21;
optional ForeignEnum optional_foreign_enum_extension = 22;
optional protobuf_unittest_import.ImportEnum
optional_import_enum_extension = 23;
optional string optional_string_piece_extension = 24 [ctype=STRING_PIECE];
optional string optional_cord_extension = 25 [ctype=CORD];
optional protobuf_unittest_import.PublicImportMessage
optional_public_import_message_extension = 26;
optional TestAllTypes.NestedMessage
optional_lazy_message_extension = 27 [lazy=true];
// Repeated
repeated int32 repeated_int32_extension = 31;
repeated int64 repeated_int64_extension = 32;
repeated uint32 repeated_uint32_extension = 33;
repeated uint64 repeated_uint64_extension = 34;
repeated sint32 repeated_sint32_extension = 35;
repeated sint64 repeated_sint64_extension = 36;
repeated fixed32 repeated_fixed32_extension = 37;
repeated fixed64 repeated_fixed64_extension = 38;
repeated sfixed32 repeated_sfixed32_extension = 39;
repeated sfixed64 repeated_sfixed64_extension = 40;
repeated float repeated_float_extension = 41;
repeated double repeated_double_extension = 42;
repeated bool repeated_bool_extension = 43;
repeated string repeated_string_extension = 44;
repeated bytes repeated_bytes_extension = 45;
repeated group RepeatedGroup_extension = 46 {
optional int32 a = 47;
}
repeated TestAllTypes.NestedMessage repeated_nested_message_extension = 48;
repeated ForeignMessage repeated_foreign_message_extension = 49;
repeated protobuf_unittest_import.ImportMessage
repeated_import_message_extension = 50;
repeated TestAllTypes.NestedEnum repeated_nested_enum_extension = 51;
repeated ForeignEnum repeated_foreign_enum_extension = 52;
repeated protobuf_unittest_import.ImportEnum
repeated_import_enum_extension = 53;
repeated string repeated_string_piece_extension = 54 [ctype=STRING_PIECE];
repeated string repeated_cord_extension = 55 [ctype=CORD];
repeated TestAllTypes.NestedMessage
repeated_lazy_message_extension = 57 [lazy=true];
// Singular with defaults
optional int32 default_int32_extension = 61 [default = 41 ];
optional int64 default_int64_extension = 62 [default = 42 ];
optional uint32 default_uint32_extension = 63 [default = 43 ];
optional uint64 default_uint64_extension = 64 [default = 44 ];
optional sint32 default_sint32_extension = 65 [default = -45 ];
optional sint64 default_sint64_extension = 66 [default = 46 ];
optional fixed32 default_fixed32_extension = 67 [default = 47 ];
optional fixed64 default_fixed64_extension = 68 [default = 48 ];
optional sfixed32 default_sfixed32_extension = 69 [default = 49 ];
optional sfixed64 default_sfixed64_extension = 70 [default = -50 ];
optional float default_float_extension = 71 [default = 51.5 ];
optional double default_double_extension = 72 [default = 52e3 ];
optional bool default_bool_extension = 73 [default = true ];
optional string default_string_extension = 74 [default = "hello"];
optional bytes default_bytes_extension = 75 [default = "world"];
optional TestAllTypes.NestedEnum
default_nested_enum_extension = 81 [default = BAR];
optional ForeignEnum
default_foreign_enum_extension = 82 [default = FOREIGN_BAR];
optional protobuf_unittest_import.ImportEnum
default_import_enum_extension = 83 [default = IMPORT_BAR];
optional string default_string_piece_extension = 84 [ctype=STRING_PIECE,
default="abc"];
optional string default_cord_extension = 85 [ctype=CORD, default="123"];
}
message TestNestedExtension {
extend TestAllExtensions {
// Check for bug where string extensions declared in tested scope did not
// compile.
optional string test = 1002 [default="test"];
}
}
// We have separate messages for testing required fields because it's
// annoying to have to fill in required fields in TestProto in order to
// do anything with it. Note that we don't need to test every type of
// required filed because the code output is basically identical to
// optional fields for all types.
message TestRequired {
required int32 a = 1;
optional int32 dummy2 = 2;
required int32 b = 3;
extend TestAllExtensions {
optional TestRequired single = 1000;
repeated TestRequired multi = 1001;
}
// Pad the field count to 32 so that we can test that IsInitialized()
// properly checks multiple elements of has_bits_.
optional int32 dummy4 = 4;
optional int32 dummy5 = 5;
optional int32 dummy6 = 6;
optional int32 dummy7 = 7;
optional int32 dummy8 = 8;
optional int32 dummy9 = 9;
optional int32 dummy10 = 10;
optional int32 dummy11 = 11;
optional int32 dummy12 = 12;
optional int32 dummy13 = 13;
optional int32 dummy14 = 14;
optional int32 dummy15 = 15;
optional int32 dummy16 = 16;
optional int32 dummy17 = 17;
optional int32 dummy18 = 18;
optional int32 dummy19 = 19;
optional int32 dummy20 = 20;
optional int32 dummy21 = 21;
optional int32 dummy22 = 22;
optional int32 dummy23 = 23;
optional int32 dummy24 = 24;
optional int32 dummy25 = 25;
optional int32 dummy26 = 26;
optional int32 dummy27 = 27;
optional int32 dummy28 = 28;
optional int32 dummy29 = 29;
optional int32 dummy30 = 30;
optional int32 dummy31 = 31;
optional int32 dummy32 = 32;
required int32 c = 33;
}
message TestRequiredForeign {
optional TestRequired optional_message = 1;
repeated TestRequired repeated_message = 2;
optional int32 dummy = 3;
}
// Test that we can use NestedMessage from outside TestAllTypes.
message TestForeignNested {
optional TestAllTypes.NestedMessage foreign_nested = 1;
}
// TestEmptyMessage is used to test unknown field support.
message TestEmptyMessage {
}
// Like above, but declare all field numbers as potential extensions. No
// actual extensions should ever be defined for this type.
message TestEmptyMessageWithExtensions {
extensions 1 to max;
}
message TestMultipleExtensionRanges {
extensions 42;
extensions 4143 to 4243;
extensions 65536 to max;
}
// Test that really large tag numbers don't break anything.
message TestReallyLargeTagNumber {
// The largest possible tag number is 2^28 - 1, since the wire format uses
// three bits to communicate wire type.
optional int32 a = 1;
optional int32 bb = 268435455;
}
message TestRecursiveMessage {
optional TestRecursiveMessage a = 1;
optional int32 i = 2;
}
// Test that mutual recursion works.
message TestMutualRecursionA {
optional TestMutualRecursionB bb = 1;
}
message TestMutualRecursionB {
optional TestMutualRecursionA a = 1;
optional int32 optional_int32 = 2;
}
// Test that groups have disjoint field numbers from their siblings and
// parents. This is NOT possible in proto1; only proto2. When attempting
// to compile with proto1, this will emit an error; so we only include it
// in protobuf_unittest_proto.
message TestDupFieldNumber { // NO_PROTO1
optional int32 a = 1; // NO_PROTO1
optional group Foo = 2 { optional int32 a = 1; } // NO_PROTO1
optional group Bar = 3 { optional int32 a = 1; } // NO_PROTO1
} // NO_PROTO1
// Additional messages for testing lazy fields.
message TestEagerMessage {
optional TestAllTypes sub_message = 1 [lazy=false];
}
message TestLazyMessage {
optional TestAllTypes sub_message = 1 [lazy=true];
}
// Needed for a Python test.
message TestNestedMessageHasBits {
message NestedMessage {
repeated int32 nestedmessage_repeated_int32 = 1;
repeated ForeignMessage nestedmessage_repeated_foreignmessage = 2;
}
optional NestedMessage optional_nested_message = 1;
}
// Test an enum that has multiple values with the same number.
enum TestEnumWithDupValue {
option allow_alias = true;
FOO1 = 1;
BAR1 = 2;
BAZ = 3;
FOO2 = 1;
BAR2 = 2;
}
// Test an enum with large, unordered values.
enum TestSparseEnum {
SPARSE_A = 123;
SPARSE_B = 62374;
SPARSE_C = 12589234;
SPARSE_D = -15;
SPARSE_E = -53452;
SPARSE_F = 0;
SPARSE_G = 2;
}
// Test message with CamelCase field names. This violates Protocol Buffer
// standard style.
message TestCamelCaseFieldNames {
optional int32 PrimitiveField = 1;
optional string StringField = 2;
optional ForeignEnum EnumField = 3;
optional ForeignMessage MessageField = 4;
optional string StringPieceField = 5 [ctype=STRING_PIECE];
optional string CordField = 6 [ctype=CORD];
repeated int32 RepeatedPrimitiveField = 7;
repeated string RepeatedStringField = 8;
repeated ForeignEnum RepeatedEnumField = 9;
repeated ForeignMessage RepeatedMessageField = 10;
repeated string RepeatedStringPieceField = 11 [ctype=STRING_PIECE];
repeated string RepeatedCordField = 12 [ctype=CORD];
}
// We list fields out of order, to ensure that we're using field number and not
// field index to determine serialization order.
message TestFieldOrderings {
optional string my_string = 11;
extensions 2 to 10;
optional int64 my_int = 1;
extensions 12 to 100;
optional float my_float = 101;
}
extend TestFieldOrderings {
optional string my_extension_string = 50;
optional int32 my_extension_int = 5;
}
message TestExtremeDefaultValues {
optional bytes escaped_bytes = 1 [default = "\0\001\a\b\f\n\r\t\v\\\'\"\xfe"];
optional uint32 large_uint32 = 2 [default = 0xFFFFFFFF];
optional uint64 large_uint64 = 3 [default = 0xFFFFFFFFFFFFFFFF];
optional int32 small_int32 = 4 [default = -0x7FFFFFFF];
optional int64 small_int64 = 5 [default = -0x7FFFFFFFFFFFFFFF];
optional int32 really_small_int32 = 21 [default = -0x80000000];
optional int64 really_small_int64 = 22 [default = -0x8000000000000000];
// The default value here is UTF-8 for "\u1234". (We could also just type
// the UTF-8 text directly into this text file rather than escape it, but
// lots of people use editors that would be confused by this.)
optional string utf8_string = 6 [default = "\341\210\264"];
// Tests for single-precision floating-point values.
optional float zero_float = 7 [default = 0];
optional float one_float = 8 [default = 1];
optional float small_float = 9 [default = 1.5];
optional float negative_one_float = 10 [default = -1];
optional float negative_float = 11 [default = -1.5];
// Using exponents
optional float large_float = 12 [default = 2E8];
optional float small_negative_float = 13 [default = -8e-28];
// Text for nonfinite floating-point values.
optional double inf_double = 14 [default = inf];
optional double neg_inf_double = 15 [default = -inf];
optional double nan_double = 16 [default = nan];
optional float inf_float = 17 [default = inf];
optional float neg_inf_float = 18 [default = -inf];
optional float nan_float = 19 [default = nan];
// Tests for C++ trigraphs.
// Trigraphs should be escaped in C++ generated files, but they should not be
// escaped for other languages.
// Note that in .proto file, "\?" is a valid way to escape ? in string
// literals.
optional string cpp_trigraph = 20 [default = "? \? ?? \?? \??? ??/ ?\?-"];
// String defaults containing the character '\000'
optional string string_with_zero = 23 [default = "hel\000lo"];
optional bytes bytes_with_zero = 24 [default = "wor\000ld"];
optional string string_piece_with_zero = 25 [ctype=STRING_PIECE,
default="ab\000c"];
optional string cord_with_zero = 26 [ctype=CORD,
default="12\0003"];
}
message SparseEnumMessage {
optional TestSparseEnum sparse_enum = 1;
}
// Test String and Bytes: string is for valid UTF-8 strings
message OneString {
optional string data = 1;
}
message MoreString {
repeated string data = 1;
}
message OneBytes {
optional bytes data = 1;
}
message MoreBytes {
repeated bytes data = 1;
}
// Test messages for packed fields
message TestPackedTypes {
repeated int32 packed_int32 = 90 [packed = true];
repeated int64 packed_int64 = 91 [packed = true];
repeated uint32 packed_uint32 = 92 [packed = true];
repeated uint64 packed_uint64 = 93 [packed = true];
repeated sint32 packed_sint32 = 94 [packed = true];
repeated sint64 packed_sint64 = 95 [packed = true];
repeated fixed32 packed_fixed32 = 96 [packed = true];
repeated fixed64 packed_fixed64 = 97 [packed = true];
repeated sfixed32 packed_sfixed32 = 98 [packed = true];
repeated sfixed64 packed_sfixed64 = 99 [packed = true];
repeated float packed_float = 100 [packed = true];
repeated double packed_double = 101 [packed = true];
repeated bool packed_bool = 102 [packed = true];
repeated ForeignEnum packed_enum = 103 [packed = true];
}
// A message with the same fields as TestPackedTypes, but without packing. Used
// to test packed <-> unpacked wire compatibility.
message TestUnpackedTypes {
repeated int32 unpacked_int32 = 90 [packed = false];
repeated int64 unpacked_int64 = 91 [packed = false];
repeated uint32 unpacked_uint32 = 92 [packed = false];
repeated uint64 unpacked_uint64 = 93 [packed = false];
repeated sint32 unpacked_sint32 = 94 [packed = false];
repeated sint64 unpacked_sint64 = 95 [packed = false];
repeated fixed32 unpacked_fixed32 = 96 [packed = false];
repeated fixed64 unpacked_fixed64 = 97 [packed = false];
repeated sfixed32 unpacked_sfixed32 = 98 [packed = false];
repeated sfixed64 unpacked_sfixed64 = 99 [packed = false];
repeated float unpacked_float = 100 [packed = false];
repeated double unpacked_double = 101 [packed = false];
repeated bool unpacked_bool = 102 [packed = false];
repeated ForeignEnum unpacked_enum = 103 [packed = false];
}
message TestPackedExtensions {
extensions 1 to max;
}
extend TestPackedExtensions {
repeated int32 packed_int32_extension = 90 [packed = true];
repeated int64 packed_int64_extension = 91 [packed = true];
repeated uint32 packed_uint32_extension = 92 [packed = true];
repeated uint64 packed_uint64_extension = 93 [packed = true];
repeated sint32 packed_sint32_extension = 94 [packed = true];
repeated sint64 packed_sint64_extension = 95 [packed = true];
repeated fixed32 packed_fixed32_extension = 96 [packed = true];
repeated fixed64 packed_fixed64_extension = 97 [packed = true];
repeated sfixed32 packed_sfixed32_extension = 98 [packed = true];
repeated sfixed64 packed_sfixed64_extension = 99 [packed = true];
repeated float packed_float_extension = 100 [packed = true];
repeated double packed_double_extension = 101 [packed = true];
repeated bool packed_bool_extension = 102 [packed = true];
repeated ForeignEnum packed_enum_extension = 103 [packed = true];
}
// Used by ExtensionSetTest/DynamicExtensions. The test actually builds
// a set of extensions to TestAllExtensions dynamically, based on the fields
// of this message type.
message TestDynamicExtensions {
enum DynamicEnumType {
DYNAMIC_FOO = 2200;
DYNAMIC_BAR = 2201;
DYNAMIC_BAZ = 2202;
}
message DynamicMessageType {
optional int32 dynamic_field = 2100;
}
optional fixed32 scalar_extension = 2000;
optional ForeignEnum enum_extension = 2001;
optional DynamicEnumType dynamic_enum_extension = 2002;
optional ForeignMessage message_extension = 2003;
optional DynamicMessageType dynamic_message_extension = 2004;
repeated string repeated_extension = 2005;
repeated sint32 packed_extension = 2006 [packed = true];
}
message TestRepeatedScalarDifferentTagSizes {
// Parsing repeated fixed size values used to fail. This message needs to be
// used in order to get a tag of the right size; all of the repeated fields
// in TestAllTypes didn't trigger the check.
repeated fixed32 repeated_fixed32 = 12;
// Check for a varint type, just for good measure.
repeated int32 repeated_int32 = 13;
// These have two-byte tags.
repeated fixed64 repeated_fixed64 = 2046;
repeated int64 repeated_int64 = 2047;
// Three byte tags.
repeated float repeated_float = 262142;
repeated uint64 repeated_uint64 = 262143;
}
// Test that if an optional or required message/group field appears multiple
// times in the input, they need to be merged.
message TestParsingMerge {
// RepeatedFieldsGenerator defines matching field types as TestParsingMerge,
// except that all fields are repeated. In the tests, we will serialize the
// RepeatedFieldsGenerator to bytes, and parse the bytes to TestParsingMerge.
// Repeated fields in RepeatedFieldsGenerator are expected to be merged into
// the corresponding required/optional fields in TestParsingMerge.
message RepeatedFieldsGenerator {
repeated TestAllTypes field1 = 1;
repeated TestAllTypes field2 = 2;
repeated TestAllTypes field3 = 3;
repeated group Group1 = 10 {
optional TestAllTypes field1 = 11;
}
repeated group Group2 = 20 {
optional TestAllTypes field1 = 21;
}
repeated TestAllTypes ext1 = 1000;
repeated TestAllTypes ext2 = 1001;
}
required TestAllTypes required_all_types = 1;
optional TestAllTypes optional_all_types = 2;
repeated TestAllTypes repeated_all_types = 3;
optional group OptionalGroup = 10 {
optional TestAllTypes optional_group_all_types = 11;
}
repeated group RepeatedGroup = 20 {
optional TestAllTypes repeated_group_all_types = 21;
}
extensions 1000 to max;
extend TestParsingMerge {
optional TestAllTypes optional_ext = 1000;
repeated TestAllTypes repeated_ext = 1001;
}
}
message TestCommentInjectionMessage {
// */ <- This should not close the generated doc comment
optional string a = 1 [default="*/ <- Neither should this."];
}
// Test that RPC services work.
message FooRequest {}
message FooResponse {}
message FooClientMessage {}
message FooServerMessage{}
service TestService {
rpc Foo(FooRequest) returns (FooResponse);
rpc Bar(BarRequest) returns (BarResponse);
}
message BarRequest {}
message BarResponse {}

@ -1,387 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: benjy@google.com (Benjy Weinberger)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file used to test the "custom options" feature of proto2.
// Some generic_services option(s) added automatically.
// See: http://go/proto2-generic-services-default
option cc_generic_services = true; // auto-added
option java_generic_services = true; // auto-added
option py_generic_services = true;
// A custom file option (defined below).
option (file_opt1) = 9876543210;
import "google/protobuf/descriptor.proto";
// We don't put this in a package within proto2 because we need to make sure
// that the generated code doesn't depend on being in the proto2 namespace.
package protobuf_unittest;
// Some simple test custom options of various types.
extend google.protobuf.FileOptions {
optional uint64 file_opt1 = 7736974;
}
extend google.protobuf.MessageOptions {
optional int32 message_opt1 = 7739036;
}
extend google.protobuf.FieldOptions {
optional fixed64 field_opt1 = 7740936;
// This is useful for testing that we correctly register default values for
// extension options.
optional int32 field_opt2 = 7753913 [default=42];
}
extend google.protobuf.EnumOptions {
optional sfixed32 enum_opt1 = 7753576;
}
extend google.protobuf.EnumValueOptions {
optional int32 enum_value_opt1 = 1560678;
}
extend google.protobuf.ServiceOptions {
optional sint64 service_opt1 = 7887650;
}
enum MethodOpt1 {
METHODOPT1_VAL1 = 1;
METHODOPT1_VAL2 = 2;
}
extend google.protobuf.MethodOptions {
optional MethodOpt1 method_opt1 = 7890860;
}
// A test message with custom options at all possible locations (and also some
// regular options, to make sure they interact nicely).
message TestMessageWithCustomOptions {
option message_set_wire_format = false;
option (message_opt1) = -56;
optional string field1 = 1 [ctype=CORD,
(field_opt1)=8765432109];
enum AnEnum {
option (enum_opt1) = -789;
ANENUM_VAL1 = 1;
ANENUM_VAL2 = 2 [(enum_value_opt1) = 123];
}
}
// A test RPC service with custom options at all possible locations (and also
// some regular options, to make sure they interact nicely).
message CustomOptionFooRequest {
}
message CustomOptionFooResponse {
}
message CustomOptionFooClientMessage {
}
message CustomOptionFooServerMessage {
}
service TestServiceWithCustomOptions {
option (service_opt1) = -9876543210;
rpc Foo(CustomOptionFooRequest) returns (CustomOptionFooResponse) {
option (method_opt1) = METHODOPT1_VAL2;
}
}
// Options of every possible field type, so we can test them all exhaustively.
message DummyMessageContainingEnum {
enum TestEnumType {
TEST_OPTION_ENUM_TYPE1 = 22;
TEST_OPTION_ENUM_TYPE2 = -23;
}
}
message DummyMessageInvalidAsOptionType {
}
extend google.protobuf.MessageOptions {
optional bool bool_opt = 7706090;
optional int32 int32_opt = 7705709;
optional int64 int64_opt = 7705542;
optional uint32 uint32_opt = 7704880;
optional uint64 uint64_opt = 7702367;
optional sint32 sint32_opt = 7701568;
optional sint64 sint64_opt = 7700863;
optional fixed32 fixed32_opt = 7700307;
optional fixed64 fixed64_opt = 7700194;
optional sfixed32 sfixed32_opt = 7698645;
optional sfixed64 sfixed64_opt = 7685475;
optional float float_opt = 7675390;
optional double double_opt = 7673293;
optional string string_opt = 7673285;
optional bytes bytes_opt = 7673238;
optional DummyMessageContainingEnum.TestEnumType enum_opt = 7673233;
optional DummyMessageInvalidAsOptionType message_type_opt = 7665967;
}
message CustomOptionMinIntegerValues {
option (bool_opt) = false;
option (int32_opt) = -0x80000000;
option (int64_opt) = -0x8000000000000000;
option (uint32_opt) = 0;
option (uint64_opt) = 0;
option (sint32_opt) = -0x80000000;
option (sint64_opt) = -0x8000000000000000;
option (fixed32_opt) = 0;
option (fixed64_opt) = 0;
option (sfixed32_opt) = -0x80000000;
option (sfixed64_opt) = -0x8000000000000000;
}
message CustomOptionMaxIntegerValues {
option (bool_opt) = true;
option (int32_opt) = 0x7FFFFFFF;
option (int64_opt) = 0x7FFFFFFFFFFFFFFF;
option (uint32_opt) = 0xFFFFFFFF;
option (uint64_opt) = 0xFFFFFFFFFFFFFFFF;
option (sint32_opt) = 0x7FFFFFFF;
option (sint64_opt) = 0x7FFFFFFFFFFFFFFF;
option (fixed32_opt) = 0xFFFFFFFF;
option (fixed64_opt) = 0xFFFFFFFFFFFFFFFF;
option (sfixed32_opt) = 0x7FFFFFFF;
option (sfixed64_opt) = 0x7FFFFFFFFFFFFFFF;
}
message CustomOptionOtherValues {
option (int32_opt) = -100; // To test sign-extension.
option (float_opt) = 12.3456789;
option (double_opt) = 1.234567890123456789;
option (string_opt) = "Hello, \"World\"";
option (bytes_opt) = "Hello\0World";
option (enum_opt) = TEST_OPTION_ENUM_TYPE2;
}
message SettingRealsFromPositiveInts {
option (float_opt) = 12;
option (double_opt) = 154;
}
message SettingRealsFromNegativeInts {
option (float_opt) = -12;
option (double_opt) = -154;
}
// Options of complex message types, themselves combined and extended in
// various ways.
message ComplexOptionType1 {
optional int32 foo = 1;
optional int32 foo2 = 2;
optional int32 foo3 = 3;
extensions 100 to max;
}
message ComplexOptionType2 {
optional ComplexOptionType1 bar = 1;
optional int32 baz = 2;
message ComplexOptionType4 {
optional int32 waldo = 1;
extend google.protobuf.MessageOptions {
optional ComplexOptionType4 complex_opt4 = 7633546;
}
}
optional ComplexOptionType4 fred = 3;
extensions 100 to max;
}
message ComplexOptionType3 {
optional int32 qux = 1;
optional group ComplexOptionType5 = 2 {
optional int32 plugh = 3;
}
}
extend ComplexOptionType1 {
optional int32 quux = 7663707;
optional ComplexOptionType3 corge = 7663442;
}
extend ComplexOptionType2 {
optional int32 grault = 7650927;
optional ComplexOptionType1 garply = 7649992;
}
extend google.protobuf.MessageOptions {
optional protobuf_unittest.ComplexOptionType1 complex_opt1 = 7646756;
optional ComplexOptionType2 complex_opt2 = 7636949;
optional ComplexOptionType3 complex_opt3 = 7636463;
optional group ComplexOpt6 = 7595468 {
optional int32 xyzzy = 7593951;
}
}
// Note that we try various different ways of naming the same extension.
message VariousComplexOptions {
option (.protobuf_unittest.complex_opt1).foo = 42;
option (protobuf_unittest.complex_opt1).(.protobuf_unittest.quux) = 324;
option (.protobuf_unittest.complex_opt1).(protobuf_unittest.corge).qux = 876;
option (complex_opt2).baz = 987;
option (complex_opt2).(grault) = 654;
option (complex_opt2).bar.foo = 743;
option (complex_opt2).bar.(quux) = 1999;
option (complex_opt2).bar.(protobuf_unittest.corge).qux = 2008;
option (complex_opt2).(garply).foo = 741;
option (complex_opt2).(garply).(.protobuf_unittest.quux) = 1998;
option (complex_opt2).(protobuf_unittest.garply).(corge).qux = 2121;
option (ComplexOptionType2.ComplexOptionType4.complex_opt4).waldo = 1971;
option (complex_opt2).fred.waldo = 321;
option (protobuf_unittest.complex_opt3).qux = 9;
option (complex_opt3).complexoptiontype5.plugh = 22;
option (complexopt6).xyzzy = 24;
}
// ------------------------------------------------------
// Definitions for testing aggregate option parsing.
// See descriptor_unittest.cc.
message AggregateMessageSet {
option message_set_wire_format = true;
extensions 4 to max;
}
message AggregateMessageSetElement {
extend AggregateMessageSet {
optional AggregateMessageSetElement message_set_extension = 15447542;
}
optional string s = 1;
}
// A helper type used to test aggregate option parsing
message Aggregate {
optional int32 i = 1;
optional string s = 2;
// A nested object
optional Aggregate sub = 3;
// To test the parsing of extensions inside aggregate values
optional google.protobuf.FileOptions file = 4;
extend google.protobuf.FileOptions {
optional Aggregate nested = 15476903;
}
// An embedded message set
optional AggregateMessageSet mset = 5;
}
// Allow Aggregate to be used as an option at all possible locations
// in the .proto grammar.
extend google.protobuf.FileOptions { optional Aggregate fileopt = 15478479; }
extend google.protobuf.MessageOptions { optional Aggregate msgopt = 15480088; }
extend google.protobuf.FieldOptions { optional Aggregate fieldopt = 15481374; }
extend google.protobuf.EnumOptions { optional Aggregate enumopt = 15483218; }
extend google.protobuf.EnumValueOptions { optional Aggregate enumvalopt = 15486921; }
extend google.protobuf.ServiceOptions { optional Aggregate serviceopt = 15497145; }
extend google.protobuf.MethodOptions { optional Aggregate methodopt = 15512713; }
// Try using AggregateOption at different points in the proto grammar
option (fileopt) = {
s: 'FileAnnotation'
// Also test the handling of comments
/* of both types */ i: 100
sub { s: 'NestedFileAnnotation' }
// Include a google.protobuf.FileOptions and recursively extend it with
// another fileopt.
file {
[protobuf_unittest.fileopt] {
s:'FileExtensionAnnotation'
}
}
// A message set inside an option value
mset {
[protobuf_unittest.AggregateMessageSetElement.message_set_extension] {
s: 'EmbeddedMessageSetElement'
}
}
};
message AggregateMessage {
option (msgopt) = { i:101 s:'MessageAnnotation' };
optional int32 fieldname = 1 [(fieldopt) = { s:'FieldAnnotation' }];
}
service AggregateService {
option (serviceopt) = { s:'ServiceAnnotation' };
rpc Method (AggregateMessage) returns (AggregateMessage) {
option (methodopt) = { s:'MethodAnnotation' };
}
}
enum AggregateEnum {
option (enumopt) = { s:'EnumAnnotation' };
VALUE = 1 [(enumvalopt) = { s:'EnumValueAnnotation' }];
}
// Test custom options for nested type.
message NestedOptionType {
message NestedMessage {
option (message_opt1) = 1001;
optional int32 nested_field = 1 [(field_opt1) = 1002];
}
enum NestedEnum {
option (enum_opt1) = 1003;
NESTED_ENUM_VALUE = 1 [(enum_value_opt1) = 1004];
}
extend google.protobuf.FileOptions {
optional int32 nested_extension = 7912573 [(field_opt2) = 1005];
}
}

@ -1,50 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file which imports a proto file that uses optimize_for = CODE_SIZE.
import "google/protobuf/unittest_optimize_for.proto";
package protobuf_unittest;
// We optimize for speed here, but we are importing a proto that is optimized
// for code size.
option optimize_for = SPEED;
message TestEmbedOptimizedForSize {
// Test that embedding a message which has optimize_for = CODE_SIZE into
// one optimized for speed works.
optional TestOptimizedForSize optional_message = 1;
repeated TestOptimizedForSize repeated_message = 2;
}

@ -1,37 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file intentionally left blank. (At one point this wouldn't compile
// correctly.)

@ -1,64 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file which is imported by unittest.proto to test importing.
// We don't put this in a package within proto2 because we need to make sure
// that the generated code doesn't depend on being in the proto2 namespace.
// In test_util.h we do
// "using namespace unittest_import = protobuf_unittest_import".
package protobuf_unittest_import;
option optimize_for = SPEED;
// Exercise the java_package option.
option java_package = "com.google.protobuf.test";
// Do not set a java_outer_classname here to verify that Proto2 works without
// one.
// Test public import
import public "google/protobuf/unittest_import_public.proto";
message ImportMessage {
optional int32 d = 1;
}
enum ImportEnum {
IMPORT_FOO = 7;
IMPORT_BAR = 8;
IMPORT_BAZ = 9;
}

@ -1,51 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
//
// This is like unittest_import.proto but with optimize_for = LITE_RUNTIME.
package protobuf_unittest_import;
option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf";
import public "google/protobuf/unittest_import_public_lite.proto";
message ImportMessageLite {
optional int32 d = 1;
}
enum ImportEnumLite {
IMPORT_LITE_FOO = 7;
IMPORT_LITE_BAR = 8;
IMPORT_LITE_BAZ = 9;
}

@ -1,40 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: liujisi@google.com (Pherl Liu)
package protobuf_unittest_import;
option java_package = "com.google.protobuf.test";
message PublicImportMessage {
optional int32 e = 1;
}

@ -1,42 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: liujisi@google.com (Pherl Liu)
package protobuf_unittest_import;
option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf";
message PublicImportMessageLite {
optional int32 e = 1;
}

@ -1,360 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
//
// This is like unittest.proto but with optimize_for = LITE_RUNTIME.
package protobuf_unittest;
import "google/protobuf/unittest_import_lite.proto";
option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf";
// Same as TestAllTypes but with the lite runtime.
message TestAllTypesLite {
message NestedMessage {
optional int32 bb = 1;
}
enum NestedEnum {
FOO = 1;
BAR = 2;
BAZ = 3;
}
// Singular
optional int32 optional_int32 = 1;
optional int64 optional_int64 = 2;
optional uint32 optional_uint32 = 3;
optional uint64 optional_uint64 = 4;
optional sint32 optional_sint32 = 5;
optional sint64 optional_sint64 = 6;
optional fixed32 optional_fixed32 = 7;
optional fixed64 optional_fixed64 = 8;
optional sfixed32 optional_sfixed32 = 9;
optional sfixed64 optional_sfixed64 = 10;
optional float optional_float = 11;
optional double optional_double = 12;
optional bool optional_bool = 13;
optional string optional_string = 14;
optional bytes optional_bytes = 15;
optional group OptionalGroup = 16 {
optional int32 a = 17;
}
optional NestedMessage optional_nested_message = 18;
optional ForeignMessageLite optional_foreign_message = 19;
optional protobuf_unittest_import.ImportMessageLite
optional_import_message = 20;
optional NestedEnum optional_nested_enum = 21;
optional ForeignEnumLite optional_foreign_enum = 22;
optional protobuf_unittest_import.ImportEnumLite optional_import_enum = 23;
optional string optional_string_piece = 24 [ctype=STRING_PIECE];
optional string optional_cord = 25 [ctype=CORD];
// Defined in unittest_import_public.proto
optional protobuf_unittest_import.PublicImportMessageLite
optional_public_import_message = 26;
optional NestedMessage optional_lazy_message = 27 [lazy=true];
// Repeated
repeated int32 repeated_int32 = 31;
repeated int64 repeated_int64 = 32;
repeated uint32 repeated_uint32 = 33;
repeated uint64 repeated_uint64 = 34;
repeated sint32 repeated_sint32 = 35;
repeated sint64 repeated_sint64 = 36;
repeated fixed32 repeated_fixed32 = 37;
repeated fixed64 repeated_fixed64 = 38;
repeated sfixed32 repeated_sfixed32 = 39;
repeated sfixed64 repeated_sfixed64 = 40;
repeated float repeated_float = 41;
repeated double repeated_double = 42;
repeated bool repeated_bool = 43;
repeated string repeated_string = 44;
repeated bytes repeated_bytes = 45;
repeated group RepeatedGroup = 46 {
optional int32 a = 47;
}
repeated NestedMessage repeated_nested_message = 48;
repeated ForeignMessageLite repeated_foreign_message = 49;
repeated protobuf_unittest_import.ImportMessageLite
repeated_import_message = 50;
repeated NestedEnum repeated_nested_enum = 51;
repeated ForeignEnumLite repeated_foreign_enum = 52;
repeated protobuf_unittest_import.ImportEnumLite repeated_import_enum = 53;
repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
repeated string repeated_cord = 55 [ctype=CORD];
repeated NestedMessage repeated_lazy_message = 57 [lazy=true];
// Singular with defaults
optional int32 default_int32 = 61 [default = 41 ];
optional int64 default_int64 = 62 [default = 42 ];
optional uint32 default_uint32 = 63 [default = 43 ];
optional uint64 default_uint64 = 64 [default = 44 ];
optional sint32 default_sint32 = 65 [default = -45 ];
optional sint64 default_sint64 = 66 [default = 46 ];
optional fixed32 default_fixed32 = 67 [default = 47 ];
optional fixed64 default_fixed64 = 68 [default = 48 ];
optional sfixed32 default_sfixed32 = 69 [default = 49 ];
optional sfixed64 default_sfixed64 = 70 [default = -50 ];
optional float default_float = 71 [default = 51.5 ];
optional double default_double = 72 [default = 52e3 ];
optional bool default_bool = 73 [default = true ];
optional string default_string = 74 [default = "hello"];
optional bytes default_bytes = 75 [default = "world"];
optional NestedEnum default_nested_enum = 81 [default = BAR];
optional ForeignEnumLite default_foreign_enum = 82
[default = FOREIGN_LITE_BAR];
optional protobuf_unittest_import.ImportEnumLite
default_import_enum = 83 [default = IMPORT_LITE_BAR];
optional string default_string_piece = 84 [ctype=STRING_PIECE,default="abc"];
optional string default_cord = 85 [ctype=CORD,default="123"];
}
message ForeignMessageLite {
optional int32 c = 1;
}
enum ForeignEnumLite {
FOREIGN_LITE_FOO = 4;
FOREIGN_LITE_BAR = 5;
FOREIGN_LITE_BAZ = 6;
}
message TestPackedTypesLite {
repeated int32 packed_int32 = 90 [packed = true];
repeated int64 packed_int64 = 91 [packed = true];
repeated uint32 packed_uint32 = 92 [packed = true];
repeated uint64 packed_uint64 = 93 [packed = true];
repeated sint32 packed_sint32 = 94 [packed = true];
repeated sint64 packed_sint64 = 95 [packed = true];
repeated fixed32 packed_fixed32 = 96 [packed = true];
repeated fixed64 packed_fixed64 = 97 [packed = true];
repeated sfixed32 packed_sfixed32 = 98 [packed = true];
repeated sfixed64 packed_sfixed64 = 99 [packed = true];
repeated float packed_float = 100 [packed = true];
repeated double packed_double = 101 [packed = true];
repeated bool packed_bool = 102 [packed = true];
repeated ForeignEnumLite packed_enum = 103 [packed = true];
}
message TestAllExtensionsLite {
extensions 1 to max;
}
extend TestAllExtensionsLite {
// Singular
optional int32 optional_int32_extension_lite = 1;
optional int64 optional_int64_extension_lite = 2;
optional uint32 optional_uint32_extension_lite = 3;
optional uint64 optional_uint64_extension_lite = 4;
optional sint32 optional_sint32_extension_lite = 5;
optional sint64 optional_sint64_extension_lite = 6;
optional fixed32 optional_fixed32_extension_lite = 7;
optional fixed64 optional_fixed64_extension_lite = 8;
optional sfixed32 optional_sfixed32_extension_lite = 9;
optional sfixed64 optional_sfixed64_extension_lite = 10;
optional float optional_float_extension_lite = 11;
optional double optional_double_extension_lite = 12;
optional bool optional_bool_extension_lite = 13;
optional string optional_string_extension_lite = 14;
optional bytes optional_bytes_extension_lite = 15;
optional group OptionalGroup_extension_lite = 16 {
optional int32 a = 17;
}
optional TestAllTypesLite.NestedMessage optional_nested_message_extension_lite
= 18;
optional ForeignMessageLite optional_foreign_message_extension_lite = 19;
optional protobuf_unittest_import.ImportMessageLite
optional_import_message_extension_lite = 20;
optional TestAllTypesLite.NestedEnum optional_nested_enum_extension_lite = 21;
optional ForeignEnumLite optional_foreign_enum_extension_lite = 22;
optional protobuf_unittest_import.ImportEnumLite
optional_import_enum_extension_lite = 23;
optional string optional_string_piece_extension_lite = 24
[ctype=STRING_PIECE];
optional string optional_cord_extension_lite = 25 [ctype=CORD];
optional protobuf_unittest_import.PublicImportMessageLite
optional_public_import_message_extension_lite = 26;
optional TestAllTypesLite.NestedMessage
optional_lazy_message_extension_lite = 27 [lazy=true];
// Repeated
repeated int32 repeated_int32_extension_lite = 31;
repeated int64 repeated_int64_extension_lite = 32;
repeated uint32 repeated_uint32_extension_lite = 33;
repeated uint64 repeated_uint64_extension_lite = 34;
repeated sint32 repeated_sint32_extension_lite = 35;
repeated sint64 repeated_sint64_extension_lite = 36;
repeated fixed32 repeated_fixed32_extension_lite = 37;
repeated fixed64 repeated_fixed64_extension_lite = 38;
repeated sfixed32 repeated_sfixed32_extension_lite = 39;
repeated sfixed64 repeated_sfixed64_extension_lite = 40;
repeated float repeated_float_extension_lite = 41;
repeated double repeated_double_extension_lite = 42;
repeated bool repeated_bool_extension_lite = 43;
repeated string repeated_string_extension_lite = 44;
repeated bytes repeated_bytes_extension_lite = 45;
repeated group RepeatedGroup_extension_lite = 46 {
optional int32 a = 47;
}
repeated TestAllTypesLite.NestedMessage repeated_nested_message_extension_lite
= 48;
repeated ForeignMessageLite repeated_foreign_message_extension_lite = 49;
repeated protobuf_unittest_import.ImportMessageLite
repeated_import_message_extension_lite = 50;
repeated TestAllTypesLite.NestedEnum repeated_nested_enum_extension_lite = 51;
repeated ForeignEnumLite repeated_foreign_enum_extension_lite = 52;
repeated protobuf_unittest_import.ImportEnumLite
repeated_import_enum_extension_lite = 53;
repeated string repeated_string_piece_extension_lite = 54
[ctype=STRING_PIECE];
repeated string repeated_cord_extension_lite = 55 [ctype=CORD];
repeated TestAllTypesLite.NestedMessage
repeated_lazy_message_extension_lite = 57 [lazy=true];
// Singular with defaults
optional int32 default_int32_extension_lite = 61 [default = 41 ];
optional int64 default_int64_extension_lite = 62 [default = 42 ];
optional uint32 default_uint32_extension_lite = 63 [default = 43 ];
optional uint64 default_uint64_extension_lite = 64 [default = 44 ];
optional sint32 default_sint32_extension_lite = 65 [default = -45 ];
optional sint64 default_sint64_extension_lite = 66 [default = 46 ];
optional fixed32 default_fixed32_extension_lite = 67 [default = 47 ];
optional fixed64 default_fixed64_extension_lite = 68 [default = 48 ];
optional sfixed32 default_sfixed32_extension_lite = 69 [default = 49 ];
optional sfixed64 default_sfixed64_extension_lite = 70 [default = -50 ];
optional float default_float_extension_lite = 71 [default = 51.5 ];
optional double default_double_extension_lite = 72 [default = 52e3 ];
optional bool default_bool_extension_lite = 73 [default = true ];
optional string default_string_extension_lite = 74 [default = "hello"];
optional bytes default_bytes_extension_lite = 75 [default = "world"];
optional TestAllTypesLite.NestedEnum
default_nested_enum_extension_lite = 81 [default = BAR];
optional ForeignEnumLite
default_foreign_enum_extension_lite = 82 [default = FOREIGN_LITE_BAR];
optional protobuf_unittest_import.ImportEnumLite
default_import_enum_extension_lite = 83 [default = IMPORT_LITE_BAR];
optional string default_string_piece_extension_lite = 84 [ctype=STRING_PIECE,
default="abc"];
optional string default_cord_extension_lite = 85 [ctype=CORD, default="123"];
}
message TestPackedExtensionsLite {
extensions 1 to max;
}
extend TestPackedExtensionsLite {
repeated int32 packed_int32_extension_lite = 90 [packed = true];
repeated int64 packed_int64_extension_lite = 91 [packed = true];
repeated uint32 packed_uint32_extension_lite = 92 [packed = true];
repeated uint64 packed_uint64_extension_lite = 93 [packed = true];
repeated sint32 packed_sint32_extension_lite = 94 [packed = true];
repeated sint64 packed_sint64_extension_lite = 95 [packed = true];
repeated fixed32 packed_fixed32_extension_lite = 96 [packed = true];
repeated fixed64 packed_fixed64_extension_lite = 97 [packed = true];
repeated sfixed32 packed_sfixed32_extension_lite = 98 [packed = true];
repeated sfixed64 packed_sfixed64_extension_lite = 99 [packed = true];
repeated float packed_float_extension_lite = 100 [packed = true];
repeated double packed_double_extension_lite = 101 [packed = true];
repeated bool packed_bool_extension_lite = 102 [packed = true];
repeated ForeignEnumLite packed_enum_extension_lite = 103 [packed = true];
}
message TestNestedExtensionLite {
extend TestAllExtensionsLite {
optional int32 nested_extension = 12345;
}
}
// Test that deprecated fields work. We only verify that they compile (at one
// point this failed).
message TestDeprecatedLite {
optional int32 deprecated_field = 1 [deprecated = true];
}
// See the comments of the same type in unittest.proto.
message TestParsingMergeLite {
message RepeatedFieldsGenerator {
repeated TestAllTypesLite field1 = 1;
repeated TestAllTypesLite field2 = 2;
repeated TestAllTypesLite field3 = 3;
repeated group Group1 = 10 {
optional TestAllTypesLite field1 = 11;
}
repeated group Group2 = 20 {
optional TestAllTypesLite field1 = 21;
}
repeated TestAllTypesLite ext1 = 1000;
repeated TestAllTypesLite ext2 = 1001;
}
required TestAllTypesLite required_all_types = 1;
optional TestAllTypesLite optional_all_types = 2;
repeated TestAllTypesLite repeated_all_types = 3;
optional group OptionalGroup = 10 {
optional TestAllTypesLite optional_group_all_types = 11;
}
repeated group RepeatedGroup = 20 {
optional TestAllTypesLite repeated_group_all_types = 21;
}
extensions 1000 to max;
extend TestParsingMergeLite {
optional TestAllTypesLite optional_ext = 1000;
repeated TestAllTypesLite repeated_ext = 1001;
}
}

@ -1,43 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
//
// Tests that a "lite" message can import a regular message.
package protobuf_unittest;
import "google/protobuf/unittest.proto";
option optimize_for = LITE_RUNTIME;
message TestLiteImportsNonlite {
optional TestAllTypes message = 1;
}

@ -1,72 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file contains messages for testing message_set_wire_format.
package protobuf_unittest;
option optimize_for = SPEED;
// A message with message_set_wire_format.
message TestMessageSet {
option message_set_wire_format = true;
extensions 4 to max;
}
message TestMessageSetContainer {
optional TestMessageSet message_set = 1;
}
message TestMessageSetExtension1 {
extend TestMessageSet {
optional TestMessageSetExtension1 message_set_extension = 1545008;
}
optional int32 i = 15;
}
message TestMessageSetExtension2 {
extend TestMessageSet {
optional TestMessageSetExtension2 message_set_extension = 1547769;
}
optional string str = 25;
}
// MessageSet wire format is equivalent to this.
message RawMessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required bytes message = 3;
}
}

@ -1,52 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
package google.protobuf.no_generic_services_test;
// *_generic_services are false by default.
message TestMessage {
optional int32 a = 1;
extensions 1000 to max;
}
enum TestEnum {
FOO = 1;
}
extend TestMessage {
optional int32 test_extension = 1000;
}
service TestService {
rpc Foo(TestMessage) returns(TestMessage);
}

@ -1,61 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file which uses optimize_for = CODE_SIZE.
import "google/protobuf/unittest.proto";
package protobuf_unittest;
option optimize_for = CODE_SIZE;
message TestOptimizedForSize {
optional int32 i = 1;
optional ForeignMessage msg = 19;
extensions 1000 to max;
extend TestOptimizedForSize {
optional int32 test_extension = 1234;
optional TestRequiredOptimizedForSize test_extension2 = 1235;
}
}
message TestRequiredOptimizedForSize {
required int32 x = 1;
}
message TestOptionalOptimizedForSize {
optional TestRequiredOptimizedForSize o = 1;
}

@ -1,30 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.protobuf.compatibility</groupId>
<artifactId>compatibility-test-suite</artifactId>
<version>2.5.0</version>
<name>Protocol Buffer Java API compatibility tests</name>
<packaging>pom</packaging>
<modules>
<module>protos</module>
<module>more_protos</module>
<module>tests</module>
</modules>
<properties>
<protoc.path>protoc</protoc.path>
<protobuf.version>2.5.0</protobuf.version>
<protos.protoc.path>${protoc.path}</protos.protoc.path>
<protos.protobuf.version>${protobuf.version}</protos.protobuf.version>
<more_protos.protoc.path>${protoc.path}</more_protos.protoc.path>
<more_protos.protobuf.version>${protobuf.version}</more_protos.protobuf.version>
<tests.protobuf.version>${protobuf.version}</tests.protobuf.version>
<protobuf.test.source.path>.</protobuf.test.source.path>
</properties>
</project>

@ -1,71 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.google.protobuf.compatibility</groupId>
<artifactId>compatibility-test-suite</artifactId>
<version>2.5.0</version>
<relativePath>..</relativePath>
</parent>
<groupId>com.google.protobuf.compatibility</groupId>
<artifactId>compatibility-protos</artifactId>
<version>2.5.0</version>
<name>Protos for Compatibility test</name>
<dependencies>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${protos.protobuf.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<tasks>
<mkdir dir="target/generated-sources" />
<exec executable="${protos.protoc.path}">
<arg value="--java_out=target/generated-sources" />
<arg value="--proto_path=src/proto" />
<arg value="src/proto/google/protobuf/unittest_custom_options.proto" />
<arg value="src/proto/google/protobuf/unittest_enormous_descriptor.proto" />
<arg value="src/proto/google/protobuf/unittest_import.proto" />
<arg value="src/proto/google/protobuf/unittest_import_public.proto" />
<arg value="src/proto/google/protobuf/unittest_mset.proto" />
<arg value="src/proto/google/protobuf/unittest_no_generic_services.proto" />
<arg value="src/proto/com/google/protobuf/nested_builders_test.proto" />
<arg value="src/proto/com/google/protobuf/nested_extension.proto" />
<arg value="src/proto/com/google/protobuf/non_nested_extension.proto" />
<arg value="src/proto/com/google/protobuf/test_bad_identifiers.proto" />
</exec>
</tasks>
<sourceRoot>target/generated-sources</sourceRoot>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,71 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
//
// A proto file which tests the java_multiple_files option.
// Some generic_services option(s) added automatically.
// See: http://go/proto2-generic-services-default
option java_generic_services = true; // auto-added
import "google/protobuf/unittest.proto";
package protobuf_unittest;
option java_multiple_files = true;
option java_outer_classname = "MultipleFilesTestProto";
message MessageWithNoOuter {
message NestedMessage {
optional int32 i = 1;
}
enum NestedEnum {
BAZ = 3;
}
optional NestedMessage nested = 1;
repeated TestAllTypes foreign = 2;
optional NestedEnum nested_enum = 3;
optional EnumWithNoOuter foreign_enum = 4;
}
enum EnumWithNoOuter {
FOO = 1;
BAR = 2;
}
service ServiceWithNoOuter {
rpc Foo(MessageWithNoOuter) returns(TestAllTypes);
}
extend TestAllExtensions {
optional int32 extension_with_outer = 1234567;
}

@ -1,53 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: jonp@google.com (Jon Perlow)
//
package protobuf_unittest;
option java_multiple_files = true;
option java_outer_classname = "NestedBuilders";
message Vehicle {
optional Engine engine = 1;
repeated Wheel wheel = 2;
}
message Engine {
optional int32 cylinder = 1;
optional int32 liters = 2;
}
message Wheel {
optional int32 radius = 1;
optional int32 width = 2;
}

@ -1,45 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: Darick Tong (darick@google.com)
//
// A proto file with nested extensions. Note that this must be defined in
// a separate file to properly test the initialization of the outer class.
import "com/google/protobuf/non_nested_extension.proto";
package protobuf_unittest;
message MyNestedExtension {
extend MessageToBeExtended {
optional MessageToBeExtended recursiveExtension = 2;
}
}

@ -1,48 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: Darick Tong (darick@google.com)
//
// A proto file with nested extensions for a MessageLite messages. Note that
// this must be defined in a separate file to properly test the initialization
// of the outer class.
package protobuf_unittest;
option optimize_for = LITE_RUNTIME;
import "com/google/protobuf/non_nested_extension_lite.proto";
message MyNestedExtensionLite {
extend MessageLiteToBeExtended {
optional MessageLiteToBeExtended recursiveExtensionLite = 3;
}
}

@ -1,48 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: Darick Tong (darick@google.com)
//
// A proto file with extensions.
package protobuf_unittest;
message MessageToBeExtended {
extensions 1 to max;
}
message MyNonNestedExtension {
}
extend MessageToBeExtended {
optional MyNonNestedExtension nonNestedExtension = 1;
}

@ -1,50 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: Darick Tong (darick@google.com)
//
// A proto file with extensions for a MessageLite messages.
package protobuf_unittest;
option optimize_for = LITE_RUNTIME;
message MessageLiteToBeExtended {
extensions 1 to max;
}
message MyNonNestedExtensionLite {
}
extend MessageLiteToBeExtended {
optional MyNonNestedExtensionLite nonNestedExtensionLite = 1;
}

@ -1,108 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: jonp@google.com (Jon Perlow)
// This file tests that various identifiers work as field and type names even
// though the same identifiers are used internally by the java code generator.
// Some generic_services option(s) added automatically.
// See: http://go/proto2-generic-services-default
option java_generic_services = true; // auto-added
package io_protocol_tests;
option java_package = "com.google.protobuf";
option java_outer_classname = "TestBadIdentifiersProto";
message TestMessage {
}
message Descriptor {
option no_standard_descriptor_accessor = true;
optional string descriptor = 1;
message NestedDescriptor {
option no_standard_descriptor_accessor = true;
optional string descriptor = 1;
}
optional NestedDescriptor nested_descriptor = 2;
}
message Parser {
enum ParserEnum {
PARSER = 1;
}
optional ParserEnum parser = 1;
}
message Deprecated {
enum TestEnum {
FOO = 1;
}
optional int32 field1 = 1 [deprecated=true];
optional TestEnum field2 = 2 [deprecated=true];
optional TestMessage field3 = 3 [deprecated=true];
}
message Override {
optional int32 override = 1;
}
message Object {
optional int32 object = 1;
optional string string_object = 2;
}
message String {
optional string string = 1;
}
message Integer {
optional int32 integer = 1;
}
message Long {
optional int32 long = 1;
}
message Float {
optional float float = 1;
}
message Double {
optional double double = 1;
}
service TestConflictingMethodNames {
rpc Override(TestMessage) returns (TestMessage);
}

@ -1,620 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// The messages in this file describe the definitions found in .proto files.
// A valid .proto file can be translated directly to a FileDescriptorProto
// without any other information (e.g. without reading its imports).
package google.protobuf;
option java_package = "com.google.protobuf";
option java_outer_classname = "DescriptorProtos";
// descriptor.proto must be optimized for speed because reflection-based
// algorithms don't work during bootstrapping.
option optimize_for = SPEED;
// The protocol compiler can output a FileDescriptorSet containing the .proto
// files it parses.
message FileDescriptorSet {
repeated FileDescriptorProto file = 1;
}
// Describes a complete .proto file.
message FileDescriptorProto {
optional string name = 1; // file name, relative to root of source tree
optional string package = 2; // e.g. "foo", "foo.bar", etc.
// Names of files imported by this file.
repeated string dependency = 3;
// Indexes of the public imported files in the dependency list above.
repeated int32 public_dependency = 10;
// Indexes of the weak imported files in the dependency list.
// For Google-internal migration only. Do not use.
repeated int32 weak_dependency = 11;
// All top-level definitions in this file.
repeated DescriptorProto message_type = 4;
repeated EnumDescriptorProto enum_type = 5;
repeated ServiceDescriptorProto service = 6;
repeated FieldDescriptorProto extension = 7;
optional FileOptions options = 8;
// This field contains optional information about the original source code.
// You may safely remove this entire field without harming runtime
// functionality of the descriptors -- the information is needed only by
// development tools.
optional SourceCodeInfo source_code_info = 9;
}
// Describes a message type.
message DescriptorProto {
optional string name = 1;
repeated FieldDescriptorProto field = 2;
repeated FieldDescriptorProto extension = 6;
repeated DescriptorProto nested_type = 3;
repeated EnumDescriptorProto enum_type = 4;
message ExtensionRange {
optional int32 start = 1;
optional int32 end = 2;
}
repeated ExtensionRange extension_range = 5;
optional MessageOptions options = 7;
}
// Describes a field within a message.
message FieldDescriptorProto {
enum Type {
// 0 is reserved for errors.
// Order is weird for historical reasons.
TYPE_DOUBLE = 1;
TYPE_FLOAT = 2;
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
// negative values are likely.
TYPE_INT64 = 3;
TYPE_UINT64 = 4;
// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
// negative values are likely.
TYPE_INT32 = 5;
TYPE_FIXED64 = 6;
TYPE_FIXED32 = 7;
TYPE_BOOL = 8;
TYPE_STRING = 9;
TYPE_GROUP = 10; // Tag-delimited aggregate.
TYPE_MESSAGE = 11; // Length-delimited aggregate.
// New in version 2.
TYPE_BYTES = 12;
TYPE_UINT32 = 13;
TYPE_ENUM = 14;
TYPE_SFIXED32 = 15;
TYPE_SFIXED64 = 16;
TYPE_SINT32 = 17; // Uses ZigZag encoding.
TYPE_SINT64 = 18; // Uses ZigZag encoding.
};
enum Label {
// 0 is reserved for errors
LABEL_OPTIONAL = 1;
LABEL_REQUIRED = 2;
LABEL_REPEATED = 3;
// TODO(sanjay): Should we add LABEL_MAP?
};
optional string name = 1;
optional int32 number = 3;
optional Label label = 4;
// If type_name is set, this need not be set. If both this and type_name
// are set, this must be either TYPE_ENUM or TYPE_MESSAGE.
optional Type type = 5;
// For message and enum types, this is the name of the type. If the name
// starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
// rules are used to find the type (i.e. first the nested types within this
// message are searched, then within the parent, on up to the root
// namespace).
optional string type_name = 6;
// For extensions, this is the name of the type being extended. It is
// resolved in the same manner as type_name.
optional string extendee = 2;
// For numeric types, contains the original text representation of the value.
// For booleans, "true" or "false".
// For strings, contains the default text contents (not escaped in any way).
// For bytes, contains the C escaped value. All bytes >= 128 are escaped.
// TODO(kenton): Base-64 encode?
optional string default_value = 7;
optional FieldOptions options = 8;
}
// Describes an enum type.
message EnumDescriptorProto {
optional string name = 1;
repeated EnumValueDescriptorProto value = 2;
optional EnumOptions options = 3;
}
// Describes a value within an enum.
message EnumValueDescriptorProto {
optional string name = 1;
optional int32 number = 2;
optional EnumValueOptions options = 3;
}
// Describes a service.
message ServiceDescriptorProto {
optional string name = 1;
repeated MethodDescriptorProto method = 2;
optional ServiceOptions options = 3;
}
// Describes a method of a service.
message MethodDescriptorProto {
optional string name = 1;
// Input and output type names. These are resolved in the same way as
// FieldDescriptorProto.type_name, but must refer to a message type.
optional string input_type = 2;
optional string output_type = 3;
optional MethodOptions options = 4;
}
// ===================================================================
// Options
// Each of the definitions above may have "options" attached. These are
// just annotations which may cause code to be generated slightly differently
// or may contain hints for code that manipulates protocol messages.
//
// Clients may define custom options as extensions of the *Options messages.
// These extensions may not yet be known at parsing time, so the parser cannot
// store the values in them. Instead it stores them in a field in the *Options
// message called uninterpreted_option. This field must have the same name
// across all *Options messages. We then use this field to populate the
// extensions when we build a descriptor, at which point all protos have been
// parsed and so all extensions are known.
//
// Extension numbers for custom options may be chosen as follows:
// * For options which will only be used within a single application or
// organization, or for experimental options, use field numbers 50000
// through 99999. It is up to you to ensure that you do not use the
// same number for multiple options.
// * For options which will be published and used publicly by multiple
// independent entities, e-mail protobuf-global-extension-registry@google.com
// to reserve extension numbers. Simply provide your project name (e.g.
// Object-C plugin) and your project website (if available) -- there's no need
// to explain how you intend to use them. Usually you only need one extension
// number. You can declare multiple options with only one extension number by
// putting them in a sub-message. See the Custom Options section of the docs
// for examples:
// http://code.google.com/apis/protocolbuffers/docs/proto.html#options
// If this turns out to be popular, a web service will be set up
// to automatically assign option numbers.
message FileOptions {
// Sets the Java package where classes generated from this .proto will be
// placed. By default, the proto package is used, but this is often
// inappropriate because proto packages do not normally start with backwards
// domain names.
optional string java_package = 1;
// If set, all the classes from the .proto file are wrapped in a single
// outer class with the given name. This applies to both Proto1
// (equivalent to the old "--one_java_file" option) and Proto2 (where
// a .proto always translates to a single class, but you may want to
// explicitly choose the class name).
optional string java_outer_classname = 8;
// If set true, then the Java code generator will generate a separate .java
// file for each top-level message, enum, and service defined in the .proto
// file. Thus, these types will *not* be nested inside the outer class
// named by java_outer_classname. However, the outer class will still be
// generated to contain the file's getDescriptor() method as well as any
// top-level extensions defined in the file.
optional bool java_multiple_files = 10 [default=false];
// If set true, then the Java code generator will generate equals() and
// hashCode() methods for all messages defined in the .proto file. This is
// purely a speed optimization, as the AbstractMessage base class includes
// reflection-based implementations of these methods.
optional bool java_generate_equals_and_hash = 20 [default=false];
// Generated classes can be optimized for speed or code size.
enum OptimizeMode {
SPEED = 1; // Generate complete code for parsing, serialization,
// etc.
CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
}
optional OptimizeMode optimize_for = 9 [default=SPEED];
// Sets the Go package where structs generated from this .proto will be
// placed. There is no default.
optional string go_package = 11;
// Should generic services be generated in each language? "Generic" services
// are not specific to any particular RPC system. They are generated by the
// main code generators in each language (without additional plugins).
// Generic services were the only kind of service generation supported by
// early versions of proto2.
//
// Generic services are now considered deprecated in favor of using plugins
// that generate code specific to your particular RPC system. Therefore,
// these default to false. Old code which depends on generic services should
// explicitly set them to true.
optional bool cc_generic_services = 16 [default=false];
optional bool java_generic_services = 17 [default=false];
optional bool py_generic_services = 18 [default=false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message MessageOptions {
// Set true to use the old proto1 MessageSet wire format for extensions.
// This is provided for backwards-compatibility with the MessageSet wire
// format. You should not use this for any other reason: It's less
// efficient, has fewer features, and is more complicated.
//
// The message must be defined exactly as follows:
// message Foo {
// option message_set_wire_format = true;
// extensions 4 to max;
// }
// Note that the message cannot have any defined fields; MessageSets only
// have extensions.
//
// All extensions of your type must be singular messages; e.g. they cannot
// be int32s, enums, or repeated messages.
//
// Because this is an option, the above two restrictions are not enforced by
// the protocol compiler.
optional bool message_set_wire_format = 1 [default=false];
// Disables the generation of the standard "descriptor()" accessor, which can
// conflict with a field of the same name. This is meant to make migration
// from proto1 easier; new code should avoid fields named "descriptor".
optional bool no_standard_descriptor_accessor = 2 [default=false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message FieldOptions {
// The ctype option instructs the C++ code generator to use a different
// representation of the field than it normally would. See the specific
// options below. This option is not yet implemented in the open source
// release -- sorry, we'll try to include it in a future version!
optional CType ctype = 1 [default = STRING];
enum CType {
// Default mode.
STRING = 0;
CORD = 1;
STRING_PIECE = 2;
}
// The packed option can be enabled for repeated primitive fields to enable
// a more efficient representation on the wire. Rather than repeatedly
// writing the tag and type for each element, the entire array is encoded as
// a single length-delimited blob.
optional bool packed = 2;
// Should this field be parsed lazily? Lazy applies only to message-type
// fields. It means that when the outer message is initially parsed, the
// inner message's contents will not be parsed but instead stored in encoded
// form. The inner message will actually be parsed when it is first accessed.
//
// This is only a hint. Implementations are free to choose whether to use
// eager or lazy parsing regardless of the value of this option. However,
// setting this option true suggests that the protocol author believes that
// using lazy parsing on this field is worth the additional bookkeeping
// overhead typically needed to implement it.
//
// This option does not affect the public interface of any generated code;
// all method signatures remain the same. Furthermore, thread-safety of the
// interface is not affected by this option; const methods remain safe to
// call from multiple threads concurrently, while non-const methods continue
// to require exclusive access.
//
//
// Note that implementations may choose not to check required fields within
// a lazy sub-message. That is, calling IsInitialized() on the outher message
// may return true even if the inner message has missing required fields.
// This is necessary because otherwise the inner message would have to be
// parsed in order to perform the check, defeating the purpose of lazy
// parsing. An implementation which chooses not to check required fields
// must be consistent about it. That is, for any particular sub-message, the
// implementation must either *always* check its required fields, or *never*
// check its required fields, regardless of whether or not the message has
// been parsed.
optional bool lazy = 5 [default=false];
// Is this field deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for accessors, or it will be completely ignored; in the very least, this
// is a formalization for deprecating fields.
optional bool deprecated = 3 [default=false];
// EXPERIMENTAL. DO NOT USE.
// For "map" fields, the name of the field in the enclosed type that
// is the key for this map. For example, suppose we have:
// message Item {
// required string name = 1;
// required string value = 2;
// }
// message Config {
// repeated Item items = 1 [experimental_map_key="name"];
// }
// In this situation, the map key for Item will be set to "name".
// TODO: Fully-implement this, then remove the "experimental_" prefix.
optional string experimental_map_key = 9;
// For Google-internal migration only. Do not use.
optional bool weak = 10 [default=false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message EnumOptions {
// Set this option to false to disallow mapping different tag names to a same
// value.
optional bool allow_alias = 2 [default=true];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message EnumValueOptions {
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message ServiceOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message MethodOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
// A message representing a option the parser does not recognize. This only
// appears in options protos created by the compiler::Parser class.
// DescriptorPool resolves these when building Descriptor objects. Therefore,
// options protos in descriptor objects (e.g. returned by Descriptor::options(),
// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
// in them.
message UninterpretedOption {
// The name of the uninterpreted option. Each string represents a segment in
// a dot-separated name. is_extension is true iff a segment represents an
// extension (denoted with parentheses in options specs in .proto files).
// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
// "foo.(bar.baz).qux".
message NamePart {
required string name_part = 1;
required bool is_extension = 2;
}
repeated NamePart name = 2;
// The value of the uninterpreted option, in whatever type the tokenizer
// identified it as during parsing. Exactly one of these should be set.
optional string identifier_value = 3;
optional uint64 positive_int_value = 4;
optional int64 negative_int_value = 5;
optional double double_value = 6;
optional bytes string_value = 7;
optional string aggregate_value = 8;
}
// ===================================================================
// Optional source code info
// Encapsulates information about the original source file from which a
// FileDescriptorProto was generated.
message SourceCodeInfo {
// A Location identifies a piece of source code in a .proto file which
// corresponds to a particular definition. This information is intended
// to be useful to IDEs, code indexers, documentation generators, and similar
// tools.
//
// For example, say we have a file like:
// message Foo {
// optional string foo = 1;
// }
// Let's look at just the field definition:
// optional string foo = 1;
// ^ ^^ ^^ ^ ^^^
// a bc de f ghi
// We have the following locations:
// span path represents
// [a,i) [ 4, 0, 2, 0 ] The whole field definition.
// [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
// [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
// [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
// [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
//
// Notes:
// - A location may refer to a repeated field itself (i.e. not to any
// particular index within it). This is used whenever a set of elements are
// logically enclosed in a single code segment. For example, an entire
// extend block (possibly containing multiple extension definitions) will
// have an outer location whose path refers to the "extensions" repeated
// field without an index.
// - Multiple locations may have the same path. This happens when a single
// logical declaration is spread out across multiple places. The most
// obvious example is the "extend" block again -- there may be multiple
// extend blocks in the same scope, each of which will have the same path.
// - A location's span is not always a subset of its parent's span. For
// example, the "extendee" of an extension declaration appears at the
// beginning of the "extend" block and is shared by all extensions within
// the block.
// - Just because a location's span is a subset of some other location's span
// does not mean that it is a descendent. For example, a "group" defines
// both a type and a field in a single declaration. Thus, the locations
// corresponding to the type and field and their components will overlap.
// - Code which tries to interpret locations should probably be designed to
// ignore those that it doesn't understand, as more types of locations could
// be recorded in the future.
repeated Location location = 1;
message Location {
// Identifies which part of the FileDescriptorProto was defined at this
// location.
//
// Each element is a field number or an index. They form a path from
// the root FileDescriptorProto to the place where the definition. For
// example, this path:
// [ 4, 3, 2, 7, 1 ]
// refers to:
// file.message_type(3) // 4, 3
// .field(7) // 2, 7
// .name() // 1
// This is because FileDescriptorProto.message_type has field number 4:
// repeated DescriptorProto message_type = 4;
// and DescriptorProto.field has field number 2:
// repeated FieldDescriptorProto field = 2;
// and FieldDescriptorProto.name has field number 1:
// optional string name = 1;
//
// Thus, the above path gives the location of a field name. If we removed
// the last element:
// [ 4, 3, 2, 7 ]
// this path refers to the whole field declaration (from the beginning
// of the label to the terminating semicolon).
repeated int32 path = 1 [packed=true];
// Always has exactly three or four elements: start line, start column,
// end line (optional, otherwise assumed same as start line), end column.
// These are packed into a single field for efficiency. Note that line
// and column numbers are zero-based -- typically you will want to add
// 1 to each before displaying to a user.
repeated int32 span = 2 [packed=true];
// If this SourceCodeInfo represents a complete declaration, these are any
// comments appearing before and after the declaration which appear to be
// attached to the declaration.
//
// A series of line comments appearing on consecutive lines, with no other
// tokens appearing on those lines, will be treated as a single comment.
//
// Only the comment content is provided; comment markers (e.g. //) are
// stripped out. For block comments, leading whitespace and an asterisk
// will be stripped from the beginning of each line other than the first.
// Newlines are included in the output.
//
// Examples:
//
// optional int32 foo = 1; // Comment attached to foo.
// // Comment attached to bar.
// optional int32 bar = 2;
//
// optional string baz = 3;
// // Comment attached to baz.
// // Another line attached to baz.
//
// // Comment attached to qux.
// //
// // Another line attached to qux.
// optional double qux = 4;
//
// optional string corge = 5;
// /* Block comment attached
// * to corge. Leading asterisks
// * will be removed. */
// /* Block comment attached to
// * grault. */
// optional int32 grault = 6;
optional string leading_comments = 3;
optional string trailing_comments = 4;
}
}

@ -1,719 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file we will use for unit testing.
// Some generic_services option(s) added automatically.
// See: http://go/proto2-generic-services-default
option cc_generic_services = true; // auto-added
option java_generic_services = true; // auto-added
option py_generic_services = true; // auto-added
import "google/protobuf/unittest_import.proto";
// We don't put this in a package within proto2 because we need to make sure
// that the generated code doesn't depend on being in the proto2 namespace.
// In test_util.h we do "using namespace unittest = protobuf_unittest".
package protobuf_unittest;
// Protos optimized for SPEED use a strict superset of the generated code
// of equivalent ones optimized for CODE_SIZE, so we should optimize all our
// tests for speed unless explicitly testing code size optimization.
option optimize_for = SPEED;
option java_outer_classname = "UnittestProto";
// This proto includes every type of field in both singular and repeated
// forms.
message TestAllTypes {
message NestedMessage {
// The field name "b" fails to compile in proto1 because it conflicts with
// a local variable named "b" in one of the generated methods. Doh.
// This file needs to compile in proto1 to test backwards-compatibility.
optional int32 bb = 1;
}
enum NestedEnum {
FOO = 1;
BAR = 2;
BAZ = 3;
}
// Singular
optional int32 optional_int32 = 1;
optional int64 optional_int64 = 2;
optional uint32 optional_uint32 = 3;
optional uint64 optional_uint64 = 4;
optional sint32 optional_sint32 = 5;
optional sint64 optional_sint64 = 6;
optional fixed32 optional_fixed32 = 7;
optional fixed64 optional_fixed64 = 8;
optional sfixed32 optional_sfixed32 = 9;
optional sfixed64 optional_sfixed64 = 10;
optional float optional_float = 11;
optional double optional_double = 12;
optional bool optional_bool = 13;
optional string optional_string = 14;
optional bytes optional_bytes = 15;
optional group OptionalGroup = 16 {
optional int32 a = 17;
}
optional NestedMessage optional_nested_message = 18;
optional ForeignMessage optional_foreign_message = 19;
optional protobuf_unittest_import.ImportMessage optional_import_message = 20;
optional NestedEnum optional_nested_enum = 21;
optional ForeignEnum optional_foreign_enum = 22;
optional protobuf_unittest_import.ImportEnum optional_import_enum = 23;
optional string optional_string_piece = 24 [ctype=STRING_PIECE];
optional string optional_cord = 25 [ctype=CORD];
// Defined in unittest_import_public.proto
optional protobuf_unittest_import.PublicImportMessage
optional_public_import_message = 26;
optional NestedMessage optional_lazy_message = 27 [lazy=true];
// Repeated
repeated int32 repeated_int32 = 31;
repeated int64 repeated_int64 = 32;
repeated uint32 repeated_uint32 = 33;
repeated uint64 repeated_uint64 = 34;
repeated sint32 repeated_sint32 = 35;
repeated sint64 repeated_sint64 = 36;
repeated fixed32 repeated_fixed32 = 37;
repeated fixed64 repeated_fixed64 = 38;
repeated sfixed32 repeated_sfixed32 = 39;
repeated sfixed64 repeated_sfixed64 = 40;
repeated float repeated_float = 41;
repeated double repeated_double = 42;
repeated bool repeated_bool = 43;
repeated string repeated_string = 44;
repeated bytes repeated_bytes = 45;
repeated group RepeatedGroup = 46 {
optional int32 a = 47;
}
repeated NestedMessage repeated_nested_message = 48;
repeated ForeignMessage repeated_foreign_message = 49;
repeated protobuf_unittest_import.ImportMessage repeated_import_message = 50;
repeated NestedEnum repeated_nested_enum = 51;
repeated ForeignEnum repeated_foreign_enum = 52;
repeated protobuf_unittest_import.ImportEnum repeated_import_enum = 53;
repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
repeated string repeated_cord = 55 [ctype=CORD];
repeated NestedMessage repeated_lazy_message = 57 [lazy=true];
// Singular with defaults
optional int32 default_int32 = 61 [default = 41 ];
optional int64 default_int64 = 62 [default = 42 ];
optional uint32 default_uint32 = 63 [default = 43 ];
optional uint64 default_uint64 = 64 [default = 44 ];
optional sint32 default_sint32 = 65 [default = -45 ];
optional sint64 default_sint64 = 66 [default = 46 ];
optional fixed32 default_fixed32 = 67 [default = 47 ];
optional fixed64 default_fixed64 = 68 [default = 48 ];
optional sfixed32 default_sfixed32 = 69 [default = 49 ];
optional sfixed64 default_sfixed64 = 70 [default = -50 ];
optional float default_float = 71 [default = 51.5 ];
optional double default_double = 72 [default = 52e3 ];
optional bool default_bool = 73 [default = true ];
optional string default_string = 74 [default = "hello"];
optional bytes default_bytes = 75 [default = "world"];
optional NestedEnum default_nested_enum = 81 [default = BAR ];
optional ForeignEnum default_foreign_enum = 82 [default = FOREIGN_BAR];
optional protobuf_unittest_import.ImportEnum
default_import_enum = 83 [default = IMPORT_BAR];
optional string default_string_piece = 84 [ctype=STRING_PIECE,default="abc"];
optional string default_cord = 85 [ctype=CORD,default="123"];
}
message TestDeprecatedFields {
optional int32 deprecated_int32 = 1 [deprecated=true];
}
// Define these after TestAllTypes to make sure the compiler can handle
// that.
message ForeignMessage {
optional int32 c = 1;
}
enum ForeignEnum {
FOREIGN_FOO = 4;
FOREIGN_BAR = 5;
FOREIGN_BAZ = 6;
}
message TestAllExtensions {
extensions 1 to max;
}
extend TestAllExtensions {
// Singular
optional int32 optional_int32_extension = 1;
optional int64 optional_int64_extension = 2;
optional uint32 optional_uint32_extension = 3;
optional uint64 optional_uint64_extension = 4;
optional sint32 optional_sint32_extension = 5;
optional sint64 optional_sint64_extension = 6;
optional fixed32 optional_fixed32_extension = 7;
optional fixed64 optional_fixed64_extension = 8;
optional sfixed32 optional_sfixed32_extension = 9;
optional sfixed64 optional_sfixed64_extension = 10;
optional float optional_float_extension = 11;
optional double optional_double_extension = 12;
optional bool optional_bool_extension = 13;
optional string optional_string_extension = 14;
optional bytes optional_bytes_extension = 15;
optional group OptionalGroup_extension = 16 {
optional int32 a = 17;
}
optional TestAllTypes.NestedMessage optional_nested_message_extension = 18;
optional ForeignMessage optional_foreign_message_extension = 19;
optional protobuf_unittest_import.ImportMessage
optional_import_message_extension = 20;
optional TestAllTypes.NestedEnum optional_nested_enum_extension = 21;
optional ForeignEnum optional_foreign_enum_extension = 22;
optional protobuf_unittest_import.ImportEnum
optional_import_enum_extension = 23;
optional string optional_string_piece_extension = 24 [ctype=STRING_PIECE];
optional string optional_cord_extension = 25 [ctype=CORD];
optional protobuf_unittest_import.PublicImportMessage
optional_public_import_message_extension = 26;
optional TestAllTypes.NestedMessage
optional_lazy_message_extension = 27 [lazy=true];
// Repeated
repeated int32 repeated_int32_extension = 31;
repeated int64 repeated_int64_extension = 32;
repeated uint32 repeated_uint32_extension = 33;
repeated uint64 repeated_uint64_extension = 34;
repeated sint32 repeated_sint32_extension = 35;
repeated sint64 repeated_sint64_extension = 36;
repeated fixed32 repeated_fixed32_extension = 37;
repeated fixed64 repeated_fixed64_extension = 38;
repeated sfixed32 repeated_sfixed32_extension = 39;
repeated sfixed64 repeated_sfixed64_extension = 40;
repeated float repeated_float_extension = 41;
repeated double repeated_double_extension = 42;
repeated bool repeated_bool_extension = 43;
repeated string repeated_string_extension = 44;
repeated bytes repeated_bytes_extension = 45;
repeated group RepeatedGroup_extension = 46 {
optional int32 a = 47;
}
repeated TestAllTypes.NestedMessage repeated_nested_message_extension = 48;
repeated ForeignMessage repeated_foreign_message_extension = 49;
repeated protobuf_unittest_import.ImportMessage
repeated_import_message_extension = 50;
repeated TestAllTypes.NestedEnum repeated_nested_enum_extension = 51;
repeated ForeignEnum repeated_foreign_enum_extension = 52;
repeated protobuf_unittest_import.ImportEnum
repeated_import_enum_extension = 53;
repeated string repeated_string_piece_extension = 54 [ctype=STRING_PIECE];
repeated string repeated_cord_extension = 55 [ctype=CORD];
repeated TestAllTypes.NestedMessage
repeated_lazy_message_extension = 57 [lazy=true];
// Singular with defaults
optional int32 default_int32_extension = 61 [default = 41 ];
optional int64 default_int64_extension = 62 [default = 42 ];
optional uint32 default_uint32_extension = 63 [default = 43 ];
optional uint64 default_uint64_extension = 64 [default = 44 ];
optional sint32 default_sint32_extension = 65 [default = -45 ];
optional sint64 default_sint64_extension = 66 [default = 46 ];
optional fixed32 default_fixed32_extension = 67 [default = 47 ];
optional fixed64 default_fixed64_extension = 68 [default = 48 ];
optional sfixed32 default_sfixed32_extension = 69 [default = 49 ];
optional sfixed64 default_sfixed64_extension = 70 [default = -50 ];
optional float default_float_extension = 71 [default = 51.5 ];
optional double default_double_extension = 72 [default = 52e3 ];
optional bool default_bool_extension = 73 [default = true ];
optional string default_string_extension = 74 [default = "hello"];
optional bytes default_bytes_extension = 75 [default = "world"];
optional TestAllTypes.NestedEnum
default_nested_enum_extension = 81 [default = BAR];
optional ForeignEnum
default_foreign_enum_extension = 82 [default = FOREIGN_BAR];
optional protobuf_unittest_import.ImportEnum
default_import_enum_extension = 83 [default = IMPORT_BAR];
optional string default_string_piece_extension = 84 [ctype=STRING_PIECE,
default="abc"];
optional string default_cord_extension = 85 [ctype=CORD, default="123"];
}
message TestNestedExtension {
extend TestAllExtensions {
// Check for bug where string extensions declared in tested scope did not
// compile.
optional string test = 1002 [default="test"];
}
}
// We have separate messages for testing required fields because it's
// annoying to have to fill in required fields in TestProto in order to
// do anything with it. Note that we don't need to test every type of
// required filed because the code output is basically identical to
// optional fields for all types.
message TestRequired {
required int32 a = 1;
optional int32 dummy2 = 2;
required int32 b = 3;
extend TestAllExtensions {
optional TestRequired single = 1000;
repeated TestRequired multi = 1001;
}
// Pad the field count to 32 so that we can test that IsInitialized()
// properly checks multiple elements of has_bits_.
optional int32 dummy4 = 4;
optional int32 dummy5 = 5;
optional int32 dummy6 = 6;
optional int32 dummy7 = 7;
optional int32 dummy8 = 8;
optional int32 dummy9 = 9;
optional int32 dummy10 = 10;
optional int32 dummy11 = 11;
optional int32 dummy12 = 12;
optional int32 dummy13 = 13;
optional int32 dummy14 = 14;
optional int32 dummy15 = 15;
optional int32 dummy16 = 16;
optional int32 dummy17 = 17;
optional int32 dummy18 = 18;
optional int32 dummy19 = 19;
optional int32 dummy20 = 20;
optional int32 dummy21 = 21;
optional int32 dummy22 = 22;
optional int32 dummy23 = 23;
optional int32 dummy24 = 24;
optional int32 dummy25 = 25;
optional int32 dummy26 = 26;
optional int32 dummy27 = 27;
optional int32 dummy28 = 28;
optional int32 dummy29 = 29;
optional int32 dummy30 = 30;
optional int32 dummy31 = 31;
optional int32 dummy32 = 32;
required int32 c = 33;
}
message TestRequiredForeign {
optional TestRequired optional_message = 1;
repeated TestRequired repeated_message = 2;
optional int32 dummy = 3;
}
// Test that we can use NestedMessage from outside TestAllTypes.
message TestForeignNested {
optional TestAllTypes.NestedMessage foreign_nested = 1;
}
// TestEmptyMessage is used to test unknown field support.
message TestEmptyMessage {
}
// Like above, but declare all field numbers as potential extensions. No
// actual extensions should ever be defined for this type.
message TestEmptyMessageWithExtensions {
extensions 1 to max;
}
message TestMultipleExtensionRanges {
extensions 42;
extensions 4143 to 4243;
extensions 65536 to max;
}
// Test that really large tag numbers don't break anything.
message TestReallyLargeTagNumber {
// The largest possible tag number is 2^28 - 1, since the wire format uses
// three bits to communicate wire type.
optional int32 a = 1;
optional int32 bb = 268435455;
}
message TestRecursiveMessage {
optional TestRecursiveMessage a = 1;
optional int32 i = 2;
}
// Test that mutual recursion works.
message TestMutualRecursionA {
optional TestMutualRecursionB bb = 1;
}
message TestMutualRecursionB {
optional TestMutualRecursionA a = 1;
optional int32 optional_int32 = 2;
}
// Test that groups have disjoint field numbers from their siblings and
// parents. This is NOT possible in proto1; only proto2. When attempting
// to compile with proto1, this will emit an error; so we only include it
// in protobuf_unittest_proto.
message TestDupFieldNumber { // NO_PROTO1
optional int32 a = 1; // NO_PROTO1
optional group Foo = 2 { optional int32 a = 1; } // NO_PROTO1
optional group Bar = 3 { optional int32 a = 1; } // NO_PROTO1
} // NO_PROTO1
// Additional messages for testing lazy fields.
message TestEagerMessage {
optional TestAllTypes sub_message = 1 [lazy=false];
}
message TestLazyMessage {
optional TestAllTypes sub_message = 1 [lazy=true];
}
// Needed for a Python test.
message TestNestedMessageHasBits {
message NestedMessage {
repeated int32 nestedmessage_repeated_int32 = 1;
repeated ForeignMessage nestedmessage_repeated_foreignmessage = 2;
}
optional NestedMessage optional_nested_message = 1;
}
// Test an enum that has multiple values with the same number.
enum TestEnumWithDupValue {
option allow_alias = true;
FOO1 = 1;
BAR1 = 2;
BAZ = 3;
FOO2 = 1;
BAR2 = 2;
}
// Test an enum with large, unordered values.
enum TestSparseEnum {
SPARSE_A = 123;
SPARSE_B = 62374;
SPARSE_C = 12589234;
SPARSE_D = -15;
SPARSE_E = -53452;
SPARSE_F = 0;
SPARSE_G = 2;
}
// Test message with CamelCase field names. This violates Protocol Buffer
// standard style.
message TestCamelCaseFieldNames {
optional int32 PrimitiveField = 1;
optional string StringField = 2;
optional ForeignEnum EnumField = 3;
optional ForeignMessage MessageField = 4;
optional string StringPieceField = 5 [ctype=STRING_PIECE];
optional string CordField = 6 [ctype=CORD];
repeated int32 RepeatedPrimitiveField = 7;
repeated string RepeatedStringField = 8;
repeated ForeignEnum RepeatedEnumField = 9;
repeated ForeignMessage RepeatedMessageField = 10;
repeated string RepeatedStringPieceField = 11 [ctype=STRING_PIECE];
repeated string RepeatedCordField = 12 [ctype=CORD];
}
// We list fields out of order, to ensure that we're using field number and not
// field index to determine serialization order.
message TestFieldOrderings {
optional string my_string = 11;
extensions 2 to 10;
optional int64 my_int = 1;
extensions 12 to 100;
optional float my_float = 101;
}
extend TestFieldOrderings {
optional string my_extension_string = 50;
optional int32 my_extension_int = 5;
}
message TestExtremeDefaultValues {
optional bytes escaped_bytes = 1 [default = "\0\001\a\b\f\n\r\t\v\\\'\"\xfe"];
optional uint32 large_uint32 = 2 [default = 0xFFFFFFFF];
optional uint64 large_uint64 = 3 [default = 0xFFFFFFFFFFFFFFFF];
optional int32 small_int32 = 4 [default = -0x7FFFFFFF];
optional int64 small_int64 = 5 [default = -0x7FFFFFFFFFFFFFFF];
optional int32 really_small_int32 = 21 [default = -0x80000000];
optional int64 really_small_int64 = 22 [default = -0x8000000000000000];
// The default value here is UTF-8 for "\u1234". (We could also just type
// the UTF-8 text directly into this text file rather than escape it, but
// lots of people use editors that would be confused by this.)
optional string utf8_string = 6 [default = "\341\210\264"];
// Tests for single-precision floating-point values.
optional float zero_float = 7 [default = 0];
optional float one_float = 8 [default = 1];
optional float small_float = 9 [default = 1.5];
optional float negative_one_float = 10 [default = -1];
optional float negative_float = 11 [default = -1.5];
// Using exponents
optional float large_float = 12 [default = 2E8];
optional float small_negative_float = 13 [default = -8e-28];
// Text for nonfinite floating-point values.
optional double inf_double = 14 [default = inf];
optional double neg_inf_double = 15 [default = -inf];
optional double nan_double = 16 [default = nan];
optional float inf_float = 17 [default = inf];
optional float neg_inf_float = 18 [default = -inf];
optional float nan_float = 19 [default = nan];
// Tests for C++ trigraphs.
// Trigraphs should be escaped in C++ generated files, but they should not be
// escaped for other languages.
// Note that in .proto file, "\?" is a valid way to escape ? in string
// literals.
optional string cpp_trigraph = 20 [default = "? \? ?? \?? \??? ??/ ?\?-"];
// String defaults containing the character '\000'
optional string string_with_zero = 23 [default = "hel\000lo"];
optional bytes bytes_with_zero = 24 [default = "wor\000ld"];
optional string string_piece_with_zero = 25 [ctype=STRING_PIECE,
default="ab\000c"];
optional string cord_with_zero = 26 [ctype=CORD,
default="12\0003"];
}
message SparseEnumMessage {
optional TestSparseEnum sparse_enum = 1;
}
// Test String and Bytes: string is for valid UTF-8 strings
message OneString {
optional string data = 1;
}
message MoreString {
repeated string data = 1;
}
message OneBytes {
optional bytes data = 1;
}
message MoreBytes {
repeated bytes data = 1;
}
// Test messages for packed fields
message TestPackedTypes {
repeated int32 packed_int32 = 90 [packed = true];
repeated int64 packed_int64 = 91 [packed = true];
repeated uint32 packed_uint32 = 92 [packed = true];
repeated uint64 packed_uint64 = 93 [packed = true];
repeated sint32 packed_sint32 = 94 [packed = true];
repeated sint64 packed_sint64 = 95 [packed = true];
repeated fixed32 packed_fixed32 = 96 [packed = true];
repeated fixed64 packed_fixed64 = 97 [packed = true];
repeated sfixed32 packed_sfixed32 = 98 [packed = true];
repeated sfixed64 packed_sfixed64 = 99 [packed = true];
repeated float packed_float = 100 [packed = true];
repeated double packed_double = 101 [packed = true];
repeated bool packed_bool = 102 [packed = true];
repeated ForeignEnum packed_enum = 103 [packed = true];
}
// A message with the same fields as TestPackedTypes, but without packing. Used
// to test packed <-> unpacked wire compatibility.
message TestUnpackedTypes {
repeated int32 unpacked_int32 = 90 [packed = false];
repeated int64 unpacked_int64 = 91 [packed = false];
repeated uint32 unpacked_uint32 = 92 [packed = false];
repeated uint64 unpacked_uint64 = 93 [packed = false];
repeated sint32 unpacked_sint32 = 94 [packed = false];
repeated sint64 unpacked_sint64 = 95 [packed = false];
repeated fixed32 unpacked_fixed32 = 96 [packed = false];
repeated fixed64 unpacked_fixed64 = 97 [packed = false];
repeated sfixed32 unpacked_sfixed32 = 98 [packed = false];
repeated sfixed64 unpacked_sfixed64 = 99 [packed = false];
repeated float unpacked_float = 100 [packed = false];
repeated double unpacked_double = 101 [packed = false];
repeated bool unpacked_bool = 102 [packed = false];
repeated ForeignEnum unpacked_enum = 103 [packed = false];
}
message TestPackedExtensions {
extensions 1 to max;
}
extend TestPackedExtensions {
repeated int32 packed_int32_extension = 90 [packed = true];
repeated int64 packed_int64_extension = 91 [packed = true];
repeated uint32 packed_uint32_extension = 92 [packed = true];
repeated uint64 packed_uint64_extension = 93 [packed = true];
repeated sint32 packed_sint32_extension = 94 [packed = true];
repeated sint64 packed_sint64_extension = 95 [packed = true];
repeated fixed32 packed_fixed32_extension = 96 [packed = true];
repeated fixed64 packed_fixed64_extension = 97 [packed = true];
repeated sfixed32 packed_sfixed32_extension = 98 [packed = true];
repeated sfixed64 packed_sfixed64_extension = 99 [packed = true];
repeated float packed_float_extension = 100 [packed = true];
repeated double packed_double_extension = 101 [packed = true];
repeated bool packed_bool_extension = 102 [packed = true];
repeated ForeignEnum packed_enum_extension = 103 [packed = true];
}
// Used by ExtensionSetTest/DynamicExtensions. The test actually builds
// a set of extensions to TestAllExtensions dynamically, based on the fields
// of this message type.
message TestDynamicExtensions {
enum DynamicEnumType {
DYNAMIC_FOO = 2200;
DYNAMIC_BAR = 2201;
DYNAMIC_BAZ = 2202;
}
message DynamicMessageType {
optional int32 dynamic_field = 2100;
}
optional fixed32 scalar_extension = 2000;
optional ForeignEnum enum_extension = 2001;
optional DynamicEnumType dynamic_enum_extension = 2002;
optional ForeignMessage message_extension = 2003;
optional DynamicMessageType dynamic_message_extension = 2004;
repeated string repeated_extension = 2005;
repeated sint32 packed_extension = 2006 [packed = true];
}
message TestRepeatedScalarDifferentTagSizes {
// Parsing repeated fixed size values used to fail. This message needs to be
// used in order to get a tag of the right size; all of the repeated fields
// in TestAllTypes didn't trigger the check.
repeated fixed32 repeated_fixed32 = 12;
// Check for a varint type, just for good measure.
repeated int32 repeated_int32 = 13;
// These have two-byte tags.
repeated fixed64 repeated_fixed64 = 2046;
repeated int64 repeated_int64 = 2047;
// Three byte tags.
repeated float repeated_float = 262142;
repeated uint64 repeated_uint64 = 262143;
}
// Test that if an optional or required message/group field appears multiple
// times in the input, they need to be merged.
message TestParsingMerge {
// RepeatedFieldsGenerator defines matching field types as TestParsingMerge,
// except that all fields are repeated. In the tests, we will serialize the
// RepeatedFieldsGenerator to bytes, and parse the bytes to TestParsingMerge.
// Repeated fields in RepeatedFieldsGenerator are expected to be merged into
// the corresponding required/optional fields in TestParsingMerge.
message RepeatedFieldsGenerator {
repeated TestAllTypes field1 = 1;
repeated TestAllTypes field2 = 2;
repeated TestAllTypes field3 = 3;
repeated group Group1 = 10 {
optional TestAllTypes field1 = 11;
}
repeated group Group2 = 20 {
optional TestAllTypes field1 = 21;
}
repeated TestAllTypes ext1 = 1000;
repeated TestAllTypes ext2 = 1001;
}
required TestAllTypes required_all_types = 1;
optional TestAllTypes optional_all_types = 2;
repeated TestAllTypes repeated_all_types = 3;
optional group OptionalGroup = 10 {
optional TestAllTypes optional_group_all_types = 11;
}
repeated group RepeatedGroup = 20 {
optional TestAllTypes repeated_group_all_types = 21;
}
extensions 1000 to max;
extend TestParsingMerge {
optional TestAllTypes optional_ext = 1000;
repeated TestAllTypes repeated_ext = 1001;
}
}
message TestCommentInjectionMessage {
// */ <- This should not close the generated doc comment
optional string a = 1 [default="*/ <- Neither should this."];
}
// Test that RPC services work.
message FooRequest {}
message FooResponse {}
message FooClientMessage {}
message FooServerMessage{}
service TestService {
rpc Foo(FooRequest) returns (FooResponse);
rpc Bar(BarRequest) returns (BarResponse);
}
message BarRequest {}
message BarResponse {}

@ -1,387 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: benjy@google.com (Benjy Weinberger)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file used to test the "custom options" feature of proto2.
// Some generic_services option(s) added automatically.
// See: http://go/proto2-generic-services-default
option cc_generic_services = true; // auto-added
option java_generic_services = true; // auto-added
option py_generic_services = true;
// A custom file option (defined below).
option (file_opt1) = 9876543210;
import "google/protobuf/descriptor.proto";
// We don't put this in a package within proto2 because we need to make sure
// that the generated code doesn't depend on being in the proto2 namespace.
package protobuf_unittest;
// Some simple test custom options of various types.
extend google.protobuf.FileOptions {
optional uint64 file_opt1 = 7736974;
}
extend google.protobuf.MessageOptions {
optional int32 message_opt1 = 7739036;
}
extend google.protobuf.FieldOptions {
optional fixed64 field_opt1 = 7740936;
// This is useful for testing that we correctly register default values for
// extension options.
optional int32 field_opt2 = 7753913 [default=42];
}
extend google.protobuf.EnumOptions {
optional sfixed32 enum_opt1 = 7753576;
}
extend google.protobuf.EnumValueOptions {
optional int32 enum_value_opt1 = 1560678;
}
extend google.protobuf.ServiceOptions {
optional sint64 service_opt1 = 7887650;
}
enum MethodOpt1 {
METHODOPT1_VAL1 = 1;
METHODOPT1_VAL2 = 2;
}
extend google.protobuf.MethodOptions {
optional MethodOpt1 method_opt1 = 7890860;
}
// A test message with custom options at all possible locations (and also some
// regular options, to make sure they interact nicely).
message TestMessageWithCustomOptions {
option message_set_wire_format = false;
option (message_opt1) = -56;
optional string field1 = 1 [ctype=CORD,
(field_opt1)=8765432109];
enum AnEnum {
option (enum_opt1) = -789;
ANENUM_VAL1 = 1;
ANENUM_VAL2 = 2 [(enum_value_opt1) = 123];
}
}
// A test RPC service with custom options at all possible locations (and also
// some regular options, to make sure they interact nicely).
message CustomOptionFooRequest {
}
message CustomOptionFooResponse {
}
message CustomOptionFooClientMessage {
}
message CustomOptionFooServerMessage {
}
service TestServiceWithCustomOptions {
option (service_opt1) = -9876543210;
rpc Foo(CustomOptionFooRequest) returns (CustomOptionFooResponse) {
option (method_opt1) = METHODOPT1_VAL2;
}
}
// Options of every possible field type, so we can test them all exhaustively.
message DummyMessageContainingEnum {
enum TestEnumType {
TEST_OPTION_ENUM_TYPE1 = 22;
TEST_OPTION_ENUM_TYPE2 = -23;
}
}
message DummyMessageInvalidAsOptionType {
}
extend google.protobuf.MessageOptions {
optional bool bool_opt = 7706090;
optional int32 int32_opt = 7705709;
optional int64 int64_opt = 7705542;
optional uint32 uint32_opt = 7704880;
optional uint64 uint64_opt = 7702367;
optional sint32 sint32_opt = 7701568;
optional sint64 sint64_opt = 7700863;
optional fixed32 fixed32_opt = 7700307;
optional fixed64 fixed64_opt = 7700194;
optional sfixed32 sfixed32_opt = 7698645;
optional sfixed64 sfixed64_opt = 7685475;
optional float float_opt = 7675390;
optional double double_opt = 7673293;
optional string string_opt = 7673285;
optional bytes bytes_opt = 7673238;
optional DummyMessageContainingEnum.TestEnumType enum_opt = 7673233;
optional DummyMessageInvalidAsOptionType message_type_opt = 7665967;
}
message CustomOptionMinIntegerValues {
option (bool_opt) = false;
option (int32_opt) = -0x80000000;
option (int64_opt) = -0x8000000000000000;
option (uint32_opt) = 0;
option (uint64_opt) = 0;
option (sint32_opt) = -0x80000000;
option (sint64_opt) = -0x8000000000000000;
option (fixed32_opt) = 0;
option (fixed64_opt) = 0;
option (sfixed32_opt) = -0x80000000;
option (sfixed64_opt) = -0x8000000000000000;
}
message CustomOptionMaxIntegerValues {
option (bool_opt) = true;
option (int32_opt) = 0x7FFFFFFF;
option (int64_opt) = 0x7FFFFFFFFFFFFFFF;
option (uint32_opt) = 0xFFFFFFFF;
option (uint64_opt) = 0xFFFFFFFFFFFFFFFF;
option (sint32_opt) = 0x7FFFFFFF;
option (sint64_opt) = 0x7FFFFFFFFFFFFFFF;
option (fixed32_opt) = 0xFFFFFFFF;
option (fixed64_opt) = 0xFFFFFFFFFFFFFFFF;
option (sfixed32_opt) = 0x7FFFFFFF;
option (sfixed64_opt) = 0x7FFFFFFFFFFFFFFF;
}
message CustomOptionOtherValues {
option (int32_opt) = -100; // To test sign-extension.
option (float_opt) = 12.3456789;
option (double_opt) = 1.234567890123456789;
option (string_opt) = "Hello, \"World\"";
option (bytes_opt) = "Hello\0World";
option (enum_opt) = TEST_OPTION_ENUM_TYPE2;
}
message SettingRealsFromPositiveInts {
option (float_opt) = 12;
option (double_opt) = 154;
}
message SettingRealsFromNegativeInts {
option (float_opt) = -12;
option (double_opt) = -154;
}
// Options of complex message types, themselves combined and extended in
// various ways.
message ComplexOptionType1 {
optional int32 foo = 1;
optional int32 foo2 = 2;
optional int32 foo3 = 3;
extensions 100 to max;
}
message ComplexOptionType2 {
optional ComplexOptionType1 bar = 1;
optional int32 baz = 2;
message ComplexOptionType4 {
optional int32 waldo = 1;
extend google.protobuf.MessageOptions {
optional ComplexOptionType4 complex_opt4 = 7633546;
}
}
optional ComplexOptionType4 fred = 3;
extensions 100 to max;
}
message ComplexOptionType3 {
optional int32 qux = 1;
optional group ComplexOptionType5 = 2 {
optional int32 plugh = 3;
}
}
extend ComplexOptionType1 {
optional int32 quux = 7663707;
optional ComplexOptionType3 corge = 7663442;
}
extend ComplexOptionType2 {
optional int32 grault = 7650927;
optional ComplexOptionType1 garply = 7649992;
}
extend google.protobuf.MessageOptions {
optional protobuf_unittest.ComplexOptionType1 complex_opt1 = 7646756;
optional ComplexOptionType2 complex_opt2 = 7636949;
optional ComplexOptionType3 complex_opt3 = 7636463;
optional group ComplexOpt6 = 7595468 {
optional int32 xyzzy = 7593951;
}
}
// Note that we try various different ways of naming the same extension.
message VariousComplexOptions {
option (.protobuf_unittest.complex_opt1).foo = 42;
option (protobuf_unittest.complex_opt1).(.protobuf_unittest.quux) = 324;
option (.protobuf_unittest.complex_opt1).(protobuf_unittest.corge).qux = 876;
option (complex_opt2).baz = 987;
option (complex_opt2).(grault) = 654;
option (complex_opt2).bar.foo = 743;
option (complex_opt2).bar.(quux) = 1999;
option (complex_opt2).bar.(protobuf_unittest.corge).qux = 2008;
option (complex_opt2).(garply).foo = 741;
option (complex_opt2).(garply).(.protobuf_unittest.quux) = 1998;
option (complex_opt2).(protobuf_unittest.garply).(corge).qux = 2121;
option (ComplexOptionType2.ComplexOptionType4.complex_opt4).waldo = 1971;
option (complex_opt2).fred.waldo = 321;
option (protobuf_unittest.complex_opt3).qux = 9;
option (complex_opt3).complexoptiontype5.plugh = 22;
option (complexopt6).xyzzy = 24;
}
// ------------------------------------------------------
// Definitions for testing aggregate option parsing.
// See descriptor_unittest.cc.
message AggregateMessageSet {
option message_set_wire_format = true;
extensions 4 to max;
}
message AggregateMessageSetElement {
extend AggregateMessageSet {
optional AggregateMessageSetElement message_set_extension = 15447542;
}
optional string s = 1;
}
// A helper type used to test aggregate option parsing
message Aggregate {
optional int32 i = 1;
optional string s = 2;
// A nested object
optional Aggregate sub = 3;
// To test the parsing of extensions inside aggregate values
optional google.protobuf.FileOptions file = 4;
extend google.protobuf.FileOptions {
optional Aggregate nested = 15476903;
}
// An embedded message set
optional AggregateMessageSet mset = 5;
}
// Allow Aggregate to be used as an option at all possible locations
// in the .proto grammar.
extend google.protobuf.FileOptions { optional Aggregate fileopt = 15478479; }
extend google.protobuf.MessageOptions { optional Aggregate msgopt = 15480088; }
extend google.protobuf.FieldOptions { optional Aggregate fieldopt = 15481374; }
extend google.protobuf.EnumOptions { optional Aggregate enumopt = 15483218; }
extend google.protobuf.EnumValueOptions { optional Aggregate enumvalopt = 15486921; }
extend google.protobuf.ServiceOptions { optional Aggregate serviceopt = 15497145; }
extend google.protobuf.MethodOptions { optional Aggregate methodopt = 15512713; }
// Try using AggregateOption at different points in the proto grammar
option (fileopt) = {
s: 'FileAnnotation'
// Also test the handling of comments
/* of both types */ i: 100
sub { s: 'NestedFileAnnotation' }
// Include a google.protobuf.FileOptions and recursively extend it with
// another fileopt.
file {
[protobuf_unittest.fileopt] {
s:'FileExtensionAnnotation'
}
}
// A message set inside an option value
mset {
[protobuf_unittest.AggregateMessageSetElement.message_set_extension] {
s: 'EmbeddedMessageSetElement'
}
}
};
message AggregateMessage {
option (msgopt) = { i:101 s:'MessageAnnotation' };
optional int32 fieldname = 1 [(fieldopt) = { s:'FieldAnnotation' }];
}
service AggregateService {
option (serviceopt) = { s:'ServiceAnnotation' };
rpc Method (AggregateMessage) returns (AggregateMessage) {
option (methodopt) = { s:'MethodAnnotation' };
}
}
enum AggregateEnum {
option (enumopt) = { s:'EnumAnnotation' };
VALUE = 1 [(enumvalopt) = { s:'EnumValueAnnotation' }];
}
// Test custom options for nested type.
message NestedOptionType {
message NestedMessage {
option (message_opt1) = 1001;
optional int32 nested_field = 1 [(field_opt1) = 1002];
}
enum NestedEnum {
option (enum_opt1) = 1003;
NESTED_ENUM_VALUE = 1 [(enum_value_opt1) = 1004];
}
extend google.protobuf.FileOptions {
optional int32 nested_extension = 7912573 [(field_opt2) = 1005];
}
}

@ -1,50 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file which imports a proto file that uses optimize_for = CODE_SIZE.
import "google/protobuf/unittest_optimize_for.proto";
package protobuf_unittest;
// We optimize for speed here, but we are importing a proto that is optimized
// for code size.
option optimize_for = SPEED;
message TestEmbedOptimizedForSize {
// Test that embedding a message which has optimize_for = CODE_SIZE into
// one optimized for speed works.
optional TestOptimizedForSize optional_message = 1;
repeated TestOptimizedForSize repeated_message = 2;
}

@ -1,37 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file intentionally left blank. (At one point this wouldn't compile
// correctly.)

@ -1,64 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file which is imported by unittest.proto to test importing.
// We don't put this in a package within proto2 because we need to make sure
// that the generated code doesn't depend on being in the proto2 namespace.
// In test_util.h we do
// "using namespace unittest_import = protobuf_unittest_import".
package protobuf_unittest_import;
option optimize_for = SPEED;
// Exercise the java_package option.
option java_package = "com.google.protobuf.test";
// Do not set a java_outer_classname here to verify that Proto2 works without
// one.
// Test public import
import public "google/protobuf/unittest_import_public.proto";
message ImportMessage {
optional int32 d = 1;
}
enum ImportEnum {
IMPORT_FOO = 7;
IMPORT_BAR = 8;
IMPORT_BAZ = 9;
}

@ -1,51 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
//
// This is like unittest_import.proto but with optimize_for = LITE_RUNTIME.
package protobuf_unittest_import;
option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf";
import public "google/protobuf/unittest_import_public_lite.proto";
message ImportMessageLite {
optional int32 d = 1;
}
enum ImportEnumLite {
IMPORT_LITE_FOO = 7;
IMPORT_LITE_BAR = 8;
IMPORT_LITE_BAZ = 9;
}

@ -1,40 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: liujisi@google.com (Pherl Liu)
package protobuf_unittest_import;
option java_package = "com.google.protobuf.test";
message PublicImportMessage {
optional int32 e = 1;
}

@ -1,42 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: liujisi@google.com (Pherl Liu)
package protobuf_unittest_import;
option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf";
message PublicImportMessageLite {
optional int32 e = 1;
}

@ -1,360 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
//
// This is like unittest.proto but with optimize_for = LITE_RUNTIME.
package protobuf_unittest;
import "google/protobuf/unittest_import_lite.proto";
option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf";
// Same as TestAllTypes but with the lite runtime.
message TestAllTypesLite {
message NestedMessage {
optional int32 bb = 1;
}
enum NestedEnum {
FOO = 1;
BAR = 2;
BAZ = 3;
}
// Singular
optional int32 optional_int32 = 1;
optional int64 optional_int64 = 2;
optional uint32 optional_uint32 = 3;
optional uint64 optional_uint64 = 4;
optional sint32 optional_sint32 = 5;
optional sint64 optional_sint64 = 6;
optional fixed32 optional_fixed32 = 7;
optional fixed64 optional_fixed64 = 8;
optional sfixed32 optional_sfixed32 = 9;
optional sfixed64 optional_sfixed64 = 10;
optional float optional_float = 11;
optional double optional_double = 12;
optional bool optional_bool = 13;
optional string optional_string = 14;
optional bytes optional_bytes = 15;
optional group OptionalGroup = 16 {
optional int32 a = 17;
}
optional NestedMessage optional_nested_message = 18;
optional ForeignMessageLite optional_foreign_message = 19;
optional protobuf_unittest_import.ImportMessageLite
optional_import_message = 20;
optional NestedEnum optional_nested_enum = 21;
optional ForeignEnumLite optional_foreign_enum = 22;
optional protobuf_unittest_import.ImportEnumLite optional_import_enum = 23;
optional string optional_string_piece = 24 [ctype=STRING_PIECE];
optional string optional_cord = 25 [ctype=CORD];
// Defined in unittest_import_public.proto
optional protobuf_unittest_import.PublicImportMessageLite
optional_public_import_message = 26;
optional NestedMessage optional_lazy_message = 27 [lazy=true];
// Repeated
repeated int32 repeated_int32 = 31;
repeated int64 repeated_int64 = 32;
repeated uint32 repeated_uint32 = 33;
repeated uint64 repeated_uint64 = 34;
repeated sint32 repeated_sint32 = 35;
repeated sint64 repeated_sint64 = 36;
repeated fixed32 repeated_fixed32 = 37;
repeated fixed64 repeated_fixed64 = 38;
repeated sfixed32 repeated_sfixed32 = 39;
repeated sfixed64 repeated_sfixed64 = 40;
repeated float repeated_float = 41;
repeated double repeated_double = 42;
repeated bool repeated_bool = 43;
repeated string repeated_string = 44;
repeated bytes repeated_bytes = 45;
repeated group RepeatedGroup = 46 {
optional int32 a = 47;
}
repeated NestedMessage repeated_nested_message = 48;
repeated ForeignMessageLite repeated_foreign_message = 49;
repeated protobuf_unittest_import.ImportMessageLite
repeated_import_message = 50;
repeated NestedEnum repeated_nested_enum = 51;
repeated ForeignEnumLite repeated_foreign_enum = 52;
repeated protobuf_unittest_import.ImportEnumLite repeated_import_enum = 53;
repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
repeated string repeated_cord = 55 [ctype=CORD];
repeated NestedMessage repeated_lazy_message = 57 [lazy=true];
// Singular with defaults
optional int32 default_int32 = 61 [default = 41 ];
optional int64 default_int64 = 62 [default = 42 ];
optional uint32 default_uint32 = 63 [default = 43 ];
optional uint64 default_uint64 = 64 [default = 44 ];
optional sint32 default_sint32 = 65 [default = -45 ];
optional sint64 default_sint64 = 66 [default = 46 ];
optional fixed32 default_fixed32 = 67 [default = 47 ];
optional fixed64 default_fixed64 = 68 [default = 48 ];
optional sfixed32 default_sfixed32 = 69 [default = 49 ];
optional sfixed64 default_sfixed64 = 70 [default = -50 ];
optional float default_float = 71 [default = 51.5 ];
optional double default_double = 72 [default = 52e3 ];
optional bool default_bool = 73 [default = true ];
optional string default_string = 74 [default = "hello"];
optional bytes default_bytes = 75 [default = "world"];
optional NestedEnum default_nested_enum = 81 [default = BAR];
optional ForeignEnumLite default_foreign_enum = 82
[default = FOREIGN_LITE_BAR];
optional protobuf_unittest_import.ImportEnumLite
default_import_enum = 83 [default = IMPORT_LITE_BAR];
optional string default_string_piece = 84 [ctype=STRING_PIECE,default="abc"];
optional string default_cord = 85 [ctype=CORD,default="123"];
}
message ForeignMessageLite {
optional int32 c = 1;
}
enum ForeignEnumLite {
FOREIGN_LITE_FOO = 4;
FOREIGN_LITE_BAR = 5;
FOREIGN_LITE_BAZ = 6;
}
message TestPackedTypesLite {
repeated int32 packed_int32 = 90 [packed = true];
repeated int64 packed_int64 = 91 [packed = true];
repeated uint32 packed_uint32 = 92 [packed = true];
repeated uint64 packed_uint64 = 93 [packed = true];
repeated sint32 packed_sint32 = 94 [packed = true];
repeated sint64 packed_sint64 = 95 [packed = true];
repeated fixed32 packed_fixed32 = 96 [packed = true];
repeated fixed64 packed_fixed64 = 97 [packed = true];
repeated sfixed32 packed_sfixed32 = 98 [packed = true];
repeated sfixed64 packed_sfixed64 = 99 [packed = true];
repeated float packed_float = 100 [packed = true];
repeated double packed_double = 101 [packed = true];
repeated bool packed_bool = 102 [packed = true];
repeated ForeignEnumLite packed_enum = 103 [packed = true];
}
message TestAllExtensionsLite {
extensions 1 to max;
}
extend TestAllExtensionsLite {
// Singular
optional int32 optional_int32_extension_lite = 1;
optional int64 optional_int64_extension_lite = 2;
optional uint32 optional_uint32_extension_lite = 3;
optional uint64 optional_uint64_extension_lite = 4;
optional sint32 optional_sint32_extension_lite = 5;
optional sint64 optional_sint64_extension_lite = 6;
optional fixed32 optional_fixed32_extension_lite = 7;
optional fixed64 optional_fixed64_extension_lite = 8;
optional sfixed32 optional_sfixed32_extension_lite = 9;
optional sfixed64 optional_sfixed64_extension_lite = 10;
optional float optional_float_extension_lite = 11;
optional double optional_double_extension_lite = 12;
optional bool optional_bool_extension_lite = 13;
optional string optional_string_extension_lite = 14;
optional bytes optional_bytes_extension_lite = 15;
optional group OptionalGroup_extension_lite = 16 {
optional int32 a = 17;
}
optional TestAllTypesLite.NestedMessage optional_nested_message_extension_lite
= 18;
optional ForeignMessageLite optional_foreign_message_extension_lite = 19;
optional protobuf_unittest_import.ImportMessageLite
optional_import_message_extension_lite = 20;
optional TestAllTypesLite.NestedEnum optional_nested_enum_extension_lite = 21;
optional ForeignEnumLite optional_foreign_enum_extension_lite = 22;
optional protobuf_unittest_import.ImportEnumLite
optional_import_enum_extension_lite = 23;
optional string optional_string_piece_extension_lite = 24
[ctype=STRING_PIECE];
optional string optional_cord_extension_lite = 25 [ctype=CORD];
optional protobuf_unittest_import.PublicImportMessageLite
optional_public_import_message_extension_lite = 26;
optional TestAllTypesLite.NestedMessage
optional_lazy_message_extension_lite = 27 [lazy=true];
// Repeated
repeated int32 repeated_int32_extension_lite = 31;
repeated int64 repeated_int64_extension_lite = 32;
repeated uint32 repeated_uint32_extension_lite = 33;
repeated uint64 repeated_uint64_extension_lite = 34;
repeated sint32 repeated_sint32_extension_lite = 35;
repeated sint64 repeated_sint64_extension_lite = 36;
repeated fixed32 repeated_fixed32_extension_lite = 37;
repeated fixed64 repeated_fixed64_extension_lite = 38;
repeated sfixed32 repeated_sfixed32_extension_lite = 39;
repeated sfixed64 repeated_sfixed64_extension_lite = 40;
repeated float repeated_float_extension_lite = 41;
repeated double repeated_double_extension_lite = 42;
repeated bool repeated_bool_extension_lite = 43;
repeated string repeated_string_extension_lite = 44;
repeated bytes repeated_bytes_extension_lite = 45;
repeated group RepeatedGroup_extension_lite = 46 {
optional int32 a = 47;
}
repeated TestAllTypesLite.NestedMessage repeated_nested_message_extension_lite
= 48;
repeated ForeignMessageLite repeated_foreign_message_extension_lite = 49;
repeated protobuf_unittest_import.ImportMessageLite
repeated_import_message_extension_lite = 50;
repeated TestAllTypesLite.NestedEnum repeated_nested_enum_extension_lite = 51;
repeated ForeignEnumLite repeated_foreign_enum_extension_lite = 52;
repeated protobuf_unittest_import.ImportEnumLite
repeated_import_enum_extension_lite = 53;
repeated string repeated_string_piece_extension_lite = 54
[ctype=STRING_PIECE];
repeated string repeated_cord_extension_lite = 55 [ctype=CORD];
repeated TestAllTypesLite.NestedMessage
repeated_lazy_message_extension_lite = 57 [lazy=true];
// Singular with defaults
optional int32 default_int32_extension_lite = 61 [default = 41 ];
optional int64 default_int64_extension_lite = 62 [default = 42 ];
optional uint32 default_uint32_extension_lite = 63 [default = 43 ];
optional uint64 default_uint64_extension_lite = 64 [default = 44 ];
optional sint32 default_sint32_extension_lite = 65 [default = -45 ];
optional sint64 default_sint64_extension_lite = 66 [default = 46 ];
optional fixed32 default_fixed32_extension_lite = 67 [default = 47 ];
optional fixed64 default_fixed64_extension_lite = 68 [default = 48 ];
optional sfixed32 default_sfixed32_extension_lite = 69 [default = 49 ];
optional sfixed64 default_sfixed64_extension_lite = 70 [default = -50 ];
optional float default_float_extension_lite = 71 [default = 51.5 ];
optional double default_double_extension_lite = 72 [default = 52e3 ];
optional bool default_bool_extension_lite = 73 [default = true ];
optional string default_string_extension_lite = 74 [default = "hello"];
optional bytes default_bytes_extension_lite = 75 [default = "world"];
optional TestAllTypesLite.NestedEnum
default_nested_enum_extension_lite = 81 [default = BAR];
optional ForeignEnumLite
default_foreign_enum_extension_lite = 82 [default = FOREIGN_LITE_BAR];
optional protobuf_unittest_import.ImportEnumLite
default_import_enum_extension_lite = 83 [default = IMPORT_LITE_BAR];
optional string default_string_piece_extension_lite = 84 [ctype=STRING_PIECE,
default="abc"];
optional string default_cord_extension_lite = 85 [ctype=CORD, default="123"];
}
message TestPackedExtensionsLite {
extensions 1 to max;
}
extend TestPackedExtensionsLite {
repeated int32 packed_int32_extension_lite = 90 [packed = true];
repeated int64 packed_int64_extension_lite = 91 [packed = true];
repeated uint32 packed_uint32_extension_lite = 92 [packed = true];
repeated uint64 packed_uint64_extension_lite = 93 [packed = true];
repeated sint32 packed_sint32_extension_lite = 94 [packed = true];
repeated sint64 packed_sint64_extension_lite = 95 [packed = true];
repeated fixed32 packed_fixed32_extension_lite = 96 [packed = true];
repeated fixed64 packed_fixed64_extension_lite = 97 [packed = true];
repeated sfixed32 packed_sfixed32_extension_lite = 98 [packed = true];
repeated sfixed64 packed_sfixed64_extension_lite = 99 [packed = true];
repeated float packed_float_extension_lite = 100 [packed = true];
repeated double packed_double_extension_lite = 101 [packed = true];
repeated bool packed_bool_extension_lite = 102 [packed = true];
repeated ForeignEnumLite packed_enum_extension_lite = 103 [packed = true];
}
message TestNestedExtensionLite {
extend TestAllExtensionsLite {
optional int32 nested_extension = 12345;
}
}
// Test that deprecated fields work. We only verify that they compile (at one
// point this failed).
message TestDeprecatedLite {
optional int32 deprecated_field = 1 [deprecated = true];
}
// See the comments of the same type in unittest.proto.
message TestParsingMergeLite {
message RepeatedFieldsGenerator {
repeated TestAllTypesLite field1 = 1;
repeated TestAllTypesLite field2 = 2;
repeated TestAllTypesLite field3 = 3;
repeated group Group1 = 10 {
optional TestAllTypesLite field1 = 11;
}
repeated group Group2 = 20 {
optional TestAllTypesLite field1 = 21;
}
repeated TestAllTypesLite ext1 = 1000;
repeated TestAllTypesLite ext2 = 1001;
}
required TestAllTypesLite required_all_types = 1;
optional TestAllTypesLite optional_all_types = 2;
repeated TestAllTypesLite repeated_all_types = 3;
optional group OptionalGroup = 10 {
optional TestAllTypesLite optional_group_all_types = 11;
}
repeated group RepeatedGroup = 20 {
optional TestAllTypesLite repeated_group_all_types = 21;
}
extensions 1000 to max;
extend TestParsingMergeLite {
optional TestAllTypesLite optional_ext = 1000;
repeated TestAllTypesLite repeated_ext = 1001;
}
}

@ -1,43 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
//
// Tests that a "lite" message can import a regular message.
package protobuf_unittest;
import "google/protobuf/unittest.proto";
option optimize_for = LITE_RUNTIME;
message TestLiteImportsNonlite {
optional TestAllTypes message = 1;
}

@ -1,72 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file contains messages for testing message_set_wire_format.
package protobuf_unittest;
option optimize_for = SPEED;
// A message with message_set_wire_format.
message TestMessageSet {
option message_set_wire_format = true;
extensions 4 to max;
}
message TestMessageSetContainer {
optional TestMessageSet message_set = 1;
}
message TestMessageSetExtension1 {
extend TestMessageSet {
optional TestMessageSetExtension1 message_set_extension = 1545008;
}
optional int32 i = 15;
}
message TestMessageSetExtension2 {
extend TestMessageSet {
optional TestMessageSetExtension2 message_set_extension = 1547769;
}
optional string str = 25;
}
// MessageSet wire format is equivalent to this.
message RawMessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required bytes message = 3;
}
}

@ -1,52 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
package google.protobuf.no_generic_services_test;
// *_generic_services are false by default.
message TestMessage {
optional int32 a = 1;
extensions 1000 to max;
}
enum TestEnum {
FOO = 1;
}
extend TestMessage {
optional int32 test_extension = 1000;
}
service TestService {
rpc Foo(TestMessage) returns(TestMessage);
}

@ -1,61 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file which uses optimize_for = CODE_SIZE.
import "google/protobuf/unittest.proto";
package protobuf_unittest;
option optimize_for = CODE_SIZE;
message TestOptimizedForSize {
optional int32 i = 1;
optional ForeignMessage msg = 19;
extensions 1000 to max;
extend TestOptimizedForSize {
optional int32 test_extension = 1234;
optional TestRequiredOptimizedForSize test_extension2 = 1235;
}
}
message TestRequiredOptimizedForSize {
required int32 x = 1;
}
message TestOptionalOptimizedForSize {
optional TestRequiredOptimizedForSize o = 1;
}

@ -1,115 +0,0 @@
#!/bin/bash
set -ex
# Change to the script's directory.
cd $(dirname $0)
MAVEN_LOCAL_REPOSITORY=/var/maven_local_repository
MVN="mvn --batch-mode -e -X -Dhttps.protocols=TLSv1.2 -Dmaven.repo.local=$MAVEN_LOCAL_REPOSITORY"
# Version of the tests (i.e., the version of protobuf from where we extracted
# these tests).
TEST_VERSION=`grep "^ <version>.*</version>" pom.xml | sed "s| <version>\(.*\)</version>|\1|"`
# The old version of protobuf that we are testing compatibility against. This
# is usually the same as TEST_VERSION (i.e., we use the tests extracted from
# that version to test compatibility of the newest runtime against it), but it
# is also possible to use this same test set to test the compatibility of the
# latest version against other versions.
OLD_VERSION=$1
OLD_VERSION_PROTOC=https://repo1.maven.org/maven2/com/google/protobuf/protoc/$OLD_VERSION/protoc-$OLD_VERSION-linux-x86_64.exe
# Extract the latest protobuf version number.
VERSION_NUMBER=`grep "^ <version>.*</version>" ../../pom.xml | sed "s| <version>\(.*\)</version>|\1|"`
echo "Running compatibility tests between current $VERSION_NUMBER and released $OLD_VERSION"
# Check protoc
[ -f ../../../src/protoc ] || {
echo "[ERROR]: Please build protoc first."
exit 1
}
# Build and install protobuf-java-$VERSION_NUMBER.jar
[ -f ../../core/target/protobuf-java-$VERSION_NUMBER.jar ] || {
pushd ../..
$MVN install -Dmaven.test.skip=true
popd
}
# Download old version source for the compatibility test
[ -d protobuf ] || {
git clone https://github.com/protocolbuffers/protobuf.git
cd protobuf
git reset --hard v$TEST_VERSION
cd ..
}
# Download old version protoc compiler (for linux)
wget $OLD_VERSION_PROTOC -O protoc
chmod +x protoc
# Test source compatibility. In these tests we recompile everything against
# the new runtime (including old version generated code).
# Test A.1:
# protos: use new version
# more_protos: use old version
$MVN clean test \
-Dprotobuf.test.source.path=$(pwd)/protobuf \
-Dprotoc.path=$(pwd)/protoc \
-Dprotos.protoc.path=$(pwd)/../../../src/protoc \
-Dprotobuf.version=$VERSION_NUMBER
# Test A.2:
# protos: use old version
# more_protos: use new version
$MVN clean test \
-Dprotobuf.test.source.path=$(pwd)/protobuf \
-Dprotoc.path=$(pwd)/protoc \
-Dmore_protos.protoc.path=$(pwd)/../../../src/protoc \
-Dprotobuf.version=$VERSION_NUMBER
# Test binary compatibility. In these tests we run the old version compiled
# jar against the new runtime directly without recompile.
# Collect all test dependencies in a single jar file (except for protobuf) to
# make it easier to run binary compatibility test (where we will need to run
# the jar files directly).
cd deps
$MVN assembly:single
cd ..
cp -f deps/target/compatibility-test-deps-${TEST_VERSION}-jar-with-dependencies.jar deps.jar
# Build the old version of all 3 artifacts.
$MVN clean install -Dmaven.test.skip=true -Dprotoc.path=$(pwd)/protoc -Dprotobuf.version=$OLD_VERSION
cp -f protos/target/compatibility-protos-${TEST_VERSION}.jar protos.jar
cp -f more_protos/target/compatibility-more-protos-${TEST_VERSION}.jar more_protos.jar
cp -f tests/target/compatibility-tests-${TEST_VERSION}.jar tests.jar
# Collect the list of tests we need to run.
TESTS=`find tests -name "*Test.java" | sed "s|/|.|g;s/.java$//g;s/tests.src.main.java.//g"`
# Test B.1: run all the old artifacts against the new runtime. Note that we
# must run the test in the protobuf source tree because some of the tests need
# to read golden test data files.
cd protobuf
java -cp ../../../core/target/protobuf-java-$VERSION_NUMBER.jar:../protos.jar:../more_protos.jar:../tests.jar:../deps.jar org.junit.runner.JUnitCore $TESTS
cd ..
# Test B.2: update protos.jar only.
cd protos
$MVN clean package -Dmaven.test.skip=true -Dprotoc.path=$(pwd)/../../../../src/protoc -Dprotobuf.version=$VERSION_NUMBER
cd ..
cd protobuf
java -cp ../../../core/target/protobuf-java-$VERSION_NUMBER.jar:../protos/target/compatibility-protos-${TEST_VERSION}.jar:../more_protos.jar:../tests.jar:../deps.jar org.junit.runner.JUnitCore $TESTS
cd ..
# Test B.3: update more_protos.jar only.
cd more_protos
$MVN clean package -Dmaven.test.skip=true -Dprotoc.path=$(pwd)/../../../../src/protoc -Dprotobuf.version=$VERSION_NUMBER
cd ..
cd protobuf
java -cp ../../../core/target/protobuf-java-$VERSION_NUMBER.jar:../protos.jar:../more_protos/target/compatibility-more-protos-${TEST_VERSION}.jar:../tests.jar:../deps.jar org.junit.runner.JUnitCore $TESTS
cd ..

@ -1,73 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.google.protobuf.compatibility</groupId>
<artifactId>compatibility-test-suite</artifactId>
<version>2.5.0</version>
<relativePath>..</relativePath>
</parent>
<groupId>com.google.protobuf.compatibility</groupId>
<artifactId>compatibility-tests</artifactId>
<version>2.5.0</version>
<name>Compatibility Tests</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymockclassextension</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${tests.protobuf.version}</version>
</dependency>
<dependency>
<groupId>com.google.protobuf.compatibility</groupId>
<artifactId>compatibility-protos</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.google.protobuf.compatibility</groupId>
<artifactId>compatibility-more-protos</artifactId>
<version>2.5.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<testSourceDirectory>${basedir}/src/main/java/</testSourceDirectory>
<testClassesDirectory>${project.build.directory}/classes/</testClassesDirectory>
<includes>
<include>**/*Test.java</include>
</includes>
<workingDirectory>${protobuf.test.source.path}</workingDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -1,510 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import com.google.protobuf.Descriptors.FieldDescriptor;
import protobuf_unittest.UnittestOptimizeFor.TestOptimizedForSize;
import protobuf_unittest.UnittestProto;
import protobuf_unittest.UnittestProto.ForeignMessage;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
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;
/**
* Unit test for {@link AbstractMessage}.
*
* @author kenton@google.com Kenton Varda
*/
public class AbstractMessageTest extends TestCase {
/**
* Extends AbstractMessage and wraps some other message object. The methods
* of the Message interface which aren't explicitly implemented by
* AbstractMessage are forwarded to the wrapped object. This allows us to
* test that AbstractMessage's implementations work even if the wrapped
* object does not use them.
*/
private static class AbstractMessageWrapper extends AbstractMessage {
private final Message wrappedMessage;
public AbstractMessageWrapper(Message wrappedMessage) {
this.wrappedMessage = wrappedMessage;
}
public Descriptors.Descriptor getDescriptorForType() {
return wrappedMessage.getDescriptorForType();
}
public AbstractMessageWrapper getDefaultInstanceForType() {
return new AbstractMessageWrapper(
wrappedMessage.getDefaultInstanceForType());
}
public Map<Descriptors.FieldDescriptor, Object> getAllFields() {
return wrappedMessage.getAllFields();
}
public boolean hasField(Descriptors.FieldDescriptor field) {
return wrappedMessage.hasField(field);
}
public Object getField(Descriptors.FieldDescriptor field) {
return wrappedMessage.getField(field);
}
public int getRepeatedFieldCount(Descriptors.FieldDescriptor field) {
return wrappedMessage.getRepeatedFieldCount(field);
}
public Object getRepeatedField(
Descriptors.FieldDescriptor field, int index) {
return wrappedMessage.getRepeatedField(field, index);
}
public UnknownFieldSet getUnknownFields() {
return wrappedMessage.getUnknownFields();
}
public Builder newBuilderForType() {
return new Builder(wrappedMessage.newBuilderForType());
}
public Builder toBuilder() {
return new Builder(wrappedMessage.toBuilder());
}
static class Builder extends AbstractMessage.Builder<Builder> {
private final Message.Builder wrappedBuilder;
public Builder(Message.Builder wrappedBuilder) {
this.wrappedBuilder = wrappedBuilder;
}
public AbstractMessageWrapper build() {
return new AbstractMessageWrapper(wrappedBuilder.build());
}
public AbstractMessageWrapper buildPartial() {
return new AbstractMessageWrapper(wrappedBuilder.buildPartial());
}
public Builder clone() {
return new Builder(wrappedBuilder.clone());
}
public boolean isInitialized() {
return clone().buildPartial().isInitialized();
}
public Descriptors.Descriptor getDescriptorForType() {
return wrappedBuilder.getDescriptorForType();
}
public AbstractMessageWrapper getDefaultInstanceForType() {
return new AbstractMessageWrapper(
wrappedBuilder.getDefaultInstanceForType());
}
public Map<Descriptors.FieldDescriptor, Object> getAllFields() {
return wrappedBuilder.getAllFields();
}
public Builder newBuilderForField(Descriptors.FieldDescriptor field) {
return new Builder(wrappedBuilder.newBuilderForField(field));
}
public boolean hasField(Descriptors.FieldDescriptor field) {
return wrappedBuilder.hasField(field);
}
public Object getField(Descriptors.FieldDescriptor field) {
return wrappedBuilder.getField(field);
}
public Builder setField(Descriptors.FieldDescriptor field, Object value) {
wrappedBuilder.setField(field, value);
return this;
}
public Builder clearField(Descriptors.FieldDescriptor field) {
wrappedBuilder.clearField(field);
return this;
}
public int getRepeatedFieldCount(Descriptors.FieldDescriptor field) {
return wrappedBuilder.getRepeatedFieldCount(field);
}
public Object getRepeatedField(
Descriptors.FieldDescriptor field, int index) {
return wrappedBuilder.getRepeatedField(field, index);
}
public Builder setRepeatedField(Descriptors.FieldDescriptor field,
int index, Object value) {
wrappedBuilder.setRepeatedField(field, index, value);
return this;
}
public Builder addRepeatedField(
Descriptors.FieldDescriptor field, Object value) {
wrappedBuilder.addRepeatedField(field, value);
return this;
}
public UnknownFieldSet getUnknownFields() {
return wrappedBuilder.getUnknownFields();
}
public Builder setUnknownFields(UnknownFieldSet unknownFields) {
wrappedBuilder.setUnknownFields(unknownFields);
return this;
}
@Override
public Message.Builder getFieldBuilder(FieldDescriptor field) {
return wrappedBuilder.getFieldBuilder(field);
}
}
public Parser<? extends Message> getParserForType() {
return wrappedMessage.getParserForType();
}
}
// =================================================================
TestUtil.ReflectionTester reflectionTester =
new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
TestUtil.ReflectionTester extensionsReflectionTester =
new TestUtil.ReflectionTester(TestAllExtensions.getDescriptor(),
TestUtil.getExtensionRegistry());
public void testClear() throws Exception {
AbstractMessageWrapper message =
new AbstractMessageWrapper.Builder(
TestAllTypes.newBuilder(TestUtil.getAllSet()))
.clear().build();
TestUtil.assertClear((TestAllTypes) message.wrappedMessage);
}
public void testCopy() throws Exception {
AbstractMessageWrapper message =
new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder())
.mergeFrom(TestUtil.getAllSet()).build();
TestUtil.assertAllFieldsSet((TestAllTypes) message.wrappedMessage);
}
public void testSerializedSize() throws Exception {
TestAllTypes message = TestUtil.getAllSet();
Message abstractMessage = new AbstractMessageWrapper(TestUtil.getAllSet());
assertEquals(message.getSerializedSize(),
abstractMessage.getSerializedSize());
}
public void testSerialization() throws Exception {
Message abstractMessage = new AbstractMessageWrapper(TestUtil.getAllSet());
TestUtil.assertAllFieldsSet(
TestAllTypes.parseFrom(abstractMessage.toByteString()));
assertEquals(TestUtil.getAllSet().toByteString(),
abstractMessage.toByteString());
}
public void testParsing() throws Exception {
AbstractMessageWrapper.Builder builder =
new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder());
AbstractMessageWrapper message =
builder.mergeFrom(TestUtil.getAllSet().toByteString()).build();
TestUtil.assertAllFieldsSet((TestAllTypes) message.wrappedMessage);
}
public void testParsingUninitialized() throws Exception {
TestRequiredForeign.Builder builder = TestRequiredForeign.newBuilder();
builder.getOptionalMessageBuilder().setDummy2(10);
ByteString bytes = builder.buildPartial().toByteString();
Message.Builder abstractMessageBuilder =
new AbstractMessageWrapper.Builder(TestRequiredForeign.newBuilder());
// mergeFrom() should not throw initialization error.
abstractMessageBuilder.mergeFrom(bytes).buildPartial();
try {
abstractMessageBuilder.mergeFrom(bytes).build();
fail();
} catch (UninitializedMessageException ex) {
// pass
}
// test DynamicMessage directly.
Message.Builder dynamicMessageBuilder = DynamicMessage.newBuilder(
TestRequiredForeign.getDescriptor());
// mergeFrom() should not throw initialization error.
dynamicMessageBuilder.mergeFrom(bytes).buildPartial();
try {
dynamicMessageBuilder.mergeFrom(bytes).build();
fail();
} catch (UninitializedMessageException ex) {
// pass
}
}
public void testPackedSerialization() throws Exception {
Message abstractMessage =
new AbstractMessageWrapper(TestUtil.getPackedSet());
TestUtil.assertPackedFieldsSet(
TestPackedTypes.parseFrom(abstractMessage.toByteString()));
assertEquals(TestUtil.getPackedSet().toByteString(),
abstractMessage.toByteString());
}
public void testPackedParsing() throws Exception {
AbstractMessageWrapper.Builder builder =
new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder());
AbstractMessageWrapper message =
builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
TestUtil.assertPackedFieldsSet((TestPackedTypes) message.wrappedMessage);
}
public void testUnpackedSerialization() throws Exception {
Message abstractMessage =
new AbstractMessageWrapper(TestUtil.getUnpackedSet());
TestUtil.assertUnpackedFieldsSet(
TestUnpackedTypes.parseFrom(abstractMessage.toByteString()));
assertEquals(TestUtil.getUnpackedSet().toByteString(),
abstractMessage.toByteString());
}
public void testParsePackedToUnpacked() throws Exception {
AbstractMessageWrapper.Builder builder =
new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder());
AbstractMessageWrapper message =
builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
TestUtil.assertUnpackedFieldsSet(
(TestUnpackedTypes) message.wrappedMessage);
}
public void testParseUnpackedToPacked() throws Exception {
AbstractMessageWrapper.Builder builder =
new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder());
AbstractMessageWrapper message =
builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
TestUtil.assertPackedFieldsSet((TestPackedTypes) message.wrappedMessage);
}
public void testUnpackedParsing() throws Exception {
AbstractMessageWrapper.Builder builder =
new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder());
AbstractMessageWrapper message =
builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
TestUtil.assertUnpackedFieldsSet(
(TestUnpackedTypes) message.wrappedMessage);
}
public void testOptimizedForSize() throws Exception {
// We're mostly only checking that this class was compiled successfully.
TestOptimizedForSize message =
TestOptimizedForSize.newBuilder().setI(1).build();
message = TestOptimizedForSize.parseFrom(message.toByteString());
assertEquals(2, message.getSerializedSize());
}
// -----------------------------------------------------------------
// Tests for isInitialized().
private static final TestRequired TEST_REQUIRED_UNINITIALIZED =
TestRequired.getDefaultInstance();
private static final TestRequired TEST_REQUIRED_INITIALIZED =
TestRequired.newBuilder().setA(1).setB(2).setC(3).build();
public void testIsInitialized() throws Exception {
TestRequired.Builder builder = TestRequired.newBuilder();
AbstractMessageWrapper.Builder abstractBuilder =
new AbstractMessageWrapper.Builder(builder);
assertFalse(abstractBuilder.isInitialized());
assertEquals("a, b, c", abstractBuilder.getInitializationErrorString());
builder.setA(1);
assertFalse(abstractBuilder.isInitialized());
assertEquals("b, c", abstractBuilder.getInitializationErrorString());
builder.setB(1);
assertFalse(abstractBuilder.isInitialized());
assertEquals("c", abstractBuilder.getInitializationErrorString());
builder.setC(1);
assertTrue(abstractBuilder.isInitialized());
assertEquals("", abstractBuilder.getInitializationErrorString());
}
public void testForeignIsInitialized() throws Exception {
TestRequiredForeign.Builder builder = TestRequiredForeign.newBuilder();
AbstractMessageWrapper.Builder abstractBuilder =
new AbstractMessageWrapper.Builder(builder);
assertTrue(abstractBuilder.isInitialized());
assertEquals("", abstractBuilder.getInitializationErrorString());
builder.setOptionalMessage(TEST_REQUIRED_UNINITIALIZED);
assertFalse(abstractBuilder.isInitialized());
assertEquals(
"optional_message.a, optional_message.b, optional_message.c",
abstractBuilder.getInitializationErrorString());
builder.setOptionalMessage(TEST_REQUIRED_INITIALIZED);
assertTrue(abstractBuilder.isInitialized());
assertEquals("", abstractBuilder.getInitializationErrorString());
builder.addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED);
assertFalse(abstractBuilder.isInitialized());
assertEquals(
"repeated_message[0].a, repeated_message[0].b, repeated_message[0].c",
abstractBuilder.getInitializationErrorString());
builder.setRepeatedMessage(0, TEST_REQUIRED_INITIALIZED);
assertTrue(abstractBuilder.isInitialized());
assertEquals("", abstractBuilder.getInitializationErrorString());
}
// -----------------------------------------------------------------
// Tests for mergeFrom
static final TestAllTypes MERGE_SOURCE =
TestAllTypes.newBuilder()
.setOptionalInt32(1)
.setOptionalString("foo")
.setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
.addRepeatedString("bar")
.build();
static final TestAllTypes MERGE_DEST =
TestAllTypes.newBuilder()
.setOptionalInt64(2)
.setOptionalString("baz")
.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build())
.addRepeatedString("qux")
.build();
static final String MERGE_RESULT_TEXT =
"optional_int32: 1\n" +
"optional_int64: 2\n" +
"optional_string: \"foo\"\n" +
"optional_foreign_message {\n" +
" c: 3\n" +
"}\n" +
"repeated_string: \"qux\"\n" +
"repeated_string: \"bar\"\n";
public void testMergeFrom() throws Exception {
AbstractMessageWrapper result =
new AbstractMessageWrapper.Builder(
TestAllTypes.newBuilder(MERGE_DEST))
.mergeFrom(MERGE_SOURCE).build();
assertEquals(MERGE_RESULT_TEXT, result.toString());
}
// -----------------------------------------------------------------
// Tests for equals and hashCode
public void testEqualsAndHashCode() throws Exception {
TestAllTypes a = TestUtil.getAllSet();
TestAllTypes b = TestAllTypes.newBuilder().build();
TestAllTypes c = TestAllTypes.newBuilder(b).addRepeatedString("x").build();
TestAllTypes d = TestAllTypes.newBuilder(c).addRepeatedString("y").build();
TestAllExtensions e = TestUtil.getAllExtensionsSet();
TestAllExtensions f = TestAllExtensions.newBuilder(e)
.addExtension(UnittestProto.repeatedInt32Extension, 999).build();
checkEqualsIsConsistent(a);
checkEqualsIsConsistent(b);
checkEqualsIsConsistent(c);
checkEqualsIsConsistent(d);
checkEqualsIsConsistent(e);
checkEqualsIsConsistent(f);
checkNotEqual(a, b);
checkNotEqual(a, c);
checkNotEqual(a, d);
checkNotEqual(a, e);
checkNotEqual(a, f);
checkNotEqual(b, c);
checkNotEqual(b, d);
checkNotEqual(b, e);
checkNotEqual(b, f);
checkNotEqual(c, d);
checkNotEqual(c, e);
checkNotEqual(c, f);
checkNotEqual(d, e);
checkNotEqual(d, f);
checkNotEqual(e, f);
// Deserializing into the TestEmptyMessage such that every field
// is an {@link UnknownFieldSet.Field}.
UnittestProto.TestEmptyMessage eUnknownFields =
UnittestProto.TestEmptyMessage.parseFrom(e.toByteArray());
UnittestProto.TestEmptyMessage fUnknownFields =
UnittestProto.TestEmptyMessage.parseFrom(f.toByteArray());
checkNotEqual(eUnknownFields, fUnknownFields);
checkEqualsIsConsistent(eUnknownFields);
checkEqualsIsConsistent(fUnknownFields);
// Subsequent reconstitutions should be identical
UnittestProto.TestEmptyMessage eUnknownFields2 =
UnittestProto.TestEmptyMessage.parseFrom(e.toByteArray());
checkEqualsIsConsistent(eUnknownFields, eUnknownFields2);
}
/**
* Asserts that the given proto has symmetric equals and hashCode methods.
*/
private void checkEqualsIsConsistent(Message message) {
// Object should be equal to itself.
assertEquals(message, message);
// Object should be equal to a dynamic copy of itself.
DynamicMessage dynamic = DynamicMessage.newBuilder(message).build();
checkEqualsIsConsistent(message, dynamic);
}
/**
* Asserts that the given protos are equal and have the same hash code.
*/
private void checkEqualsIsConsistent(Message message1, Message message2) {
assertEquals(message1, message2);
assertEquals(message2, message1);
assertEquals(message2.hashCode(), message1.hashCode());
}
/**
* Asserts that the given protos are not equal and have different hash codes.
*
* @warning It's valid for non-equal objects to have the same hash code, so
* this test is stricter than it needs to be. However, this should happen
* relatively rarely.
*/
private void checkNotEqual(Message m1, Message m2) {
String equalsError = String.format("%s should not be equal to %s", m1, m2);
assertFalse(equalsError, m1.equals(m2));
assertFalse(equalsError, m2.equals(m1));
assertFalse(
String.format("%s should have a different hash code from %s", m1, m2),
m1.hashCode() == m2.hashCode());
}
}

@ -1,56 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import java.io.UnsupportedEncodingException;
/**
* This class tests {@link BoundedByteString}, which extends {@link LiteralByteString},
* by inheriting the tests from {@link LiteralByteStringTest}. The only method which
* is strange enough that it needs to be overridden here is {@link #testToString()}.
*
* @author carlanton@google.com (Carl Haverl)
*/
public class BoundedByteStringTest extends LiteralByteStringTest {
@Override
protected void setUp() throws Exception {
classUnderTest = "BoundedByteString";
byte[] sourceBytes = ByteStringTest.getTestBytes(2341, 11337766L);
int from = 100;
int to = sourceBytes.length - 100;
stringUnderTest = ByteString.copyFrom(sourceBytes).substring(from, to);
referenceBytes = new byte[to - from];
System.arraycopy(sourceBytes, from, referenceBytes, 0, to - from);
expectedHashCode = 727575887;
}
}

@ -1,590 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import com.google.protobuf.ByteString.Output;
import junit.framework.TestCase;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;
/**
* Test methods with implementations in {@link ByteString}, plus do some top-level "integration"
* tests.
*
* @author carlanton@google.com (Carl Haverl)
*/
public class ByteStringTest extends TestCase {
private static final String UTF_16 = "UTF-16";
static byte[] getTestBytes(int size, long seed) {
Random random = new Random(seed);
byte[] result = new byte[size];
random.nextBytes(result);
return result;
}
private byte[] getTestBytes(int size) {
return getTestBytes(size, 445566L);
}
private byte[] getTestBytes() {
return getTestBytes(1000);
}
// Compare the entire left array with a subset of the right array.
private boolean isArrayRange(byte[] left, byte[] right, int rightOffset, int length) {
boolean stillEqual = (left.length == length);
for (int i = 0; (stillEqual && i < length); ++i) {
stillEqual = (left[i] == right[rightOffset + i]);
}
return stillEqual;
}
// Returns true only if the given two arrays have identical contents.
private boolean isArray(byte[] left, byte[] right) {
return left.length == right.length && isArrayRange(left, right, 0, left.length);
}
public void testSubstring_BeginIndex() {
byte[] bytes = getTestBytes();
ByteString substring = ByteString.copyFrom(bytes).substring(500);
assertTrue("substring must contain the tail of the string",
isArrayRange(substring.toByteArray(), bytes, 500, bytes.length - 500));
}
public void testCopyFrom_BytesOffsetSize() {
byte[] bytes = getTestBytes();
ByteString byteString = ByteString.copyFrom(bytes, 500, 200);
assertTrue("copyFrom sub-range must contain the expected bytes",
isArrayRange(byteString.toByteArray(), bytes, 500, 200));
}
public void testCopyFrom_Bytes() {
byte[] bytes = getTestBytes();
ByteString byteString = ByteString.copyFrom(bytes);
assertTrue("copyFrom must contain the expected bytes",
isArray(byteString.toByteArray(), bytes));
}
public void testCopyFrom_ByteBufferSize() {
byte[] bytes = getTestBytes();
ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
byteBuffer.put(bytes);
byteBuffer.position(500);
ByteString byteString = ByteString.copyFrom(byteBuffer, 200);
assertTrue("copyFrom byteBuffer sub-range must contain the expected bytes",
isArrayRange(byteString.toByteArray(), bytes, 500, 200));
}
public void testCopyFrom_ByteBuffer() {
byte[] bytes = getTestBytes();
ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
byteBuffer.put(bytes);
byteBuffer.position(500);
ByteString byteString = ByteString.copyFrom(byteBuffer);
assertTrue("copyFrom byteBuffer sub-range must contain the expected bytes",
isArrayRange(byteString.toByteArray(), bytes, 500, bytes.length - 500));
}
public void testCopyFrom_StringEncoding() throws UnsupportedEncodingException {
String testString = "I love unicode \u1234\u5678 characters";
ByteString byteString = ByteString.copyFrom(testString, UTF_16);
byte[] testBytes = testString.getBytes(UTF_16);
assertTrue("copyFrom string must respect the charset",
isArrayRange(byteString.toByteArray(), testBytes, 0, testBytes.length));
}
public void testCopyFrom_Utf8() throws UnsupportedEncodingException {
String testString = "I love unicode \u1234\u5678 characters";
ByteString byteString = ByteString.copyFromUtf8(testString);
byte[] testBytes = testString.getBytes("UTF-8");
assertTrue("copyFromUtf8 string must respect the charset",
isArrayRange(byteString.toByteArray(), testBytes, 0, testBytes.length));
}
public void testCopyFrom_Iterable() {
byte[] testBytes = getTestBytes(77777, 113344L);
final List<ByteString> pieces = makeConcretePieces(testBytes);
// Call copyFrom() on a Collection
ByteString byteString = ByteString.copyFrom(pieces);
assertTrue("copyFrom a List must contain the expected bytes",
isArrayRange(byteString.toByteArray(), testBytes, 0, testBytes.length));
// Call copyFrom on an iteration that's not a collection
ByteString byteStringAlt = ByteString.copyFrom(new Iterable<ByteString>() {
public Iterator<ByteString> iterator() {
return pieces.iterator();
}
});
assertEquals("copyFrom from an Iteration must contain the expected bytes",
byteString, byteStringAlt);
}
public void testCopyTo_TargetOffset() {
byte[] bytes = getTestBytes();
ByteString byteString = ByteString.copyFrom(bytes);
byte[] target = new byte[bytes.length + 1000];
byteString.copyTo(target, 400);
assertTrue("copyFrom byteBuffer sub-range must contain the expected bytes",
isArrayRange(bytes, target, 400, bytes.length));
}
public void testReadFrom_emptyStream() throws IOException {
ByteString byteString =
ByteString.readFrom(new ByteArrayInputStream(new byte[0]));
assertSame("reading an empty stream must result in the EMPTY constant "
+ "byte string", ByteString.EMPTY, byteString);
}
public void testReadFrom_smallStream() throws IOException {
assertReadFrom(getTestBytes(10));
}
public void testReadFrom_mutating() throws IOException {
byte[] capturedArray = null;
EvilInputStream eis = new EvilInputStream();
ByteString byteString = ByteString.readFrom(eis);
capturedArray = eis.capturedArray;
byte[] originalValue = byteString.toByteArray();
for (int x = 0; x < capturedArray.length; ++x) {
capturedArray[x] = (byte) 0;
}
byte[] newValue = byteString.toByteArray();
assertTrue("copyFrom byteBuffer must not grant access to underlying array",
Arrays.equals(originalValue, newValue));
}
// Tests sizes that are over multi-segment rope threshold.
public void testReadFrom_largeStream() throws IOException {
assertReadFrom(getTestBytes(0x100));
assertReadFrom(getTestBytes(0x101));
assertReadFrom(getTestBytes(0x110));
assertReadFrom(getTestBytes(0x1000));
assertReadFrom(getTestBytes(0x1001));
assertReadFrom(getTestBytes(0x1010));
assertReadFrom(getTestBytes(0x10000));
assertReadFrom(getTestBytes(0x10001));
assertReadFrom(getTestBytes(0x10010));
}
// Tests that IOExceptions propagate through ByteString.readFrom().
public void testReadFrom_IOExceptions() {
try {
ByteString.readFrom(new FailStream());
fail("readFrom must throw the underlying IOException");
} catch (IOException e) {
assertEquals("readFrom must throw the expected exception",
"synthetic failure", e.getMessage());
}
}
// Tests that ByteString.readFrom works with streams that don't
// always fill their buffers.
public void testReadFrom_reluctantStream() throws IOException {
final byte[] data = getTestBytes(0x1000);
ByteString byteString = ByteString.readFrom(new ReluctantStream(data));
assertTrue("readFrom byte stream must contain the expected bytes",
isArray(byteString.toByteArray(), data));
// Same test as above, but with some specific chunk sizes.
assertReadFromReluctantStream(data, 100);
assertReadFromReluctantStream(data, 248);
assertReadFromReluctantStream(data, 249);
assertReadFromReluctantStream(data, 250);
assertReadFromReluctantStream(data, 251);
assertReadFromReluctantStream(data, 0x1000);
assertReadFromReluctantStream(data, 0x1001);
}
// Fails unless ByteString.readFrom reads the bytes correctly from a
// reluctant stream with the given chunkSize parameter.
private void assertReadFromReluctantStream(byte[] bytes, int chunkSize)
throws IOException {
ByteString b = ByteString.readFrom(new ReluctantStream(bytes), chunkSize);
assertTrue("readFrom byte stream must contain the expected bytes",
isArray(b.toByteArray(), bytes));
}
// Tests that ByteString.readFrom works with streams that implement
// available().
public void testReadFrom_available() throws IOException {
final byte[] data = getTestBytes(0x1001);
ByteString byteString = ByteString.readFrom(new AvailableStream(data));
assertTrue("readFrom byte stream must contain the expected bytes",
isArray(byteString.toByteArray(), data));
}
// Fails unless ByteString.readFrom reads the bytes correctly.
private void assertReadFrom(byte[] bytes) throws IOException {
ByteString byteString =
ByteString.readFrom(new ByteArrayInputStream(bytes));
assertTrue("readFrom byte stream must contain the expected bytes",
isArray(byteString.toByteArray(), bytes));
}
// A stream that fails when read.
private static final class FailStream extends InputStream {
@Override public int read() throws IOException {
throw new IOException("synthetic failure");
}
}
// A stream that simulates blocking by only producing 250 characters
// per call to read(byte[]).
private static class ReluctantStream extends InputStream {
protected final byte[] data;
protected int pos = 0;
public ReluctantStream(byte[] data) {
this.data = data;
}
@Override public int read() {
if (pos == data.length) {
return -1;
} else {
return data[pos++];
}
}
@Override public int read(byte[] buf) {
return read(buf, 0, buf.length);
}
@Override public int read(byte[] buf, int offset, int size) {
if (pos == data.length) {
return -1;
}
int count = Math.min(Math.min(size, data.length - pos), 250);
System.arraycopy(data, pos, buf, offset, count);
pos += count;
return count;
}
}
// Same as above, but also implements available().
private static final class AvailableStream extends ReluctantStream {
public AvailableStream(byte[] data) {
super(data);
}
@Override public int available() {
return Math.min(250, data.length - pos);
}
}
// A stream which exposes the byte array passed into read(byte[], int, int).
private static class EvilInputStream extends InputStream {
public byte[] capturedArray = null;
@Override
public int read(byte[] buf, int off, int len) {
if (capturedArray != null) {
return -1;
} else {
capturedArray = buf;
for (int x = 0; x < len; ++x) {
buf[x] = (byte) x;
}
return len;
}
}
@Override
public int read() {
// Purposefully do nothing.
return -1;
}
}
// A stream which exposes the byte array passed into write(byte[], int, int).
private static class EvilOutputStream extends OutputStream {
public byte[] capturedArray = null;
@Override
public void write(byte[] buf, int off, int len) {
if (capturedArray == null) {
capturedArray = buf;
}
}
@Override
public void write(int ignored) {
// Purposefully do nothing.
}
}
public void testToStringUtf8() throws UnsupportedEncodingException {
String testString = "I love unicode \u1234\u5678 characters";
byte[] testBytes = testString.getBytes("UTF-8");
ByteString byteString = ByteString.copyFrom(testBytes);
assertEquals("copyToStringUtf8 must respect the charset",
testString, byteString.toStringUtf8());
}
public void testNewOutput_InitialCapacity() throws IOException {
byte[] bytes = getTestBytes();
ByteString.Output output = ByteString.newOutput(bytes.length + 100);
output.write(bytes);
ByteString byteString = output.toByteString();
assertTrue(
"String built from newOutput(int) must contain the expected bytes",
isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length));
}
// Test newOutput() using a variety of buffer sizes and a variety of (fixed)
// write sizes
public void testNewOutput_ArrayWrite() throws IOException {
byte[] bytes = getTestBytes();
int length = bytes.length;
int[] bufferSizes = {128, 256, length / 2, length - 1, length, length + 1,
2 * length, 3 * length};
int[] writeSizes = {1, 4, 5, 7, 23, bytes.length};
for (int bufferSize : bufferSizes) {
for (int writeSize : writeSizes) {
// Test writing the entire output writeSize bytes at a time.
ByteString.Output output = ByteString.newOutput(bufferSize);
for (int i = 0; i < length; i += writeSize) {
output.write(bytes, i, Math.min(writeSize, length - i));
}
ByteString byteString = output.toByteString();
assertTrue("String built from newOutput() must contain the expected bytes",
isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length));
}
}
}
// Test newOutput() using a variety of buffer sizes, but writing all the
// characters using write(byte);
public void testNewOutput_WriteChar() throws IOException {
byte[] bytes = getTestBytes();
int length = bytes.length;
int[] bufferSizes = {0, 1, 128, 256, length / 2,
length - 1, length, length + 1,
2 * length, 3 * length};
for (int bufferSize : bufferSizes) {
ByteString.Output output = ByteString.newOutput(bufferSize);
for (byte byteValue : bytes) {
output.write(byteValue);
}
ByteString byteString = output.toByteString();
assertTrue("String built from newOutput() must contain the expected bytes",
isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length));
}
}
// Test newOutput() in which we write the bytes using a variety of methods
// and sizes, and in which we repeatedly call toByteString() in the middle.
public void testNewOutput_Mixed() throws IOException {
Random rng = new Random(1);
byte[] bytes = getTestBytes();
int length = bytes.length;
int[] bufferSizes = {0, 1, 128, 256, length / 2,
length - 1, length, length + 1,
2 * length, 3 * length};
for (int bufferSize : bufferSizes) {
// Test writing the entire output using a mixture of write sizes and
// methods;
ByteString.Output output = ByteString.newOutput(bufferSize);
int position = 0;
while (position < bytes.length) {
if (rng.nextBoolean()) {
int count = 1 + rng.nextInt(bytes.length - position);
output.write(bytes, position, count);
position += count;
} else {
output.write(bytes[position]);
position++;
}
assertEquals("size() returns the right value", position, output.size());
assertTrue("newOutput() substring must have correct bytes",
isArrayRange(output.toByteString().toByteArray(),
bytes, 0, position));
}
ByteString byteString = output.toByteString();
assertTrue("String built from newOutput() must contain the expected bytes",
isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length));
}
}
public void testNewOutputEmpty() throws IOException {
// Make sure newOutput() correctly builds empty byte strings
ByteString byteString = ByteString.newOutput().toByteString();
assertEquals(ByteString.EMPTY, byteString);
}
public void testNewOutput_Mutating() throws IOException {
Output os = ByteString.newOutput(5);
os.write(new byte[] {1, 2, 3, 4, 5});
EvilOutputStream eos = new EvilOutputStream();
os.writeTo(eos);
byte[] capturedArray = eos.capturedArray;
ByteString byteString = os.toByteString();
byte[] oldValue = byteString.toByteArray();
Arrays.fill(capturedArray, (byte) 0);
byte[] newValue = byteString.toByteArray();
assertTrue("Output must not provide access to the underlying byte array",
Arrays.equals(oldValue, newValue));
}
public void testSubstringParity() {
byte[] bigBytes = getTestBytes(2048 * 1024, 113344L);
int start = 512 * 1024 - 3333;
int end = 512 * 1024 + 7777;
ByteString concreteSubstring = ByteString.copyFrom(bigBytes).substring(start, end);
boolean ok = true;
for (int i = start; ok && i < end; ++i) {
ok = (bigBytes[i] == concreteSubstring.byteAt(i - start));
}
assertTrue("Concrete substring didn't capture the right bytes", ok);
ByteString literalString = ByteString.copyFrom(bigBytes, start, end - start);
assertTrue("Substring must be equal to literal string",
concreteSubstring.equals(literalString));
assertEquals("Substring must have same hashcode as literal string",
literalString.hashCode(), concreteSubstring.hashCode());
}
public void testCompositeSubstring() {
byte[] referenceBytes = getTestBytes(77748, 113344L);
List<ByteString> pieces = makeConcretePieces(referenceBytes);
ByteString listString = ByteString.copyFrom(pieces);
int from = 1000;
int to = 40000;
ByteString compositeSubstring = listString.substring(from, to);
byte[] substringBytes = compositeSubstring.toByteArray();
boolean stillEqual = true;
for (int i = 0; stillEqual && i < to - from; ++i) {
stillEqual = referenceBytes[from + i] == substringBytes[i];
}
assertTrue("Substring must return correct bytes", stillEqual);
stillEqual = true;
for (int i = 0; stillEqual && i < to - from; ++i) {
stillEqual = referenceBytes[from + i] == compositeSubstring.byteAt(i);
}
assertTrue("Substring must support byteAt() correctly", stillEqual);
ByteString literalSubstring = ByteString.copyFrom(referenceBytes, from, to - from);
assertTrue("Composite substring must equal a literal substring over the same bytes",
compositeSubstring.equals(literalSubstring));
assertTrue("Literal substring must equal a composite substring over the same bytes",
literalSubstring.equals(compositeSubstring));
assertEquals("We must get the same hashcodes for composite and literal substrings",
literalSubstring.hashCode(), compositeSubstring.hashCode());
assertFalse("We can't be equal to a proper substring",
compositeSubstring.equals(literalSubstring.substring(0, literalSubstring.size() - 1)));
}
public void testCopyFromList() {
byte[] referenceBytes = getTestBytes(77748, 113344L);
ByteString literalString = ByteString.copyFrom(referenceBytes);
List<ByteString> pieces = makeConcretePieces(referenceBytes);
ByteString listString = ByteString.copyFrom(pieces);
assertTrue("Composite string must be equal to literal string",
listString.equals(literalString));
assertEquals("Composite string must have same hashcode as literal string",
literalString.hashCode(), listString.hashCode());
}
public void testConcat() {
byte[] referenceBytes = getTestBytes(77748, 113344L);
ByteString literalString = ByteString.copyFrom(referenceBytes);
List<ByteString> pieces = makeConcretePieces(referenceBytes);
Iterator<ByteString> iter = pieces.iterator();
ByteString concatenatedString = iter.next();
while (iter.hasNext()) {
concatenatedString = concatenatedString.concat(iter.next());
}
assertTrue("Concatenated string must be equal to literal string",
concatenatedString.equals(literalString));
assertEquals("Concatenated string must have same hashcode as literal string",
literalString.hashCode(), concatenatedString.hashCode());
}
public void testStartsWith() {
byte[] bytes = getTestBytes(1000, 1234L);
ByteString string = ByteString.copyFrom(bytes);
ByteString prefix = ByteString.copyFrom(bytes, 0, 500);
ByteString suffix = ByteString.copyFrom(bytes, 400, 600);
assertTrue(string.startsWith(ByteString.EMPTY));
assertTrue(string.startsWith(string));
assertTrue(string.startsWith(prefix));
assertFalse(string.startsWith(suffix));
assertFalse(prefix.startsWith(suffix));
assertFalse(suffix.startsWith(prefix));
assertFalse(ByteString.EMPTY.startsWith(prefix));
assertTrue(ByteString.EMPTY.startsWith(ByteString.EMPTY));
}
static List<ByteString> makeConcretePieces(byte[] referenceBytes) {
List<ByteString> pieces = new ArrayList<ByteString>();
// Starting length should be small enough that we'll do some concatenating by
// copying if we just concatenate all these pieces together.
for (int start = 0, length = 16; start < referenceBytes.length; start += length) {
length = (length << 1) - 1;
if (start + length > referenceBytes.length) {
length = referenceBytes.length - start;
}
pieces.add(ByteString.copyFrom(referenceBytes, start, length));
}
return pieces;
}
}

@ -1,469 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestRecursiveMessage;
import junit.framework.TestCase;
import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.InputStream;
import java.io.IOException;
/**
* Unit test for {@link CodedInputStream}.
*
* @author kenton@google.com Kenton Varda
*/
public class CodedInputStreamTest extends TestCase {
/**
* Helper to construct a byte array from a bunch of bytes. The inputs are
* actually ints so that I can use hex notation and not get stupid errors
* about precision.
*/
private byte[] bytes(int... bytesAsInts) {
byte[] bytes = new byte[bytesAsInts.length];
for (int i = 0; i < bytesAsInts.length; i++) {
bytes[i] = (byte) bytesAsInts[i];
}
return bytes;
}
/**
* An InputStream which limits the number of bytes it reads at a time.
* We use this to make sure that CodedInputStream doesn't screw up when
* reading in small blocks.
*/
private static final class SmallBlockInputStream extends FilterInputStream {
private final int blockSize;
public SmallBlockInputStream(byte[] data, int blockSize) {
this(new ByteArrayInputStream(data), blockSize);
}
public SmallBlockInputStream(InputStream in, int blockSize) {
super(in);
this.blockSize = blockSize;
}
public int read(byte[] b) throws IOException {
return super.read(b, 0, Math.min(b.length, blockSize));
}
public int read(byte[] b, int off, int len) throws IOException {
return super.read(b, off, Math.min(len, blockSize));
}
}
/**
* Parses the given bytes using readRawVarint32() and readRawVarint64() and
* checks that the result matches the given value.
*/
private void assertReadVarint(byte[] data, long value) throws Exception {
CodedInputStream input = CodedInputStream.newInstance(data);
assertEquals((int)value, input.readRawVarint32());
input = CodedInputStream.newInstance(data);
assertEquals(value, input.readRawVarint64());
assertTrue(input.isAtEnd());
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
input = CodedInputStream.newInstance(
new SmallBlockInputStream(data, blockSize));
assertEquals((int)value, input.readRawVarint32());
input = CodedInputStream.newInstance(
new SmallBlockInputStream(data, blockSize));
assertEquals(value, input.readRawVarint64());
assertTrue(input.isAtEnd());
}
// Try reading direct from an InputStream. We want to verify that it
// doesn't read past the end of the input, so we copy to a new, bigger
// array first.
byte[] longerData = new byte[data.length + 1];
System.arraycopy(data, 0, longerData, 0, data.length);
InputStream rawInput = new ByteArrayInputStream(longerData);
}
/**
* Parses the given bytes using readRawVarint32() and readRawVarint64() and
* expects them to fail with an InvalidProtocolBufferException whose
* description matches the given one.
*/
private void assertReadVarintFailure(
InvalidProtocolBufferException expected, byte[] data)
throws Exception {
CodedInputStream input = CodedInputStream.newInstance(data);
try {
input.readRawVarint32();
fail("Should have thrown an exception.");
} catch (InvalidProtocolBufferException e) {
assertEquals(expected.getMessage(), e.getMessage());
}
input = CodedInputStream.newInstance(data);
try {
input.readRawVarint64();
fail("Should have thrown an exception.");
} catch (InvalidProtocolBufferException e) {
assertEquals(expected.getMessage(), e.getMessage());
}
}
/** Tests readRawVarint32() and readRawVarint64(). */
public void testReadVarint() throws Exception {
assertReadVarint(bytes(0x00), 0);
assertReadVarint(bytes(0x01), 1);
assertReadVarint(bytes(0x7f), 127);
// 14882
assertReadVarint(bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
// 2961488830
assertReadVarint(bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x0bL << 28));
// 64-bit
// 7256456126
assertReadVarint(bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x1bL << 28));
// 41256202580718336
assertReadVarint(
bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
(0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
(0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
// 11964378330978735131
assertReadVarint(
bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
(0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
(0x3bL << 28) | (0x56L << 35) | (0x00L << 42) |
(0x05L << 49) | (0x26L << 56) | (0x01L << 63));
}
/**
* Parses the given bytes using readRawLittleEndian32() and checks
* that the result matches the given value.
*/
private void assertReadLittleEndian32(byte[] data, int value)
throws Exception {
CodedInputStream input = CodedInputStream.newInstance(data);
assertEquals(value, input.readRawLittleEndian32());
assertTrue(input.isAtEnd());
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
input = CodedInputStream.newInstance(
new SmallBlockInputStream(data, blockSize));
assertEquals(value, input.readRawLittleEndian32());
assertTrue(input.isAtEnd());
}
}
/**
* Parses the given bytes using readRawLittleEndian64() and checks
* that the result matches the given value.
*/
private void assertReadLittleEndian64(byte[] data, long value)
throws Exception {
CodedInputStream input = CodedInputStream.newInstance(data);
assertEquals(value, input.readRawLittleEndian64());
assertTrue(input.isAtEnd());
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
input = CodedInputStream.newInstance(
new SmallBlockInputStream(data, blockSize));
assertEquals(value, input.readRawLittleEndian64());
assertTrue(input.isAtEnd());
}
}
/** Tests readRawLittleEndian32() and readRawLittleEndian64(). */
public void testReadLittleEndian() throws Exception {
assertReadLittleEndian32(bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
assertReadLittleEndian32(bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
assertReadLittleEndian64(
bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
0x123456789abcdef0L);
assertReadLittleEndian64(
bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a),
0x9abcdef012345678L);
}
/** Test decodeZigZag32() and decodeZigZag64(). */
public void testDecodeZigZag() throws Exception {
assertEquals( 0, CodedInputStream.decodeZigZag32(0));
assertEquals(-1, CodedInputStream.decodeZigZag32(1));
assertEquals( 1, CodedInputStream.decodeZigZag32(2));
assertEquals(-2, CodedInputStream.decodeZigZag32(3));
assertEquals(0x3FFFFFFF, CodedInputStream.decodeZigZag32(0x7FFFFFFE));
assertEquals(0xC0000000, CodedInputStream.decodeZigZag32(0x7FFFFFFF));
assertEquals(0x7FFFFFFF, CodedInputStream.decodeZigZag32(0xFFFFFFFE));
assertEquals(0x80000000, CodedInputStream.decodeZigZag32(0xFFFFFFFF));
assertEquals( 0, CodedInputStream.decodeZigZag64(0));
assertEquals(-1, CodedInputStream.decodeZigZag64(1));
assertEquals( 1, CodedInputStream.decodeZigZag64(2));
assertEquals(-2, CodedInputStream.decodeZigZag64(3));
assertEquals(0x000000003FFFFFFFL,
CodedInputStream.decodeZigZag64(0x000000007FFFFFFEL));
assertEquals(0xFFFFFFFFC0000000L,
CodedInputStream.decodeZigZag64(0x000000007FFFFFFFL));
assertEquals(0x000000007FFFFFFFL,
CodedInputStream.decodeZigZag64(0x00000000FFFFFFFEL));
assertEquals(0xFFFFFFFF80000000L,
CodedInputStream.decodeZigZag64(0x00000000FFFFFFFFL));
assertEquals(0x7FFFFFFFFFFFFFFFL,
CodedInputStream.decodeZigZag64(0xFFFFFFFFFFFFFFFEL));
assertEquals(0x8000000000000000L,
CodedInputStream.decodeZigZag64(0xFFFFFFFFFFFFFFFFL));
}
/** Tests reading and parsing a whole message with every field type. */
public void testReadWholeMessage() throws Exception {
TestAllTypes message = TestUtil.getAllSet();
byte[] rawBytes = message.toByteArray();
assertEquals(rawBytes.length, message.getSerializedSize());
TestAllTypes message2 = TestAllTypes.parseFrom(rawBytes);
TestUtil.assertAllFieldsSet(message2);
// Try different block sizes.
for (int blockSize = 1; blockSize < 256; blockSize *= 2) {
message2 = TestAllTypes.parseFrom(
new SmallBlockInputStream(rawBytes, blockSize));
TestUtil.assertAllFieldsSet(message2);
}
}
/** Tests skipField(). */
public void testSkipWholeMessage() throws Exception {
TestAllTypes message = TestUtil.getAllSet();
byte[] rawBytes = message.toByteArray();
// Create two parallel inputs. Parse one as unknown fields while using
// skipField() to skip each field on the other. Expect the same tags.
CodedInputStream input1 = CodedInputStream.newInstance(rawBytes);
CodedInputStream input2 = CodedInputStream.newInstance(rawBytes);
UnknownFieldSet.Builder unknownFields = UnknownFieldSet.newBuilder();
while (true) {
int tag = input1.readTag();
assertEquals(tag, input2.readTag());
if (tag == 0) {
break;
}
unknownFields.mergeFieldFrom(tag, input1);
input2.skipField(tag);
}
}
/**
* Test that a bug in skipRawBytes() has been fixed: if the skip skips
* exactly up to a limit, this should not break things.
*/
public void testSkipRawBytesBug() throws Exception {
byte[] rawBytes = new byte[] { 1, 2 };
CodedInputStream input = CodedInputStream.newInstance(rawBytes);
int limit = input.pushLimit(1);
input.skipRawBytes(1);
input.popLimit(limit);
assertEquals(2, input.readRawByte());
}
/**
* Test that a bug in skipRawBytes() has been fixed: if the skip skips
* past the end of a buffer with a limit that has been set past the end of
* that buffer, this should not break things.
*/
public void testSkipRawBytesPastEndOfBufferWithLimit() throws Exception {
byte[] rawBytes = new byte[] { 1, 2, 3, 4, 5 };
CodedInputStream input = CodedInputStream.newInstance(
new SmallBlockInputStream(rawBytes, 3));
int limit = input.pushLimit(4);
// In order to expose the bug we need to read at least one byte to prime the
// buffer inside the CodedInputStream.
assertEquals(1, input.readRawByte());
// Skip to the end of the limit.
input.skipRawBytes(3);
assertTrue(input.isAtEnd());
input.popLimit(limit);
assertEquals(5, input.readRawByte());
}
public void testReadHugeBlob() throws Exception {
// Allocate and initialize a 1MB blob.
byte[] blob = new byte[1 << 20];
for (int i = 0; i < blob.length; i++) {
blob[i] = (byte)i;
}
// Make a message containing it.
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestUtil.setAllFields(builder);
builder.setOptionalBytes(ByteString.copyFrom(blob));
TestAllTypes message = builder.build();
// Serialize and parse it. Make sure to parse from an InputStream, not
// directly from a ByteString, so that CodedInputStream uses buffered
// reading.
TestAllTypes message2 =
TestAllTypes.parseFrom(message.toByteString().newInput());
assertEquals(message.getOptionalBytes(), message2.getOptionalBytes());
// Make sure all the other fields were parsed correctly.
TestAllTypes message3 = TestAllTypes.newBuilder(message2)
.setOptionalBytes(TestUtil.getAllSet().getOptionalBytes())
.build();
TestUtil.assertAllFieldsSet(message3);
}
public int makeTag(int number, int tag) {
return (number << 3) + tag;
}
public void testReadMaliciouslyLargeBlob() throws Exception {
ByteString.Output rawOutput = ByteString.newOutput();
CodedOutputStream output = CodedOutputStream.newInstance(rawOutput);
int tag = makeTag(1, WireFormat.WIRETYPE_LENGTH_DELIMITED);
output.writeRawVarint32(tag);
output.writeRawVarint32(0x7FFFFFFF);
output.writeRawBytes(new byte[32]); // Pad with a few random bytes.
output.flush();
CodedInputStream input = rawOutput.toByteString().newCodedInput();
assertEquals(tag, input.readTag());
try {
input.readBytes();
fail("Should have thrown an exception!");
} catch (InvalidProtocolBufferException e) {
// success.
}
}
private TestRecursiveMessage makeRecursiveMessage(int depth) {
if (depth == 0) {
return TestRecursiveMessage.newBuilder().setI(5).build();
} else {
return TestRecursiveMessage.newBuilder()
.setA(makeRecursiveMessage(depth - 1)).build();
}
}
private void assertMessageDepth(TestRecursiveMessage message, int depth) {
if (depth == 0) {
assertFalse(message.hasA());
assertEquals(5, message.getI());
} else {
assertTrue(message.hasA());
assertMessageDepth(message.getA(), depth - 1);
}
}
public void testResetSizeCounter() throws Exception {
CodedInputStream input = CodedInputStream.newInstance(
new SmallBlockInputStream(new byte[256], 8));
input.setSizeLimit(16);
input.readRawBytes(16);
assertEquals(16, input.getTotalBytesRead());
try {
input.readRawByte();
fail("Should have thrown an exception!");
} catch (InvalidProtocolBufferException e) {
// success.
}
input.resetSizeCounter();
assertEquals(0, input.getTotalBytesRead());
input.readRawByte(); // No exception thrown.
input.resetSizeCounter();
assertEquals(0, input.getTotalBytesRead());
}
/**
* Tests that if we read an string that contains invalid UTF-8, no exception
* is thrown. Instead, the invalid bytes are replaced with the Unicode
* "replacement character" U+FFFD.
*/
public void testReadInvalidUtf8() throws Exception {
ByteString.Output rawOutput = ByteString.newOutput();
CodedOutputStream output = CodedOutputStream.newInstance(rawOutput);
int tag = makeTag(1, WireFormat.WIRETYPE_LENGTH_DELIMITED);
output.writeRawVarint32(tag);
output.writeRawVarint32(1);
output.writeRawBytes(new byte[] { (byte)0x80 });
output.flush();
CodedInputStream input = rawOutput.toByteString().newCodedInput();
assertEquals(tag, input.readTag());
String text = input.readString();
assertEquals(0xfffd, text.charAt(0));
}
public void testReadFromSlice() throws Exception {
byte[] bytes = bytes(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
CodedInputStream in = CodedInputStream.newInstance(bytes, 3, 5);
assertEquals(0, in.getTotalBytesRead());
for (int i = 3; i < 8; i++) {
assertEquals(i, in.readRawByte());
assertEquals(i-2, in.getTotalBytesRead());
}
// eof
assertEquals(0, in.readTag());
assertEquals(5, in.getTotalBytesRead());
}
public void testInvalidTag() throws Exception {
// Any tag number which corresponds to field number zero is invalid and
// should throw InvalidProtocolBufferException.
for (int i = 0; i < 8; i++) {
try {
CodedInputStream.newInstance(bytes(i)).readTag();
fail("Should have thrown an exception.");
} catch (InvalidProtocolBufferException e) {
}
}
}
}

@ -1,318 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import protobuf_unittest.UnittestProto.SparseEnumMessage;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestPackedTypes;
import protobuf_unittest.UnittestProto.TestSparseEnum;
import junit.framework.TestCase;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Unit test for {@link CodedOutputStream}.
*
* @author kenton@google.com Kenton Varda
*/
public class CodedOutputStreamTest extends TestCase {
/**
* Helper to construct a byte array from a bunch of bytes. The inputs are
* actually ints so that I can use hex notation and not get stupid errors
* about precision.
*/
private byte[] bytes(int... bytesAsInts) {
byte[] bytes = new byte[bytesAsInts.length];
for (int i = 0; i < bytesAsInts.length; i++) {
bytes[i] = (byte) bytesAsInts[i];
}
return bytes;
}
/** Arrays.asList() does not work with arrays of primitives. :( */
private List<Byte> toList(byte[] bytes) {
List<Byte> result = new ArrayList<Byte>();
for (byte b : bytes) {
result.add(b);
}
return result;
}
private void assertEqualBytes(byte[] a, byte[] b) {
assertEquals(toList(a), toList(b));
}
/**
* Writes the given value using writeRawVarint32() and writeRawVarint64() and
* checks that the result matches the given bytes.
*/
private void assertWriteVarint(byte[] data, long value) throws Exception {
// Only do 32-bit write if the value fits in 32 bits.
if ((value >>> 32) == 0) {
ByteArrayOutputStream rawOutput = new ByteArrayOutputStream();
CodedOutputStream output = CodedOutputStream.newInstance(rawOutput);
output.writeRawVarint32((int) value);
output.flush();
assertEqualBytes(data, rawOutput.toByteArray());
// Also try computing size.
assertEquals(data.length,
CodedOutputStream.computeRawVarint32Size((int) value));
}
{
ByteArrayOutputStream rawOutput = new ByteArrayOutputStream();
CodedOutputStream output = CodedOutputStream.newInstance(rawOutput);
output.writeRawVarint64(value);
output.flush();
assertEqualBytes(data, rawOutput.toByteArray());
// Also try computing size.
assertEquals(data.length,
CodedOutputStream.computeRawVarint64Size(value));
}
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
// Only do 32-bit write if the value fits in 32 bits.
if ((value >>> 32) == 0) {
ByteArrayOutputStream rawOutput = new ByteArrayOutputStream();
CodedOutputStream output =
CodedOutputStream.newInstance(rawOutput, blockSize);
output.writeRawVarint32((int) value);
output.flush();
assertEqualBytes(data, rawOutput.toByteArray());
}
{
ByteArrayOutputStream rawOutput = new ByteArrayOutputStream();
CodedOutputStream output =
CodedOutputStream.newInstance(rawOutput, blockSize);
output.writeRawVarint64(value);
output.flush();
assertEqualBytes(data, rawOutput.toByteArray());
}
}
}
/** Tests writeRawVarint32() and writeRawVarint64(). */
public void testWriteVarint() throws Exception {
assertWriteVarint(bytes(0x00), 0);
assertWriteVarint(bytes(0x01), 1);
assertWriteVarint(bytes(0x7f), 127);
// 14882
assertWriteVarint(bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
// 2961488830
assertWriteVarint(bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x0bL << 28));
// 64-bit
// 7256456126
assertWriteVarint(bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x1bL << 28));
// 41256202580718336
assertWriteVarint(
bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
(0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
(0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
// 11964378330978735131
assertWriteVarint(
bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
(0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
(0x3bL << 28) | (0x56L << 35) | (0x00L << 42) |
(0x05L << 49) | (0x26L << 56) | (0x01L << 63));
}
/**
* Parses the given bytes using writeRawLittleEndian32() and checks
* that the result matches the given value.
*/
private void assertWriteLittleEndian32(byte[] data, int value)
throws Exception {
ByteArrayOutputStream rawOutput = new ByteArrayOutputStream();
CodedOutputStream output = CodedOutputStream.newInstance(rawOutput);
output.writeRawLittleEndian32(value);
output.flush();
assertEqualBytes(data, rawOutput.toByteArray());
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
rawOutput = new ByteArrayOutputStream();
output = CodedOutputStream.newInstance(rawOutput, blockSize);
output.writeRawLittleEndian32(value);
output.flush();
assertEqualBytes(data, rawOutput.toByteArray());
}
}
/**
* Parses the given bytes using writeRawLittleEndian64() and checks
* that the result matches the given value.
*/
private void assertWriteLittleEndian64(byte[] data, long value)
throws Exception {
ByteArrayOutputStream rawOutput = new ByteArrayOutputStream();
CodedOutputStream output = CodedOutputStream.newInstance(rawOutput);
output.writeRawLittleEndian64(value);
output.flush();
assertEqualBytes(data, rawOutput.toByteArray());
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
rawOutput = new ByteArrayOutputStream();
output = CodedOutputStream.newInstance(rawOutput, blockSize);
output.writeRawLittleEndian64(value);
output.flush();
assertEqualBytes(data, rawOutput.toByteArray());
}
}
/** Tests writeRawLittleEndian32() and writeRawLittleEndian64(). */
public void testWriteLittleEndian() throws Exception {
assertWriteLittleEndian32(bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
assertWriteLittleEndian32(bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
assertWriteLittleEndian64(
bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
0x123456789abcdef0L);
assertWriteLittleEndian64(
bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a),
0x9abcdef012345678L);
}
/** Test encodeZigZag32() and encodeZigZag64(). */
public void testEncodeZigZag() throws Exception {
assertEquals(0, CodedOutputStream.encodeZigZag32( 0));
assertEquals(1, CodedOutputStream.encodeZigZag32(-1));
assertEquals(2, CodedOutputStream.encodeZigZag32( 1));
assertEquals(3, CodedOutputStream.encodeZigZag32(-2));
assertEquals(0x7FFFFFFE, CodedOutputStream.encodeZigZag32(0x3FFFFFFF));
assertEquals(0x7FFFFFFF, CodedOutputStream.encodeZigZag32(0xC0000000));
assertEquals(0xFFFFFFFE, CodedOutputStream.encodeZigZag32(0x7FFFFFFF));
assertEquals(0xFFFFFFFF, CodedOutputStream.encodeZigZag32(0x80000000));
assertEquals(0, CodedOutputStream.encodeZigZag64( 0));
assertEquals(1, CodedOutputStream.encodeZigZag64(-1));
assertEquals(2, CodedOutputStream.encodeZigZag64( 1));
assertEquals(3, CodedOutputStream.encodeZigZag64(-2));
assertEquals(0x000000007FFFFFFEL,
CodedOutputStream.encodeZigZag64(0x000000003FFFFFFFL));
assertEquals(0x000000007FFFFFFFL,
CodedOutputStream.encodeZigZag64(0xFFFFFFFFC0000000L));
assertEquals(0x00000000FFFFFFFEL,
CodedOutputStream.encodeZigZag64(0x000000007FFFFFFFL));
assertEquals(0x00000000FFFFFFFFL,
CodedOutputStream.encodeZigZag64(0xFFFFFFFF80000000L));
assertEquals(0xFFFFFFFFFFFFFFFEL,
CodedOutputStream.encodeZigZag64(0x7FFFFFFFFFFFFFFFL));
assertEquals(0xFFFFFFFFFFFFFFFFL,
CodedOutputStream.encodeZigZag64(0x8000000000000000L));
// Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
// were chosen semi-randomly via keyboard bashing.
assertEquals(0,
CodedOutputStream.encodeZigZag32(CodedInputStream.decodeZigZag32(0)));
assertEquals(1,
CodedOutputStream.encodeZigZag32(CodedInputStream.decodeZigZag32(1)));
assertEquals(-1,
CodedOutputStream.encodeZigZag32(CodedInputStream.decodeZigZag32(-1)));
assertEquals(14927,
CodedOutputStream.encodeZigZag32(CodedInputStream.decodeZigZag32(14927)));
assertEquals(-3612,
CodedOutputStream.encodeZigZag32(CodedInputStream.decodeZigZag32(-3612)));
assertEquals(0,
CodedOutputStream.encodeZigZag64(CodedInputStream.decodeZigZag64(0)));
assertEquals(1,
CodedOutputStream.encodeZigZag64(CodedInputStream.decodeZigZag64(1)));
assertEquals(-1,
CodedOutputStream.encodeZigZag64(CodedInputStream.decodeZigZag64(-1)));
assertEquals(14927,
CodedOutputStream.encodeZigZag64(CodedInputStream.decodeZigZag64(14927)));
assertEquals(-3612,
CodedOutputStream.encodeZigZag64(CodedInputStream.decodeZigZag64(-3612)));
assertEquals(856912304801416L,
CodedOutputStream.encodeZigZag64(
CodedInputStream.decodeZigZag64(
856912304801416L)));
assertEquals(-75123905439571256L,
CodedOutputStream.encodeZigZag64(
CodedInputStream.decodeZigZag64(
-75123905439571256L)));
}
/** Tests writing a whole message with every field type. */
public void testWriteWholeMessage() throws Exception {
TestAllTypes message = TestUtil.getAllSet();
byte[] rawBytes = message.toByteArray();
assertEqualBytes(TestUtil.getGoldenMessage().toByteArray(), rawBytes);
// Try different block sizes.
for (int blockSize = 1; blockSize < 256; blockSize *= 2) {
ByteArrayOutputStream rawOutput = new ByteArrayOutputStream();
CodedOutputStream output =
CodedOutputStream.newInstance(rawOutput, blockSize);
message.writeTo(output);
output.flush();
assertEqualBytes(rawBytes, rawOutput.toByteArray());
}
}
/** Tests writing a whole message with every packed field type. Ensures the
* wire format of packed fields is compatible with C++. */
public void testWriteWholePackedFieldsMessage() throws Exception {
TestPackedTypes message = TestUtil.getPackedSet();
byte[] rawBytes = message.toByteArray();
assertEqualBytes(TestUtil.getGoldenPackedFieldsMessage().toByteArray(),
rawBytes);
}
/** Test writing a message containing a negative enum value. This used to
* fail because the size was not properly computed as a sign-extended varint.
*/
public void testWriteMessageWithNegativeEnumValue() throws Exception {
SparseEnumMessage message = SparseEnumMessage.newBuilder()
.setSparseEnum(TestSparseEnum.SPARSE_E) .build();
assertTrue(message.getSparseEnum().getNumber() < 0);
byte[] rawBytes = message.toByteArray();
SparseEnumMessage message2 = SparseEnumMessage.parseFrom(rawBytes);
assertEquals(TestSparseEnum.SPARSE_E, message2.getSparseEnum());
}
}

@ -1,81 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import protobuf_unittest.UnittestProto.TestDeprecatedFields;
import junit.framework.TestCase;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
/**
* Test field deprecation
*
* @author birdo@google.com (Roberto Scaramuzzi)
*/
public class DeprecatedFieldTest extends TestCase {
private String[] deprecatedGetterNames = {
"hasDeprecatedInt32",
"getDeprecatedInt32"};
private String[] deprecatedBuilderGetterNames = {
"hasDeprecatedInt32",
"getDeprecatedInt32",
"clearDeprecatedInt32"};
private String[] deprecatedBuilderSetterNames = {
"setDeprecatedInt32"};
public void testDeprecatedField() throws Exception {
Class<?> deprecatedFields = TestDeprecatedFields.class;
Class<?> deprecatedFieldsBuilder = TestDeprecatedFields.Builder.class;
for (String name : deprecatedGetterNames) {
Method method = deprecatedFields.getMethod(name);
assertTrue("Method " + name + " should be deprecated",
isDeprecated(method));
}
for (String name : deprecatedBuilderGetterNames) {
Method method = deprecatedFieldsBuilder.getMethod(name);
assertTrue("Method " + name + " should be deprecated",
isDeprecated(method));
}
for (String name : deprecatedBuilderSetterNames) {
Method method = deprecatedFieldsBuilder.getMethod(name, int.class);
assertTrue("Method " + name + " should be deprecated",
isDeprecated(method));
}
}
private boolean isDeprecated(AnnotatedElement annotated) {
return annotated.isAnnotationPresent(Deprecated.class);
}
}

@ -1,649 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import com.google.protobuf.DescriptorProtos.DescriptorProto;
import com.google.protobuf.DescriptorProtos.EnumDescriptorProto;
import com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto;
import com.google.protobuf.DescriptorProtos.FieldDescriptorProto;
import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
import com.google.protobuf.Descriptors.DescriptorValidationException;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.ServiceDescriptor;
import com.google.protobuf.Descriptors.MethodDescriptor;
import com.google.protobuf.test.UnittestImport;
import com.google.protobuf.test.UnittestImport.ImportEnum;
import com.google.protobuf.test.UnittestImport.ImportMessage;
import protobuf_unittest.UnittestProto;
import protobuf_unittest.UnittestProto.ForeignEnum;
import protobuf_unittest.UnittestProto.ForeignMessage;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestExtremeDefaultValues;
import protobuf_unittest.UnittestProto.TestRequired;
import protobuf_unittest.UnittestProto.TestService;
import protobuf_unittest.UnittestCustomOptions;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Unit test for {@link Descriptors}.
*
* @author kenton@google.com Kenton Varda
*/
public class DescriptorsTest extends TestCase {
// Regression test for bug where referencing a FieldDescriptor.Type value
// before a FieldDescriptorProto.Type value would yield a
// ExceptionInInitializerError.
@SuppressWarnings("unused")
private static final Object STATIC_INIT_TEST = FieldDescriptor.Type.BOOL;
public void testFieldTypeEnumMapping() throws Exception {
assertEquals(FieldDescriptor.Type.values().length,
FieldDescriptorProto.Type.values().length);
for (FieldDescriptor.Type type : FieldDescriptor.Type.values()) {
FieldDescriptorProto.Type protoType = type.toProto();
assertEquals("TYPE_" + type.name(), protoType.name());
assertEquals(type, FieldDescriptor.Type.valueOf(protoType));
}
}
public void testFileDescriptor() throws Exception {
FileDescriptor file = UnittestProto.getDescriptor();
assertEquals("google/protobuf/unittest.proto", file.getName());
assertEquals("protobuf_unittest", file.getPackage());
assertEquals("UnittestProto", file.getOptions().getJavaOuterClassname());
assertEquals("google/protobuf/unittest.proto",
file.toProto().getName());
assertEquals(Arrays.asList(UnittestImport.getDescriptor()),
file.getDependencies());
Descriptor messageType = TestAllTypes.getDescriptor();
assertEquals(messageType, file.getMessageTypes().get(0));
assertEquals(messageType, file.findMessageTypeByName("TestAllTypes"));
assertNull(file.findMessageTypeByName("NoSuchType"));
assertNull(file.findMessageTypeByName("protobuf_unittest.TestAllTypes"));
for (int i = 0; i < file.getMessageTypes().size(); i++) {
assertEquals(i, file.getMessageTypes().get(i).getIndex());
}
EnumDescriptor enumType = ForeignEnum.getDescriptor();
assertEquals(enumType, file.getEnumTypes().get(0));
assertEquals(enumType, file.findEnumTypeByName("ForeignEnum"));
assertNull(file.findEnumTypeByName("NoSuchType"));
assertNull(file.findEnumTypeByName("protobuf_unittest.ForeignEnum"));
assertEquals(Arrays.asList(ImportEnum.getDescriptor()),
UnittestImport.getDescriptor().getEnumTypes());
for (int i = 0; i < file.getEnumTypes().size(); i++) {
assertEquals(i, file.getEnumTypes().get(i).getIndex());
}
ServiceDescriptor service = TestService.getDescriptor();
assertEquals(service, file.getServices().get(0));
assertEquals(service, file.findServiceByName("TestService"));
assertNull(file.findServiceByName("NoSuchType"));
assertNull(file.findServiceByName("protobuf_unittest.TestService"));
assertEquals(Collections.emptyList(),
UnittestImport.getDescriptor().getServices());
for (int i = 0; i < file.getServices().size(); i++) {
assertEquals(i, file.getServices().get(i).getIndex());
}
FieldDescriptor extension =
UnittestProto.optionalInt32Extension.getDescriptor();
assertEquals(extension, file.getExtensions().get(0));
assertEquals(extension,
file.findExtensionByName("optional_int32_extension"));
assertNull(file.findExtensionByName("no_such_ext"));
assertNull(file.findExtensionByName(
"protobuf_unittest.optional_int32_extension"));
assertEquals(Collections.emptyList(),
UnittestImport.getDescriptor().getExtensions());
for (int i = 0; i < file.getExtensions().size(); i++) {
assertEquals(i, file.getExtensions().get(i).getIndex());
}
}
public void testDescriptor() throws Exception {
Descriptor messageType = TestAllTypes.getDescriptor();
Descriptor nestedType = TestAllTypes.NestedMessage.getDescriptor();
assertEquals("TestAllTypes", messageType.getName());
assertEquals("protobuf_unittest.TestAllTypes", messageType.getFullName());
assertEquals(UnittestProto.getDescriptor(), messageType.getFile());
assertNull(messageType.getContainingType());
assertEquals(DescriptorProtos.MessageOptions.getDefaultInstance(),
messageType.getOptions());
assertEquals("TestAllTypes", messageType.toProto().getName());
assertEquals("NestedMessage", nestedType.getName());
assertEquals("protobuf_unittest.TestAllTypes.NestedMessage",
nestedType.getFullName());
assertEquals(UnittestProto.getDescriptor(), nestedType.getFile());
assertEquals(messageType, nestedType.getContainingType());
FieldDescriptor field = messageType.getFields().get(0);
assertEquals("optional_int32", field.getName());
assertEquals(field, messageType.findFieldByName("optional_int32"));
assertNull(messageType.findFieldByName("no_such_field"));
assertEquals(field, messageType.findFieldByNumber(1));
assertNull(messageType.findFieldByNumber(571283));
for (int i = 0; i < messageType.getFields().size(); i++) {
assertEquals(i, messageType.getFields().get(i).getIndex());
}
assertEquals(nestedType, messageType.getNestedTypes().get(0));
assertEquals(nestedType, messageType.findNestedTypeByName("NestedMessage"));
assertNull(messageType.findNestedTypeByName("NoSuchType"));
for (int i = 0; i < messageType.getNestedTypes().size(); i++) {
assertEquals(i, messageType.getNestedTypes().get(i).getIndex());
}
EnumDescriptor enumType = TestAllTypes.NestedEnum.getDescriptor();
assertEquals(enumType, messageType.getEnumTypes().get(0));
assertEquals(enumType, messageType.findEnumTypeByName("NestedEnum"));
assertNull(messageType.findEnumTypeByName("NoSuchType"));
for (int i = 0; i < messageType.getEnumTypes().size(); i++) {
assertEquals(i, messageType.getEnumTypes().get(i).getIndex());
}
}
public void testFieldDescriptor() throws Exception {
Descriptor messageType = TestAllTypes.getDescriptor();
FieldDescriptor primitiveField =
messageType.findFieldByName("optional_int32");
FieldDescriptor enumField =
messageType.findFieldByName("optional_nested_enum");
FieldDescriptor messageField =
messageType.findFieldByName("optional_foreign_message");
FieldDescriptor cordField =
messageType.findFieldByName("optional_cord");
FieldDescriptor extension =
UnittestProto.optionalInt32Extension.getDescriptor();
FieldDescriptor nestedExtension = TestRequired.single.getDescriptor();
assertEquals("optional_int32", primitiveField.getName());
assertEquals("protobuf_unittest.TestAllTypes.optional_int32",
primitiveField.getFullName());
assertEquals(1, primitiveField.getNumber());
assertEquals(messageType, primitiveField.getContainingType());
assertEquals(UnittestProto.getDescriptor(), primitiveField.getFile());
assertEquals(FieldDescriptor.Type.INT32, primitiveField.getType());
assertEquals(FieldDescriptor.JavaType.INT, primitiveField.getJavaType());
assertEquals(DescriptorProtos.FieldOptions.getDefaultInstance(),
primitiveField.getOptions());
assertFalse(primitiveField.isExtension());
assertEquals("optional_int32", primitiveField.toProto().getName());
assertEquals("optional_nested_enum", enumField.getName());
assertEquals(FieldDescriptor.Type.ENUM, enumField.getType());
assertEquals(FieldDescriptor.JavaType.ENUM, enumField.getJavaType());
assertEquals(TestAllTypes.NestedEnum.getDescriptor(),
enumField.getEnumType());
assertEquals("optional_foreign_message", messageField.getName());
assertEquals(FieldDescriptor.Type.MESSAGE, messageField.getType());
assertEquals(FieldDescriptor.JavaType.MESSAGE, messageField.getJavaType());
assertEquals(ForeignMessage.getDescriptor(), messageField.getMessageType());
assertEquals("optional_cord", cordField.getName());
assertEquals(FieldDescriptor.Type.STRING, cordField.getType());
assertEquals(FieldDescriptor.JavaType.STRING, cordField.getJavaType());
assertEquals(DescriptorProtos.FieldOptions.CType.CORD,
cordField.getOptions().getCtype());
assertEquals("optional_int32_extension", extension.getName());
assertEquals("protobuf_unittest.optional_int32_extension",
extension.getFullName());
assertEquals(1, extension.getNumber());
assertEquals(TestAllExtensions.getDescriptor(),
extension.getContainingType());
assertEquals(UnittestProto.getDescriptor(), extension.getFile());
assertEquals(FieldDescriptor.Type.INT32, extension.getType());
assertEquals(FieldDescriptor.JavaType.INT, extension.getJavaType());
assertEquals(DescriptorProtos.FieldOptions.getDefaultInstance(),
extension.getOptions());
assertTrue(extension.isExtension());
assertEquals(null, extension.getExtensionScope());
assertEquals("optional_int32_extension", extension.toProto().getName());
assertEquals("single", nestedExtension.getName());
assertEquals("protobuf_unittest.TestRequired.single",
nestedExtension.getFullName());
assertEquals(TestRequired.getDescriptor(),
nestedExtension.getExtensionScope());
}
public void testFieldDescriptorLabel() throws Exception {
FieldDescriptor requiredField =
TestRequired.getDescriptor().findFieldByName("a");
FieldDescriptor optionalField =
TestAllTypes.getDescriptor().findFieldByName("optional_int32");
FieldDescriptor repeatedField =
TestAllTypes.getDescriptor().findFieldByName("repeated_int32");
assertTrue(requiredField.isRequired());
assertFalse(requiredField.isRepeated());
assertFalse(optionalField.isRequired());
assertFalse(optionalField.isRepeated());
assertFalse(repeatedField.isRequired());
assertTrue(repeatedField.isRepeated());
}
public void testFieldDescriptorDefault() throws Exception {
Descriptor d = TestAllTypes.getDescriptor();
assertFalse(d.findFieldByName("optional_int32").hasDefaultValue());
assertEquals(0, d.findFieldByName("optional_int32").getDefaultValue());
assertTrue(d.findFieldByName("default_int32").hasDefaultValue());
assertEquals(41, d.findFieldByName("default_int32").getDefaultValue());
d = TestExtremeDefaultValues.getDescriptor();
assertEquals(
ByteString.copyFrom(
"\0\001\007\b\f\n\r\t\013\\\'\"\u00fe".getBytes("ISO-8859-1")),
d.findFieldByName("escaped_bytes").getDefaultValue());
assertEquals(-1, d.findFieldByName("large_uint32").getDefaultValue());
assertEquals(-1L, d.findFieldByName("large_uint64").getDefaultValue());
}
public void testEnumDescriptor() throws Exception {
EnumDescriptor enumType = ForeignEnum.getDescriptor();
EnumDescriptor nestedType = TestAllTypes.NestedEnum.getDescriptor();
assertEquals("ForeignEnum", enumType.getName());
assertEquals("protobuf_unittest.ForeignEnum", enumType.getFullName());
assertEquals(UnittestProto.getDescriptor(), enumType.getFile());
assertNull(enumType.getContainingType());
assertEquals(DescriptorProtos.EnumOptions.getDefaultInstance(),
enumType.getOptions());
assertEquals("NestedEnum", nestedType.getName());
assertEquals("protobuf_unittest.TestAllTypes.NestedEnum",
nestedType.getFullName());
assertEquals(UnittestProto.getDescriptor(), nestedType.getFile());
assertEquals(TestAllTypes.getDescriptor(), nestedType.getContainingType());
EnumValueDescriptor value = ForeignEnum.FOREIGN_FOO.getValueDescriptor();
assertEquals(value, enumType.getValues().get(0));
assertEquals("FOREIGN_FOO", value.getName());
assertEquals(4, value.getNumber());
assertEquals(value, enumType.findValueByName("FOREIGN_FOO"));
assertEquals(value, enumType.findValueByNumber(4));
assertNull(enumType.findValueByName("NO_SUCH_VALUE"));
for (int i = 0; i < enumType.getValues().size(); i++) {
assertEquals(i, enumType.getValues().get(i).getIndex());
}
}
public void testServiceDescriptor() throws Exception {
ServiceDescriptor service = TestService.getDescriptor();
assertEquals("TestService", service.getName());
assertEquals("protobuf_unittest.TestService", service.getFullName());
assertEquals(UnittestProto.getDescriptor(), service.getFile());
assertEquals(2, service.getMethods().size());
MethodDescriptor fooMethod = service.getMethods().get(0);
assertEquals("Foo", fooMethod.getName());
assertEquals(UnittestProto.FooRequest.getDescriptor(),
fooMethod.getInputType());
assertEquals(UnittestProto.FooResponse.getDescriptor(),
fooMethod.getOutputType());
assertEquals(fooMethod, service.findMethodByName("Foo"));
MethodDescriptor barMethod = service.getMethods().get(1);
assertEquals("Bar", barMethod.getName());
assertEquals(UnittestProto.BarRequest.getDescriptor(),
barMethod.getInputType());
assertEquals(UnittestProto.BarResponse.getDescriptor(),
barMethod.getOutputType());
assertEquals(barMethod, service.findMethodByName("Bar"));
assertNull(service.findMethodByName("NoSuchMethod"));
for (int i = 0; i < service.getMethods().size(); i++) {
assertEquals(i, service.getMethods().get(i).getIndex());
}
}
public void testCustomOptions() throws Exception {
Descriptor descriptor =
UnittestCustomOptions.TestMessageWithCustomOptions.getDescriptor();
assertTrue(
descriptor.getOptions().hasExtension(UnittestCustomOptions.messageOpt1));
assertEquals(Integer.valueOf(-56),
descriptor.getOptions().getExtension(UnittestCustomOptions.messageOpt1));
FieldDescriptor field = descriptor.findFieldByName("field1");
assertNotNull(field);
assertTrue(
field.getOptions().hasExtension(UnittestCustomOptions.fieldOpt1));
assertEquals(Long.valueOf(8765432109L),
field.getOptions().getExtension(UnittestCustomOptions.fieldOpt1));
EnumDescriptor enumType =
UnittestCustomOptions.TestMessageWithCustomOptions.AnEnum.getDescriptor();
assertTrue(
enumType.getOptions().hasExtension(UnittestCustomOptions.enumOpt1));
assertEquals(Integer.valueOf(-789),
enumType.getOptions().getExtension(UnittestCustomOptions.enumOpt1));
ServiceDescriptor service =
UnittestCustomOptions.TestServiceWithCustomOptions.getDescriptor();
assertTrue(
service.getOptions().hasExtension(UnittestCustomOptions.serviceOpt1));
assertEquals(Long.valueOf(-9876543210L),
service.getOptions().getExtension(UnittestCustomOptions.serviceOpt1));
MethodDescriptor method = service.findMethodByName("Foo");
assertNotNull(method);
assertTrue(
method.getOptions().hasExtension(UnittestCustomOptions.methodOpt1));
assertEquals(UnittestCustomOptions.MethodOpt1.METHODOPT1_VAL2,
method.getOptions().getExtension(UnittestCustomOptions.methodOpt1));
}
/**
* Test that the FieldDescriptor.Type enum is the same as the
* WireFormat.FieldType enum.
*/
public void testFieldTypeTablesMatch() throws Exception {
FieldDescriptor.Type[] values1 = FieldDescriptor.Type.values();
WireFormat.FieldType[] values2 = WireFormat.FieldType.values();
assertEquals(values1.length, values2.length);
for (int i = 0; i < values1.length; i++) {
assertEquals(values1[i].toString(), values2[i].toString());
}
}
/**
* Test that the FieldDescriptor.JavaType enum is the same as the
* WireFormat.JavaType enum.
*/
public void testJavaTypeTablesMatch() throws Exception {
FieldDescriptor.JavaType[] values1 = FieldDescriptor.JavaType.values();
WireFormat.JavaType[] values2 = WireFormat.JavaType.values();
assertEquals(values1.length, values2.length);
for (int i = 0; i < values1.length; i++) {
assertEquals(values1[i].toString(), values2[i].toString());
}
}
public void testEnormousDescriptor() throws Exception {
// The descriptor for this file is larger than 64k, yet it did not cause
// a compiler error due to an over-long string literal.
assertTrue(
UnittestEnormousDescriptor.getDescriptor()
.toProto().getSerializedSize() > 65536);
}
/**
* Tests that the DescriptorValidationException works as intended.
*/
public void testDescriptorValidatorException() throws Exception {
FileDescriptorProto fileDescriptorProto = FileDescriptorProto.newBuilder()
.setName("foo.proto")
.addMessageType(DescriptorProto.newBuilder()
.setName("Foo")
.addField(FieldDescriptorProto.newBuilder()
.setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)
.setType(FieldDescriptorProto.Type.TYPE_INT32)
.setName("foo")
.setNumber(1)
.setDefaultValue("invalid")
.build())
.build())
.build();
try {
Descriptors.FileDescriptor.buildFrom(fileDescriptorProto,
new FileDescriptor[0]);
fail("DescriptorValidationException expected");
} catch (DescriptorValidationException e) {
// Expected; check that the error message contains some useful hints
assertTrue(e.getMessage().indexOf("foo") != -1);
assertTrue(e.getMessage().indexOf("Foo") != -1);
assertTrue(e.getMessage().indexOf("invalid") != -1);
assertTrue(e.getCause() instanceof NumberFormatException);
assertTrue(e.getCause().getMessage().indexOf("invalid") != -1);
}
}
/**
* Tests the translate/crosslink for an example where a message field's name
* and type name are the same.
*/
public void testDescriptorComplexCrosslink() throws Exception {
FileDescriptorProto fileDescriptorProto = FileDescriptorProto.newBuilder()
.setName("foo.proto")
.addMessageType(DescriptorProto.newBuilder()
.setName("Foo")
.addField(FieldDescriptorProto.newBuilder()
.setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)
.setType(FieldDescriptorProto.Type.TYPE_INT32)
.setName("foo")
.setNumber(1)
.build())
.build())
.addMessageType(DescriptorProto.newBuilder()
.setName("Bar")
.addField(FieldDescriptorProto.newBuilder()
.setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)
.setTypeName("Foo")
.setName("Foo")
.setNumber(1)
.build())
.build())
.build();
// translate and crosslink
FileDescriptor file =
Descriptors.FileDescriptor.buildFrom(fileDescriptorProto,
new FileDescriptor[0]);
// verify resulting descriptors
assertNotNull(file);
List<Descriptor> msglist = file.getMessageTypes();
assertNotNull(msglist);
assertTrue(msglist.size() == 2);
boolean barFound = false;
for (Descriptor desc : msglist) {
if (desc.getName().equals("Bar")) {
barFound = true;
assertNotNull(desc.getFields());
List<FieldDescriptor> fieldlist = desc.getFields();
assertNotNull(fieldlist);
assertTrue(fieldlist.size() == 1);
assertTrue(fieldlist.get(0).getType() == FieldDescriptor.Type.MESSAGE);
assertTrue(fieldlist.get(0).getMessageType().getName().equals("Foo"));
}
}
assertTrue(barFound);
}
public void testInvalidPublicDependency() throws Exception {
FileDescriptorProto fooProto = FileDescriptorProto.newBuilder()
.setName("foo.proto") .build();
FileDescriptorProto barProto = FileDescriptorProto.newBuilder()
.setName("boo.proto")
.addDependency("foo.proto")
.addPublicDependency(1) // Error, should be 0.
.build();
FileDescriptor fooFile = Descriptors.FileDescriptor.buildFrom(fooProto,
new FileDescriptor[0]);
try {
Descriptors.FileDescriptor.buildFrom(barProto,
new FileDescriptor[] {fooFile});
fail("DescriptorValidationException expected");
} catch (DescriptorValidationException e) {
assertTrue(
e.getMessage().indexOf("Invalid public dependency index.") != -1);
}
}
public void testHiddenDependency() throws Exception {
FileDescriptorProto barProto = FileDescriptorProto.newBuilder()
.setName("bar.proto")
.addMessageType(DescriptorProto.newBuilder().setName("Bar"))
.build();
FileDescriptorProto forwardProto = FileDescriptorProto.newBuilder()
.setName("forward.proto")
.addDependency("bar.proto")
.build();
FileDescriptorProto fooProto = FileDescriptorProto.newBuilder()
.setName("foo.proto")
.addDependency("forward.proto")
.addMessageType(DescriptorProto.newBuilder()
.setName("Foo")
.addField(FieldDescriptorProto.newBuilder()
.setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)
.setTypeName("Bar")
.setName("bar")
.setNumber(1)))
.build();
FileDescriptor barFile = Descriptors.FileDescriptor.buildFrom(
barProto, new FileDescriptor[0]);
FileDescriptor forwardFile = Descriptors.FileDescriptor.buildFrom(
forwardProto, new FileDescriptor[] {barFile});
try {
Descriptors.FileDescriptor.buildFrom(
fooProto, new FileDescriptor[] {forwardFile});
fail("DescriptorValidationException expected");
} catch (DescriptorValidationException e) {
assertTrue(e.getMessage().indexOf("Bar") != -1);
assertTrue(e.getMessage().indexOf("is not defined") != -1);
}
}
public void testPublicDependency() throws Exception {
FileDescriptorProto barProto = FileDescriptorProto.newBuilder()
.setName("bar.proto")
.addMessageType(DescriptorProto.newBuilder().setName("Bar"))
.build();
FileDescriptorProto forwardProto = FileDescriptorProto.newBuilder()
.setName("forward.proto")
.addDependency("bar.proto")
.addPublicDependency(0)
.build();
FileDescriptorProto fooProto = FileDescriptorProto.newBuilder()
.setName("foo.proto")
.addDependency("forward.proto")
.addMessageType(DescriptorProto.newBuilder()
.setName("Foo")
.addField(FieldDescriptorProto.newBuilder()
.setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)
.setTypeName("Bar")
.setName("bar")
.setNumber(1)))
.build();
FileDescriptor barFile = Descriptors.FileDescriptor.buildFrom(
barProto, new FileDescriptor[0]);
FileDescriptor forwardFile = Descriptors.FileDescriptor.buildFrom(
forwardProto, new FileDescriptor[]{barFile});
Descriptors.FileDescriptor.buildFrom(
fooProto, new FileDescriptor[] {forwardFile});
}
/**
* Tests the translate/crosslink for an example with a more complex namespace
* referencing.
*/
public void testComplexNamespacePublicDependency() throws Exception {
FileDescriptorProto fooProto = FileDescriptorProto.newBuilder()
.setName("bar.proto")
.setPackage("a.b.c.d.bar.shared")
.addEnumType(EnumDescriptorProto.newBuilder()
.setName("MyEnum")
.addValue(EnumValueDescriptorProto.newBuilder()
.setName("BLAH")
.setNumber(1)))
.build();
FileDescriptorProto barProto = FileDescriptorProto.newBuilder()
.setName("foo.proto")
.addDependency("bar.proto")
.setPackage("a.b.c.d.foo.shared")
.addMessageType(DescriptorProto.newBuilder()
.setName("MyMessage")
.addField(FieldDescriptorProto.newBuilder()
.setLabel(FieldDescriptorProto.Label.LABEL_REPEATED)
.setTypeName("bar.shared.MyEnum")
.setName("MyField")
.setNumber(1)))
.build();
// translate and crosslink
FileDescriptor fooFile = Descriptors.FileDescriptor.buildFrom(
fooProto, new FileDescriptor[0]);
FileDescriptor barFile = Descriptors.FileDescriptor.buildFrom(
barProto, new FileDescriptor[]{fooFile});
// verify resulting descriptors
assertNotNull(barFile);
List<Descriptor> msglist = barFile.getMessageTypes();
assertNotNull(msglist);
assertTrue(msglist.size() == 1);
Descriptor desc = msglist.get(0);
if (desc.getName().equals("MyMessage")) {
assertNotNull(desc.getFields());
List<FieldDescriptor> fieldlist = desc.getFields();
assertNotNull(fieldlist);
assertTrue(fieldlist.size() == 1);
FieldDescriptor field = fieldlist.get(0);
assertTrue(field.getType() == FieldDescriptor.Type.ENUM);
assertTrue(field.getEnumType().getName().equals("MyEnum"));
assertTrue(field.getEnumType().getFile().getName().equals("bar.proto"));
assertTrue(field.getEnumType().getFile().getPackage().equals(
"a.b.c.d.bar.shared"));
}
}
}

@ -1,265 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
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;
/**
* Unit test for {@link DynamicMessage}. See also {@link MessageTest}, which
* tests some {@link DynamicMessage} functionality.
*
* @author kenton@google.com Kenton Varda
*/
public class DynamicMessageTest extends TestCase {
TestUtil.ReflectionTester reflectionTester =
new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
TestUtil.ReflectionTester extensionsReflectionTester =
new TestUtil.ReflectionTester(TestAllExtensions.getDescriptor(),
TestUtil.getExtensionRegistry());
TestUtil.ReflectionTester packedReflectionTester =
new TestUtil.ReflectionTester(TestPackedTypes.getDescriptor(), null);
public void testDynamicMessageAccessors() throws Exception {
Message.Builder builder =
DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(builder);
Message message = builder.build();
reflectionTester.assertAllFieldsSetViaReflection(message);
}
public void testSettersAfterBuild() throws Exception {
Message.Builder builder =
DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
Message firstMessage = builder.build();
// double build()
builder.build();
// clear() after build()
builder.clear();
// setters after build()
reflectionTester.setAllFieldsViaReflection(builder);
Message message = builder.build();
reflectionTester.assertAllFieldsSetViaReflection(message);
// repeated setters after build()
reflectionTester.modifyRepeatedFieldsViaReflection(builder);
message = builder.build();
reflectionTester.assertRepeatedFieldsModifiedViaReflection(message);
// firstMessage shouldn't have been modified.
reflectionTester.assertClearViaReflection(firstMessage);
}
public void testUnknownFields() throws Exception {
Message.Builder builder =
DynamicMessage.newBuilder(TestEmptyMessage.getDescriptor());
builder.setUnknownFields(UnknownFieldSet.newBuilder()
.addField(1, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
.addField(2, UnknownFieldSet.Field.newBuilder().addFixed32(1).build())
.build());
Message message = builder.build();
assertEquals(2, message.getUnknownFields().asMap().size());
// clone() with unknown fields
Message.Builder newBuilder = builder.clone();
assertEquals(2, newBuilder.getUnknownFields().asMap().size());
// clear() with unknown fields
newBuilder.clear();
assertTrue(newBuilder.getUnknownFields().asMap().isEmpty());
// serialize/parse with unknown fields
newBuilder.mergeFrom(message.toByteString());
assertEquals(2, newBuilder.getUnknownFields().asMap().size());
}
public void testDynamicMessageSettersRejectNull() throws Exception {
Message.Builder builder =
DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.assertReflectionSettersRejectNull(builder);
}
public void testDynamicMessageExtensionAccessors() throws Exception {
// We don't need to extensively test DynamicMessage's handling of
// extensions because, frankly, it doesn't do anything special with them.
// It treats them just like any other fields.
Message.Builder builder =
DynamicMessage.newBuilder(TestAllExtensions.getDescriptor());
extensionsReflectionTester.setAllFieldsViaReflection(builder);
Message message = builder.build();
extensionsReflectionTester.assertAllFieldsSetViaReflection(message);
}
public void testDynamicMessageExtensionSettersRejectNull() throws Exception {
Message.Builder builder =
DynamicMessage.newBuilder(TestAllExtensions.getDescriptor());
extensionsReflectionTester.assertReflectionSettersRejectNull(builder);
}
public void testDynamicMessageRepeatedSetters() throws Exception {
Message.Builder builder =
DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(builder);
reflectionTester.modifyRepeatedFieldsViaReflection(builder);
Message message = builder.build();
reflectionTester.assertRepeatedFieldsModifiedViaReflection(message);
}
public void testDynamicMessageRepeatedSettersRejectNull() throws Exception {
Message.Builder builder =
DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.assertReflectionRepeatedSettersRejectNull(builder);
}
public void testDynamicMessageDefaults() throws Exception {
reflectionTester.assertClearViaReflection(
DynamicMessage.getDefaultInstance(TestAllTypes.getDescriptor()));
reflectionTester.assertClearViaReflection(
DynamicMessage.newBuilder(TestAllTypes.getDescriptor()).build());
}
public void testDynamicMessageSerializedSize() throws Exception {
TestAllTypes message = TestUtil.getAllSet();
Message.Builder dynamicBuilder =
DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(dynamicBuilder);
Message dynamicMessage = dynamicBuilder.build();
assertEquals(message.getSerializedSize(),
dynamicMessage.getSerializedSize());
}
public void testDynamicMessageSerialization() throws Exception {
Message.Builder builder =
DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(builder);
Message message = builder.build();
ByteString rawBytes = message.toByteString();
TestAllTypes message2 = TestAllTypes.parseFrom(rawBytes);
TestUtil.assertAllFieldsSet(message2);
// In fact, the serialized forms should be exactly the same, byte-for-byte.
assertEquals(TestUtil.getAllSet().toByteString(), rawBytes);
}
public void testDynamicMessageParsing() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestUtil.setAllFields(builder);
TestAllTypes message = builder.build();
ByteString rawBytes = message.toByteString();
Message message2 =
DynamicMessage.parseFrom(TestAllTypes.getDescriptor(), rawBytes);
reflectionTester.assertAllFieldsSetViaReflection(message2);
// Test Parser interface.
Message message3 = message2.getParserForType().parseFrom(rawBytes);
reflectionTester.assertAllFieldsSetViaReflection(message3);
}
public void testDynamicMessageExtensionParsing() throws Exception {
ByteString rawBytes = TestUtil.getAllExtensionsSet().toByteString();
Message message = DynamicMessage.parseFrom(
TestAllExtensions.getDescriptor(), rawBytes,
TestUtil.getExtensionRegistry());
extensionsReflectionTester.assertAllFieldsSetViaReflection(message);
// Test Parser interface.
Message message2 = message.getParserForType().parseFrom(
rawBytes, TestUtil.getExtensionRegistry());
extensionsReflectionTester.assertAllFieldsSetViaReflection(message2);
}
public void testDynamicMessagePackedSerialization() throws Exception {
Message.Builder builder =
DynamicMessage.newBuilder(TestPackedTypes.getDescriptor());
packedReflectionTester.setPackedFieldsViaReflection(builder);
Message message = builder.build();
ByteString rawBytes = message.toByteString();
TestPackedTypes message2 = TestPackedTypes.parseFrom(rawBytes);
TestUtil.assertPackedFieldsSet(message2);
// In fact, the serialized forms should be exactly the same, byte-for-byte.
assertEquals(TestUtil.getPackedSet().toByteString(), rawBytes);
}
public void testDynamicMessagePackedParsing() throws Exception {
TestPackedTypes.Builder builder = TestPackedTypes.newBuilder();
TestUtil.setPackedFields(builder);
TestPackedTypes message = builder.build();
ByteString rawBytes = message.toByteString();
Message message2 =
DynamicMessage.parseFrom(TestPackedTypes.getDescriptor(), rawBytes);
packedReflectionTester.assertPackedFieldsSetViaReflection(message2);
// Test Parser interface.
Message message3 = message2.getParserForType().parseFrom(rawBytes);
packedReflectionTester.assertPackedFieldsSetViaReflection(message3);
}
public void testDynamicMessageCopy() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestUtil.setAllFields(builder);
TestAllTypes message = builder.build();
DynamicMessage copy = DynamicMessage.newBuilder(message).build();
reflectionTester.assertAllFieldsSetViaReflection(copy);
}
public void testToBuilder() throws Exception {
DynamicMessage.Builder builder =
DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(builder);
int unknownFieldNum = 9;
long unknownFieldVal = 90;
builder.setUnknownFields(UnknownFieldSet.newBuilder()
.addField(unknownFieldNum,
UnknownFieldSet.Field.newBuilder()
.addVarint(unknownFieldVal).build())
.build());
DynamicMessage message = builder.build();
DynamicMessage derived = message.toBuilder().build();
reflectionTester.assertAllFieldsSetViaReflection(derived);
assertEquals(Arrays.asList(unknownFieldVal),
derived.getUnknownFields().getField(unknownFieldNum).getVarintList());
}
}

@ -1,49 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
/**
* A prerun for a test suite that allows running the full protocol buffer
* tests in a mode that disables the optimization for not using
* {@link RepeatedFieldBuilder} and {@link SingleFieldBuilder} until they are
* requested. This allows us to run all the tests through both code paths
* and ensures that both code paths produce identical results.
*
* @author jonp@google.com (Jon Perlow)
*/
public class ForceFieldBuildersPreRun implements Runnable {
//@Override (Java 1.6 override semantics, but we must support 1.5)
public void run() {
// GeneratedMessage.enableAlwaysUseFieldBuildersForTesting();
}
}

@ -1,961 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.test.UnittestImport;
import protobuf_unittest.EnumWithNoOuter;
import protobuf_unittest.MessageWithNoOuter;
import protobuf_unittest.MultipleFilesTestProto;
import protobuf_unittest.NestedExtension.MyNestedExtension;
import protobuf_unittest.NonNestedExtension;
import protobuf_unittest.NonNestedExtension.MessageToBeExtended;
import protobuf_unittest.NonNestedExtension.MyNonNestedExtension;
import protobuf_unittest.ServiceWithNoOuter;
import protobuf_unittest.UnittestOptimizeFor.TestOptimizedForSize;
import protobuf_unittest.UnittestOptimizeFor.TestOptionalOptimizedForSize;
import protobuf_unittest.UnittestOptimizeFor.TestRequiredOptimizedForSize;
import protobuf_unittest.UnittestProto;
import protobuf_unittest.UnittestProto.ForeignEnum;
import protobuf_unittest.UnittestProto.ForeignMessage;
import protobuf_unittest.UnittestProto.ForeignMessageOrBuilder;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypes.NestedMessage;
import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder;
import protobuf_unittest.UnittestProto.TestExtremeDefaultValues;
import protobuf_unittest.UnittestProto.TestPackedTypes;
import protobuf_unittest.UnittestProto.TestUnpackedTypes;
import junit.framework.TestCase;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Unit test for generated messages and generated code. See also
* {@link MessageTest}, which tests some generated message functionality.
*
* @author kenton@google.com Kenton Varda
*/
public class GeneratedMessageTest extends TestCase {
TestUtil.ReflectionTester reflectionTester =
new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
public void testDefaultInstance() throws Exception {
assertSame(TestAllTypes.getDefaultInstance(),
TestAllTypes.getDefaultInstance().getDefaultInstanceForType());
assertSame(TestAllTypes.getDefaultInstance(),
TestAllTypes.newBuilder().getDefaultInstanceForType());
}
public void testMessageOrBuilder() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestUtil.setAllFields(builder);
TestAllTypes message = builder.build();
TestUtil.assertAllFieldsSet(message);
}
public void testUsingBuilderMultipleTimes() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
// primitive field scalar and repeated
builder.setOptionalSfixed64(100);
builder.addRepeatedInt32(100);
// enum field scalar and repeated
builder.setOptionalImportEnum(UnittestImport.ImportEnum.IMPORT_BAR);
builder.addRepeatedImportEnum(UnittestImport.ImportEnum.IMPORT_BAR);
// proto field scalar and repeated
builder.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(1));
builder.addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(1));
TestAllTypes value1 = builder.build();
assertEquals(100, value1.getOptionalSfixed64());
assertEquals(100, value1.getRepeatedInt32(0));
assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
value1.getOptionalImportEnum());
assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
value1.getRepeatedImportEnum(0));
assertEquals(1, value1.getOptionalForeignMessage().getC());
assertEquals(1, value1.getRepeatedForeignMessage(0).getC());
// Make sure that builder didn't update previously created values
builder.setOptionalSfixed64(200);
builder.setRepeatedInt32(0, 200);
builder.setOptionalImportEnum(UnittestImport.ImportEnum.IMPORT_FOO);
builder.setRepeatedImportEnum(0, UnittestImport.ImportEnum.IMPORT_FOO);
builder.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(2));
builder.setRepeatedForeignMessage(0, ForeignMessage.newBuilder().setC(2));
TestAllTypes value2 = builder.build();
// Make sure value1 didn't change.
assertEquals(100, value1.getOptionalSfixed64());
assertEquals(100, value1.getRepeatedInt32(0));
assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
value1.getOptionalImportEnum());
assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
value1.getRepeatedImportEnum(0));
assertEquals(1, value1.getOptionalForeignMessage().getC());
assertEquals(1, value1.getRepeatedForeignMessage(0).getC());
// Make sure value2 is correct
assertEquals(200, value2.getOptionalSfixed64());
assertEquals(200, value2.getRepeatedInt32(0));
assertEquals(UnittestImport.ImportEnum.IMPORT_FOO,
value2.getOptionalImportEnum());
assertEquals(UnittestImport.ImportEnum.IMPORT_FOO,
value2.getRepeatedImportEnum(0));
assertEquals(2, value2.getOptionalForeignMessage().getC());
assertEquals(2, value2.getRepeatedForeignMessage(0).getC());
}
public void testRepeatedArraysAreImmutable() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
builder.addRepeatedInt32(100);
builder.addRepeatedImportEnum(UnittestImport.ImportEnum.IMPORT_BAR);
builder.addRepeatedForeignMessage(ForeignMessage.getDefaultInstance());
assertIsUnmodifiable(builder.getRepeatedInt32List());
assertIsUnmodifiable(builder.getRepeatedImportEnumList());
assertIsUnmodifiable(builder.getRepeatedForeignMessageList());
assertIsUnmodifiable(builder.getRepeatedFloatList());
TestAllTypes value = builder.build();
assertIsUnmodifiable(value.getRepeatedInt32List());
assertIsUnmodifiable(value.getRepeatedImportEnumList());
assertIsUnmodifiable(value.getRepeatedForeignMessageList());
assertIsUnmodifiable(value.getRepeatedFloatList());
}
public void testParsedMessagesAreImmutable() throws Exception {
TestAllTypes value = TestAllTypes.PARSER.parseFrom(
TestUtil.getAllSet().toByteString());
assertIsUnmodifiable(value.getRepeatedInt32List());
assertIsUnmodifiable(value.getRepeatedInt64List());
assertIsUnmodifiable(value.getRepeatedUint32List());
assertIsUnmodifiable(value.getRepeatedUint64List());
assertIsUnmodifiable(value.getRepeatedSint32List());
assertIsUnmodifiable(value.getRepeatedSint64List());
assertIsUnmodifiable(value.getRepeatedFixed32List());
assertIsUnmodifiable(value.getRepeatedFixed64List());
assertIsUnmodifiable(value.getRepeatedSfixed32List());
assertIsUnmodifiable(value.getRepeatedSfixed64List());
assertIsUnmodifiable(value.getRepeatedFloatList());
assertIsUnmodifiable(value.getRepeatedDoubleList());
assertIsUnmodifiable(value.getRepeatedBoolList());
assertIsUnmodifiable(value.getRepeatedStringList());
assertIsUnmodifiable(value.getRepeatedBytesList());
assertIsUnmodifiable(value.getRepeatedGroupList());
assertIsUnmodifiable(value.getRepeatedNestedMessageList());
assertIsUnmodifiable(value.getRepeatedForeignMessageList());
assertIsUnmodifiable(value.getRepeatedImportMessageList());
assertIsUnmodifiable(value.getRepeatedNestedEnumList());
assertIsUnmodifiable(value.getRepeatedForeignEnumList());
assertIsUnmodifiable(value.getRepeatedImportEnumList());
}
private void assertIsUnmodifiable(List<?> list) {
if (list == Collections.emptyList()) {
// OKAY -- Need to check this b/c EmptyList allows you to call clear.
} else {
try {
list.clear();
fail("List wasn't immutable");
} catch (UnsupportedOperationException e) {
// good
}
}
}
public void testSettersRejectNull() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
try {
builder.setOptionalString(null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
builder.setOptionalBytes(null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
builder.setOptionalNestedMessage((TestAllTypes.NestedMessage) null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
builder.setOptionalNestedMessage(
(TestAllTypes.NestedMessage.Builder) null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
builder.setOptionalNestedEnum(null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
builder.addRepeatedString(null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
builder.addRepeatedBytes(null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
builder.addRepeatedNestedMessage((TestAllTypes.NestedMessage) null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
builder.addRepeatedNestedMessage(
(TestAllTypes.NestedMessage.Builder) null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
builder.addRepeatedNestedEnum(null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
}
public void testRepeatedSetters() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestUtil.setAllFields(builder);
TestUtil.modifyRepeatedFields(builder);
TestAllTypes message = builder.build();
TestUtil.assertRepeatedFieldsModified(message);
}
public void testRepeatedSettersRejectNull() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
builder.addRepeatedString("one");
builder.addRepeatedString("two");
try {
builder.setRepeatedString(1, null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
builder.addRepeatedBytes(TestUtil.toBytes("one"));
builder.addRepeatedBytes(TestUtil.toBytes("two"));
try {
builder.setRepeatedBytes(1, null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
builder.addRepeatedNestedMessage(
TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
builder.addRepeatedNestedMessage(
TestAllTypes.NestedMessage.newBuilder().setBb(456).build());
try {
builder.setRepeatedNestedMessage(1, (TestAllTypes.NestedMessage) null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
builder.setRepeatedNestedMessage(
1, (TestAllTypes.NestedMessage.Builder) null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.FOO);
builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAR);
try {
builder.setRepeatedNestedEnum(1, null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
}
public void testRepeatedAppend() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
builder.addAllRepeatedInt32(Arrays.asList(1, 2, 3, 4));
builder.addAllRepeatedForeignEnum(Arrays.asList(ForeignEnum.FOREIGN_BAZ));
ForeignMessage foreignMessage =
ForeignMessage.newBuilder().setC(12).build();
builder.addAllRepeatedForeignMessage(Arrays.asList(foreignMessage));
TestAllTypes message = builder.build();
assertEquals(message.getRepeatedInt32List(), Arrays.asList(1, 2, 3, 4));
assertEquals(message.getRepeatedForeignEnumList(),
Arrays.asList(ForeignEnum.FOREIGN_BAZ));
assertEquals(1, message.getRepeatedForeignMessageCount());
assertEquals(12, message.getRepeatedForeignMessage(0).getC());
}
public void testRepeatedAppendRejectsNull() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
ForeignMessage foreignMessage =
ForeignMessage.newBuilder().setC(12).build();
try {
builder.addAllRepeatedForeignMessage(
Arrays.asList(foreignMessage, (ForeignMessage) null));
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
builder.addAllRepeatedForeignEnum(
Arrays.asList(ForeignEnum.FOREIGN_BAZ, null));
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
builder.addAllRepeatedString(Arrays.asList("one", null));
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
builder.addAllRepeatedBytes(Arrays.asList(TestUtil.toBytes("one"), null));
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
}
public void testSettingForeignMessageUsingBuilder() throws Exception {
TestAllTypes message = TestAllTypes.newBuilder()
// Pass builder for foreign message instance.
.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(123))
.build();
TestAllTypes expectedMessage = TestAllTypes.newBuilder()
// Create expected version passing foreign message instance explicitly.
.setOptionalForeignMessage(
ForeignMessage.newBuilder().setC(123).build())
.build();
// TODO(ngd): Upgrade to using real #equals method once implemented
assertEquals(expectedMessage.toString(), message.toString());
}
public void testSettingRepeatedForeignMessageUsingBuilder() throws Exception {
TestAllTypes message = TestAllTypes.newBuilder()
// Pass builder for foreign message instance.
.addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(456))
.build();
TestAllTypes expectedMessage = TestAllTypes.newBuilder()
// Create expected version passing foreign message instance explicitly.
.addRepeatedForeignMessage(
ForeignMessage.newBuilder().setC(456).build())
.build();
assertEquals(expectedMessage.toString(), message.toString());
}
public void testDefaults() throws Exception {
TestUtil.assertClear(TestAllTypes.getDefaultInstance());
TestUtil.assertClear(TestAllTypes.newBuilder().build());
TestExtremeDefaultValues message =
TestExtremeDefaultValues.getDefaultInstance();
assertEquals("\u1234", message.getUtf8String());
assertEquals(Double.POSITIVE_INFINITY, message.getInfDouble());
assertEquals(Double.NEGATIVE_INFINITY, message.getNegInfDouble());
assertTrue(Double.isNaN(message.getNanDouble()));
assertEquals(Float.POSITIVE_INFINITY, message.getInfFloat());
assertEquals(Float.NEGATIVE_INFINITY, message.getNegInfFloat());
assertTrue(Float.isNaN(message.getNanFloat()));
assertEquals("? ? ?? ?? ??? ??/ ??-", message.getCppTrigraph());
}
public void testClear() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestUtil.assertClear(builder);
TestUtil.setAllFields(builder);
builder.clear();
TestUtil.assertClear(builder);
}
public void testReflectionGetters() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestUtil.setAllFields(builder);
reflectionTester.assertAllFieldsSetViaReflection(builder);
TestAllTypes message = builder.build();
reflectionTester.assertAllFieldsSetViaReflection(message);
}
public void testReflectionSetters() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
reflectionTester.setAllFieldsViaReflection(builder);
TestUtil.assertAllFieldsSet(builder);
TestAllTypes message = builder.build();
TestUtil.assertAllFieldsSet(message);
}
public void testReflectionSettersRejectNull() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
reflectionTester.assertReflectionSettersRejectNull(builder);
}
public void testReflectionRepeatedSetters() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
reflectionTester.setAllFieldsViaReflection(builder);
reflectionTester.modifyRepeatedFieldsViaReflection(builder);
TestUtil.assertRepeatedFieldsModified(builder);
TestAllTypes message = builder.build();
TestUtil.assertRepeatedFieldsModified(message);
}
public void testReflectionRepeatedSettersRejectNull() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
reflectionTester.assertReflectionRepeatedSettersRejectNull(builder);
}
public void testReflectionDefaults() throws Exception {
reflectionTester.assertClearViaReflection(
TestAllTypes.getDefaultInstance());
reflectionTester.assertClearViaReflection(
TestAllTypes.newBuilder().build());
}
public void testEnumInterface() throws Exception {
assertTrue(TestAllTypes.getDefaultInstance().getDefaultNestedEnum()
instanceof ProtocolMessageEnum);
}
public void testEnumMap() throws Exception {
Internal.EnumLiteMap<ForeignEnum> map = ForeignEnum.internalGetValueMap();
for (ForeignEnum value : ForeignEnum.values()) {
assertEquals(value, map.findValueByNumber(value.getNumber()));
}
assertTrue(map.findValueByNumber(12345) == null);
}
public void testParsePackedToUnpacked() throws Exception {
TestUnpackedTypes.Builder builder = TestUnpackedTypes.newBuilder();
TestUnpackedTypes message =
builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
TestUtil.assertUnpackedFieldsSet(message);
}
public void testParseUnpackedToPacked() throws Exception {
TestPackedTypes.Builder builder = TestPackedTypes.newBuilder();
TestPackedTypes message =
builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
TestUtil.assertPackedFieldsSet(message);
}
// =================================================================
// Extensions.
TestUtil.ReflectionTester extensionsReflectionTester =
new TestUtil.ReflectionTester(TestAllExtensions.getDescriptor(),
TestUtil.getExtensionRegistry());
public void testExtensionMessageOrBuilder() throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
TestUtil.setAllExtensions(builder);
TestAllExtensions message = builder.build();
TestUtil.assertAllExtensionsSet(message);
}
public void testExtensionRepeatedSetters() throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
TestUtil.setAllExtensions(builder);
TestUtil.modifyRepeatedExtensions(builder);
TestAllExtensions message = builder.build();
TestUtil.assertRepeatedExtensionsModified(message);
}
public void testExtensionDefaults() throws Exception {
TestUtil.assertExtensionsClear(TestAllExtensions.getDefaultInstance());
TestUtil.assertExtensionsClear(TestAllExtensions.newBuilder().build());
}
public void testExtensionReflectionGetters() throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
TestUtil.setAllExtensions(builder);
extensionsReflectionTester.assertAllFieldsSetViaReflection(builder);
TestAllExtensions message = builder.build();
extensionsReflectionTester.assertAllFieldsSetViaReflection(message);
}
public void testExtensionReflectionSetters() throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
extensionsReflectionTester.setAllFieldsViaReflection(builder);
TestUtil.assertAllExtensionsSet(builder);
TestAllExtensions message = builder.build();
TestUtil.assertAllExtensionsSet(message);
}
public void testExtensionReflectionSettersRejectNull() throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
extensionsReflectionTester.assertReflectionSettersRejectNull(builder);
}
public void testExtensionReflectionRepeatedSetters() throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
extensionsReflectionTester.setAllFieldsViaReflection(builder);
extensionsReflectionTester.modifyRepeatedFieldsViaReflection(builder);
TestUtil.assertRepeatedExtensionsModified(builder);
TestAllExtensions message = builder.build();
TestUtil.assertRepeatedExtensionsModified(message);
}
public void testExtensionReflectionRepeatedSettersRejectNull()
throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
extensionsReflectionTester.assertReflectionRepeatedSettersRejectNull(
builder);
}
public void testExtensionReflectionDefaults() throws Exception {
extensionsReflectionTester.assertClearViaReflection(
TestAllExtensions.getDefaultInstance());
extensionsReflectionTester.assertClearViaReflection(
TestAllExtensions.newBuilder().build());
}
public void testClearExtension() throws Exception {
// clearExtension() is not actually used in TestUtil, so try it manually.
assertFalse(
TestAllExtensions.newBuilder()
.setExtension(UnittestProto.optionalInt32Extension, 1)
.clearExtension(UnittestProto.optionalInt32Extension)
.hasExtension(UnittestProto.optionalInt32Extension));
assertEquals(0,
TestAllExtensions.newBuilder()
.addExtension(UnittestProto.repeatedInt32Extension, 1)
.clearExtension(UnittestProto.repeatedInt32Extension)
.getExtensionCount(UnittestProto.repeatedInt32Extension));
}
public void testExtensionCopy() throws Exception {
TestAllExtensions original = TestUtil.getAllExtensionsSet();
TestAllExtensions copy = TestAllExtensions.newBuilder(original).build();
TestUtil.assertAllExtensionsSet(copy);
}
public void testExtensionMergeFrom() throws Exception {
TestAllExtensions original =
TestAllExtensions.newBuilder()
.setExtension(UnittestProto.optionalInt32Extension, 1).build();
TestAllExtensions merged =
TestAllExtensions.newBuilder().mergeFrom(original).build();
assertTrue(merged.hasExtension(UnittestProto.optionalInt32Extension));
assertEquals(
1, (int) merged.getExtension(UnittestProto.optionalInt32Extension));
}
// =================================================================
// multiple_files_test
public void testMultipleFilesOption() throws Exception {
// We mostly just want to check that things compile.
MessageWithNoOuter message =
MessageWithNoOuter.newBuilder()
.setNested(MessageWithNoOuter.NestedMessage.newBuilder().setI(1))
.addForeign(TestAllTypes.newBuilder().setOptionalInt32(1))
.setNestedEnum(MessageWithNoOuter.NestedEnum.BAZ)
.setForeignEnum(EnumWithNoOuter.BAR)
.build();
assertEquals(message, MessageWithNoOuter.parseFrom(message.toByteString()));
assertEquals(MultipleFilesTestProto.getDescriptor(),
MessageWithNoOuter.getDescriptor().getFile());
Descriptors.FieldDescriptor field =
MessageWithNoOuter.getDescriptor().findFieldByName("foreign_enum");
assertEquals(EnumWithNoOuter.BAR.getValueDescriptor(),
message.getField(field));
assertEquals(MultipleFilesTestProto.getDescriptor(),
ServiceWithNoOuter.getDescriptor().getFile());
assertFalse(
TestAllExtensions.getDefaultInstance().hasExtension(
MultipleFilesTestProto.extensionWithOuter));
}
public void testOptionalFieldWithRequiredSubfieldsOptimizedForSize()
throws Exception {
TestOptionalOptimizedForSize message =
TestOptionalOptimizedForSize.getDefaultInstance();
assertTrue(message.isInitialized());
message = TestOptionalOptimizedForSize.newBuilder().setO(
TestRequiredOptimizedForSize.newBuilder().buildPartial()
).buildPartial();
assertFalse(message.isInitialized());
message = TestOptionalOptimizedForSize.newBuilder().setO(
TestRequiredOptimizedForSize.newBuilder().setX(5).buildPartial()
).buildPartial();
assertTrue(message.isInitialized());
}
public void testUninitializedExtensionInOptimizedForSize()
throws Exception {
TestOptimizedForSize.Builder builder = TestOptimizedForSize.newBuilder();
builder.setExtension(TestOptimizedForSize.testExtension2,
TestRequiredOptimizedForSize.newBuilder().buildPartial());
assertFalse(builder.isInitialized());
assertFalse(builder.buildPartial().isInitialized());
builder = TestOptimizedForSize.newBuilder();
builder.setExtension(TestOptimizedForSize.testExtension2,
TestRequiredOptimizedForSize.newBuilder().setX(10).buildPartial());
assertTrue(builder.isInitialized());
assertTrue(builder.buildPartial().isInitialized());
}
public void testToBuilder() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestUtil.setAllFields(builder);
TestAllTypes message = builder.build();
TestUtil.assertAllFieldsSet(message);
TestUtil.assertAllFieldsSet(message.toBuilder().build());
}
public void testFieldConstantValues() throws Exception {
assertEquals(TestAllTypes.NestedMessage.BB_FIELD_NUMBER, 1);
assertEquals(TestAllTypes.OPTIONAL_INT32_FIELD_NUMBER, 1);
assertEquals(TestAllTypes.OPTIONALGROUP_FIELD_NUMBER, 16);
assertEquals(TestAllTypes.OPTIONAL_NESTED_MESSAGE_FIELD_NUMBER, 18);
assertEquals(TestAllTypes.OPTIONAL_NESTED_ENUM_FIELD_NUMBER, 21);
assertEquals(TestAllTypes.REPEATED_INT32_FIELD_NUMBER, 31);
assertEquals(TestAllTypes.REPEATEDGROUP_FIELD_NUMBER, 46);
assertEquals(TestAllTypes.REPEATED_NESTED_MESSAGE_FIELD_NUMBER, 48);
assertEquals(TestAllTypes.REPEATED_NESTED_ENUM_FIELD_NUMBER, 51);
}
public void testExtensionConstantValues() throws Exception {
assertEquals(UnittestProto.TestRequired.SINGLE_FIELD_NUMBER, 1000);
assertEquals(UnittestProto.TestRequired.MULTI_FIELD_NUMBER, 1001);
assertEquals(UnittestProto.OPTIONAL_INT32_EXTENSION_FIELD_NUMBER, 1);
assertEquals(UnittestProto.OPTIONALGROUP_EXTENSION_FIELD_NUMBER, 16);
assertEquals(
UnittestProto.OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 18);
assertEquals(UnittestProto.OPTIONAL_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 21);
assertEquals(UnittestProto.REPEATED_INT32_EXTENSION_FIELD_NUMBER, 31);
assertEquals(UnittestProto.REPEATEDGROUP_EXTENSION_FIELD_NUMBER, 46);
assertEquals(
UnittestProto.REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 48);
assertEquals(UnittestProto.REPEATED_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 51);
}
public void testRecursiveMessageDefaultInstance() throws Exception {
UnittestProto.TestRecursiveMessage message =
UnittestProto.TestRecursiveMessage.getDefaultInstance();
assertTrue(message != null);
assertTrue(message.getA() != null);
assertTrue(message.getA() == message);
}
public void testSerialize() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestUtil.setAllFields(builder);
TestAllTypes expected = builder.build();
ObjectOutputStream out = new ObjectOutputStream(baos);
try {
out.writeObject(expected);
} finally {
out.close();
}
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bais);
TestAllTypes actual = (TestAllTypes) in.readObject();
assertEquals(expected, actual);
}
public void testSerializePartial() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestAllTypes expected = builder.buildPartial();
ObjectOutputStream out = new ObjectOutputStream(baos);
try {
out.writeObject(expected);
} finally {
out.close();
}
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bais);
TestAllTypes actual = (TestAllTypes) in.readObject();
assertEquals(expected, actual);
}
public void testEnumValues() {
assertEquals(
TestAllTypes.NestedEnum.BAR.getNumber(),
TestAllTypes.NestedEnum.BAR_VALUE);
assertEquals(
TestAllTypes.NestedEnum.BAZ.getNumber(),
TestAllTypes.NestedEnum.BAZ_VALUE);
assertEquals(
TestAllTypes.NestedEnum.FOO.getNumber(),
TestAllTypes.NestedEnum.FOO_VALUE);
}
public void testNonNestedExtensionInitialization() {
assertTrue(NonNestedExtension.nonNestedExtension
.getMessageDefaultInstance() instanceof MyNonNestedExtension);
assertEquals("nonNestedExtension",
NonNestedExtension.nonNestedExtension.getDescriptor().getName());
}
public void testNestedExtensionInitialization() {
assertTrue(MyNestedExtension.recursiveExtension.getMessageDefaultInstance()
instanceof MessageToBeExtended);
assertEquals("recursiveExtension",
MyNestedExtension.recursiveExtension.getDescriptor().getName());
}
public void testBaseMessageOrBuilder() {
// Mostly just makes sure the base interface exists and has some methods.
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestAllTypes message = builder.buildPartial();
TestAllTypesOrBuilder builderAsInterface = (TestAllTypesOrBuilder) builder;
TestAllTypesOrBuilder messageAsInterface = (TestAllTypesOrBuilder) message;
assertEquals(
messageAsInterface.getDefaultBool(),
messageAsInterface.getDefaultBool());
assertEquals(
messageAsInterface.getOptionalDouble(),
messageAsInterface.getOptionalDouble());
}
public void testMessageOrBuilderGetters() {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
// single fields
assertSame(ForeignMessage.getDefaultInstance(),
builder.getOptionalForeignMessageOrBuilder());
ForeignMessage.Builder subBuilder =
builder.getOptionalForeignMessageBuilder();
assertSame(subBuilder, builder.getOptionalForeignMessageOrBuilder());
// repeated fields
ForeignMessage m0 = ForeignMessage.newBuilder().buildPartial();
ForeignMessage m1 = ForeignMessage.newBuilder().buildPartial();
ForeignMessage m2 = ForeignMessage.newBuilder().buildPartial();
builder.addRepeatedForeignMessage(m0);
builder.addRepeatedForeignMessage(m1);
builder.addRepeatedForeignMessage(m2);
assertSame(m0, builder.getRepeatedForeignMessageOrBuilder(0));
assertSame(m1, builder.getRepeatedForeignMessageOrBuilder(1));
assertSame(m2, builder.getRepeatedForeignMessageOrBuilder(2));
ForeignMessage.Builder b0 = builder.getRepeatedForeignMessageBuilder(0);
ForeignMessage.Builder b1 = builder.getRepeatedForeignMessageBuilder(1);
assertSame(b0, builder.getRepeatedForeignMessageOrBuilder(0));
assertSame(b1, builder.getRepeatedForeignMessageOrBuilder(1));
assertSame(m2, builder.getRepeatedForeignMessageOrBuilder(2));
List<? extends ForeignMessageOrBuilder> messageOrBuilderList =
builder.getRepeatedForeignMessageOrBuilderList();
assertSame(b0, messageOrBuilderList.get(0));
assertSame(b1, messageOrBuilderList.get(1));
assertSame(m2, messageOrBuilderList.get(2));
}
public void testGetFieldBuilder() {
Descriptor descriptor = TestAllTypes.getDescriptor();
FieldDescriptor fieldDescriptor =
descriptor.findFieldByName("optional_nested_message");
FieldDescriptor foreignFieldDescriptor =
descriptor.findFieldByName("optional_foreign_message");
FieldDescriptor importFieldDescriptor =
descriptor.findFieldByName("optional_import_message");
// Mutate the message with new field builder
// Mutate nested message
TestAllTypes.Builder builder1 = TestAllTypes.newBuilder();
Message.Builder fieldBuilder1 = builder1.newBuilderForField(fieldDescriptor)
.mergeFrom((Message) builder1.getField(fieldDescriptor));
FieldDescriptor subFieldDescriptor1 =
fieldBuilder1.getDescriptorForType().findFieldByName("bb");
fieldBuilder1.setField(subFieldDescriptor1, 1);
builder1.setField(fieldDescriptor, fieldBuilder1.build());
// Mutate foreign message
Message.Builder foreignFieldBuilder1 = builder1.newBuilderForField(
foreignFieldDescriptor)
.mergeFrom((Message) builder1.getField(foreignFieldDescriptor));
FieldDescriptor subForeignFieldDescriptor1 =
foreignFieldBuilder1.getDescriptorForType().findFieldByName("c");
foreignFieldBuilder1.setField(subForeignFieldDescriptor1, 2);
builder1.setField(foreignFieldDescriptor, foreignFieldBuilder1.build());
// Mutate import message
Message.Builder importFieldBuilder1 = builder1.newBuilderForField(
importFieldDescriptor)
.mergeFrom((Message) builder1.getField(importFieldDescriptor));
FieldDescriptor subImportFieldDescriptor1 =
importFieldBuilder1.getDescriptorForType().findFieldByName("d");
importFieldBuilder1.setField(subImportFieldDescriptor1, 3);
builder1.setField(importFieldDescriptor, importFieldBuilder1.build());
Message newMessage1 = builder1.build();
// Mutate the message with existing field builder
// Mutate nested message
TestAllTypes.Builder builder2 = TestAllTypes.newBuilder();
Message.Builder fieldBuilder2 = builder2.getFieldBuilder(fieldDescriptor);
FieldDescriptor subFieldDescriptor2 =
fieldBuilder2.getDescriptorForType().findFieldByName("bb");
fieldBuilder2.setField(subFieldDescriptor2, 1);
builder2.setField(fieldDescriptor, fieldBuilder2.build());
// Mutate foreign message
Message.Builder foreignFieldBuilder2 = builder2.newBuilderForField(
foreignFieldDescriptor)
.mergeFrom((Message) builder2.getField(foreignFieldDescriptor));
FieldDescriptor subForeignFieldDescriptor2 =
foreignFieldBuilder2.getDescriptorForType().findFieldByName("c");
foreignFieldBuilder2.setField(subForeignFieldDescriptor2, 2);
builder2.setField(foreignFieldDescriptor, foreignFieldBuilder2.build());
// Mutate import message
Message.Builder importFieldBuilder2 = builder2.newBuilderForField(
importFieldDescriptor)
.mergeFrom((Message) builder2.getField(importFieldDescriptor));
FieldDescriptor subImportFieldDescriptor2 =
importFieldBuilder2.getDescriptorForType().findFieldByName("d");
importFieldBuilder2.setField(subImportFieldDescriptor2, 3);
builder2.setField(importFieldDescriptor, importFieldBuilder2.build());
Message newMessage2 = builder2.build();
// These two messages should be equal.
assertEquals(newMessage1, newMessage2);
}
public void testGetFieldBuilderWithInitializedValue() {
Descriptor descriptor = TestAllTypes.getDescriptor();
FieldDescriptor fieldDescriptor =
descriptor.findFieldByName("optional_nested_message");
// Before setting field, builder is initialized by default value.
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
NestedMessage.Builder fieldBuilder =
(NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor);
assertEquals(0, fieldBuilder.getBb());
// Setting field value with new field builder instance.
builder = TestAllTypes.newBuilder();
NestedMessage.Builder newFieldBuilder =
builder.getOptionalNestedMessageBuilder();
newFieldBuilder.setBb(2);
// Then get the field builder instance by getFieldBuilder().
fieldBuilder =
(NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor);
// It should contain new value.
assertEquals(2, fieldBuilder.getBb());
// These two builder should be equal.
assertSame(fieldBuilder, newFieldBuilder);
}
public void testGetFieldBuilderNotSupportedException() {
Descriptor descriptor = TestAllTypes.getDescriptor();
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
try {
builder.getFieldBuilder(descriptor.findFieldByName("optional_int32"));
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
}
try {
builder.getFieldBuilder(
descriptor.findFieldByName("optional_nested_enum"));
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
}
try {
builder.getFieldBuilder(descriptor.findFieldByName("repeated_int32"));
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
}
try {
builder.getFieldBuilder(
descriptor.findFieldByName("repeated_nested_enum"));
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
}
try {
builder.getFieldBuilder(
descriptor.findFieldByName("repeated_nested_message"));
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
}
}
}

@ -1,163 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.List;
/**
* Tests for {@link LazyStringArrayList}.
*
* @author jonp@google.com (Jon Perlow)
*/
public class LazyStringArrayListTest extends TestCase {
private static String STRING_A = "A";
private static String STRING_B = "B";
private static String STRING_C = "C";
private static ByteString BYTE_STRING_A = ByteString.copyFromUtf8("A");
private static ByteString BYTE_STRING_B = ByteString.copyFromUtf8("B");
private static ByteString BYTE_STRING_C = ByteString.copyFromUtf8("C");
public void testJustStrings() {
LazyStringArrayList list = new LazyStringArrayList();
list.add(STRING_A);
list.add(STRING_B);
list.add(STRING_C);
assertEquals(3, list.size());
assertSame(STRING_A, list.get(0));
assertSame(STRING_B, list.get(1));
assertSame(STRING_C, list.get(2));
list.set(1, STRING_C);
assertSame(STRING_C, list.get(1));
list.remove(1);
assertSame(STRING_A, list.get(0));
assertSame(STRING_C, list.get(1));
}
public void testJustByteString() {
LazyStringArrayList list = new LazyStringArrayList();
list.add(BYTE_STRING_A);
list.add(BYTE_STRING_B);
list.add(BYTE_STRING_C);
assertEquals(3, list.size());
assertSame(BYTE_STRING_A, list.getByteString(0));
assertSame(BYTE_STRING_B, list.getByteString(1));
assertSame(BYTE_STRING_C, list.getByteString(2));
list.remove(1);
assertSame(BYTE_STRING_A, list.getByteString(0));
assertSame(BYTE_STRING_C, list.getByteString(1));
}
public void testConversionBackAndForth() {
LazyStringArrayList list = new LazyStringArrayList();
list.add(STRING_A);
list.add(BYTE_STRING_B);
list.add(BYTE_STRING_C);
// String a should be the same because it was originally a string
assertSame(STRING_A, list.get(0));
// String b and c should be different because the string has to be computed
// from the ByteString
String bPrime = list.get(1);
assertNotSame(STRING_B, bPrime);
assertEquals(STRING_B, bPrime);
String cPrime = list.get(2);
assertNotSame(STRING_C, cPrime);
assertEquals(STRING_C, cPrime);
// String c and c should stay the same once cached.
assertSame(bPrime, list.get(1));
assertSame(cPrime, list.get(2));
// ByteString needs to be computed from string for both a and b
ByteString aPrimeByteString = list.getByteString(0);
assertEquals(BYTE_STRING_A, aPrimeByteString);
ByteString bPrimeByteString = list.getByteString(1);
assertNotSame(BYTE_STRING_B, bPrimeByteString);
assertEquals(BYTE_STRING_B, list.getByteString(1));
// Once cached, ByteString should stay cached.
assertSame(aPrimeByteString, list.getByteString(0));
assertSame(bPrimeByteString, list.getByteString(1));
}
public void testCopyConstructorCopiesByReference() {
LazyStringArrayList list1 = new LazyStringArrayList();
list1.add(STRING_A);
list1.add(BYTE_STRING_B);
list1.add(BYTE_STRING_C);
LazyStringArrayList list2 = new LazyStringArrayList(list1);
assertEquals(3, list2.size());
assertSame(STRING_A, list2.get(0));
assertSame(BYTE_STRING_B, list2.getByteString(1));
assertSame(BYTE_STRING_C, list2.getByteString(2));
}
public void testListCopyConstructor() {
List<String> list1 = new ArrayList<String>();
list1.add(STRING_A);
list1.add(STRING_B);
list1.add(STRING_C);
LazyStringArrayList list2 = new LazyStringArrayList(list1);
assertEquals(3, list2.size());
assertSame(STRING_A, list2.get(0));
assertSame(STRING_B, list2.get(1));
assertSame(STRING_C, list2.get(2));
}
public void testAddAllCopiesByReferenceIfPossible() {
LazyStringArrayList list1 = new LazyStringArrayList();
list1.add(STRING_A);
list1.add(BYTE_STRING_B);
list1.add(BYTE_STRING_C);
LazyStringArrayList list2 = new LazyStringArrayList();
list2.addAll(list1);
assertEquals(3, list2.size());
assertSame(STRING_A, list2.get(0));
assertSame(BYTE_STRING_B, list2.getByteString(1));
assertSame(BYTE_STRING_C, list2.getByteString(2));
}
}

@ -1,108 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import protobuf_unittest.UnittestProto;
import junit.framework.TestCase;
import java.io.IOException;
/**
* Tests to make sure the lazy conversion of UTF8-encoded byte arrays to
* strings works correctly.
*
* @author jonp@google.com (Jon Perlow)
*/
public class LazyStringEndToEndTest extends TestCase {
private static ByteString TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8 =
ByteString.copyFrom(new byte[] {
114, 4, -1, 0, -1, 0, -30, 2, 4, -1,
0, -1, 0, -30, 2, 4, -1, 0, -1, 0, });
private ByteString encodedTestAllTypes;
@Override
protected void setUp() throws Exception {
super.setUp();
this.encodedTestAllTypes = UnittestProto.TestAllTypes.newBuilder()
.setOptionalString("foo")
.addRepeatedString("bar")
.addRepeatedString("baz")
.build()
.toByteString();
}
/**
* Tests that an invalid UTF8 string will roundtrip through a parse
* and serialization.
*/
public void testParseAndSerialize() throws InvalidProtocolBufferException {
UnittestProto.TestAllTypes tV2 = UnittestProto.TestAllTypes.parseFrom(
TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8);
ByteString bytes = tV2.toByteString();
assertEquals(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8, bytes);
tV2.getOptionalString();
bytes = tV2.toByteString();
assertEquals(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8, bytes);
}
public void testParseAndWrite() throws IOException {
UnittestProto.TestAllTypes tV2 = UnittestProto.TestAllTypes.parseFrom(
TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8);
byte[] sink = new byte[TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8.size()];
CodedOutputStream outputStream = CodedOutputStream.newInstance(sink);
tV2.writeTo(outputStream);
outputStream.flush();
assertEquals(
TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8,
ByteString.copyFrom(sink));
}
public void testNoStringCachingIfOnlyBytesAccessed() throws Exception {
UnittestProto.TestAllTypes proto =
UnittestProto.TestAllTypes.parseFrom(encodedTestAllTypes);
ByteString optional = proto.getOptionalStringBytes();
assertSame(optional, proto.getOptionalStringBytes());
assertSame(optional, proto.toBuilder().getOptionalStringBytes());
ByteString repeated0 = proto.getRepeatedStringBytes(0);
ByteString repeated1 = proto.getRepeatedStringBytes(1);
assertSame(repeated0, proto.getRepeatedStringBytes(0));
assertSame(repeated1, proto.getRepeatedStringBytes(1));
assertSame(repeated0, proto.toBuilder().getRepeatedStringBytes(0));
assertSame(repeated1, proto.toBuilder().getRepeatedStringBytes(1));
}
}

@ -1,344 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import junit.framework.TestCase;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Arrays;
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}.
*
* @author carlanton@google.com (Carl Haverl)
*/
public class LiteralByteStringTest extends TestCase {
protected static final String UTF_8 = "UTF-8";
protected String classUnderTest;
protected byte[] referenceBytes;
protected ByteString stringUnderTest;
protected int expectedHashCode;
@Override
protected void setUp() throws Exception {
classUnderTest = "LiteralByteString";
referenceBytes = ByteStringTest.getTestBytes(1234, 11337766L);
stringUnderTest = ByteString.copyFrom(referenceBytes);
expectedHashCode = 331161852;
}
protected String getActualClassName(Object object) {
String actualClassName = object.getClass().getName();
actualClassName = actualClassName.substring(actualClassName.lastIndexOf('.') + 1);
return actualClassName;
}
public void testByteAt() {
boolean stillEqual = true;
for (int i = 0; stillEqual && i < referenceBytes.length; ++i) {
stillEqual = (referenceBytes[i] == stringUnderTest.byteAt(i));
}
assertTrue(classUnderTest + " must capture the right bytes", stillEqual);
}
public void testByteIterator() {
boolean stillEqual = true;
ByteString.ByteIterator iter = stringUnderTest.iterator();
for (int i = 0; stillEqual && i < referenceBytes.length; ++i) {
stillEqual = (iter.hasNext() && referenceBytes[i] == iter.nextByte());
}
assertTrue(classUnderTest + " must capture the right bytes", stillEqual);
assertFalse(classUnderTest + " must have exhausted the iterator", iter.hasNext());
try {
iter.nextByte();
fail("Should have thrown an exception.");
} catch (NoSuchElementException e) {
// This is success
}
}
public void testByteIterable() {
boolean stillEqual = true;
int j = 0;
for (byte quantum : stringUnderTest) {
stillEqual = (referenceBytes[j] == quantum);
++j;
}
assertTrue(classUnderTest + " must capture the right bytes as Bytes", stillEqual);
assertEquals(classUnderTest + " iterable character count", referenceBytes.length, j);
}
public void testSize() {
assertEquals(classUnderTest + " must have the expected size", referenceBytes.length,
stringUnderTest.size());
}
public void testCopyTo_ByteArrayOffsetLength() {
int destinationOffset = 50;
int length = 100;
byte[] destination = new byte[destinationOffset + length];
int sourceOffset = 213;
stringUnderTest.copyTo(destination, sourceOffset, destinationOffset, length);
boolean stillEqual = true;
for (int i = 0; stillEqual && i < length; ++i) {
stillEqual = referenceBytes[i + sourceOffset] == destination[i + destinationOffset];
}
assertTrue(classUnderTest + ".copyTo(4 arg) must give the expected bytes", stillEqual);
}
public void testCopyTo_ByteArrayOffsetLengthErrors() {
int destinationOffset = 50;
int length = 100;
byte[] destination = new byte[destinationOffset + length];
try {
// Copy one too many bytes
stringUnderTest.copyTo(destination, stringUnderTest.size() + 1 - length,
destinationOffset, length);
fail("Should have thrown an exception when copying too many bytes of a "
+ classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
try {
// Copy with illegal negative sourceOffset
stringUnderTest.copyTo(destination, -1, destinationOffset, length);
fail("Should have thrown an exception when given a negative sourceOffset in "
+ classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
try {
// Copy with illegal negative destinationOffset
stringUnderTest.copyTo(destination, 0, -1, length);
fail("Should have thrown an exception when given a negative destinationOffset in "
+ classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
try {
// Copy with illegal negative size
stringUnderTest.copyTo(destination, 0, 0, -1);
fail("Should have thrown an exception when given a negative size in "
+ classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
try {
// Copy with illegal too-large sourceOffset
stringUnderTest.copyTo(destination, 2 * stringUnderTest.size(), 0, length);
fail("Should have thrown an exception when the destinationOffset is too large in "
+ classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
try {
// Copy with illegal too-large destinationOffset
stringUnderTest.copyTo(destination, 0, 2 * destination.length, length);
fail("Should have thrown an exception when the destinationOffset is too large in "
+ classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
}
public void testCopyTo_ByteBuffer() {
ByteBuffer myBuffer = ByteBuffer.allocate(referenceBytes.length);
stringUnderTest.copyTo(myBuffer);
assertTrue(classUnderTest + ".copyTo(ByteBuffer) must give back the same bytes",
Arrays.equals(referenceBytes, myBuffer.array()));
}
public void testAsReadOnlyByteBuffer() {
ByteBuffer byteBuffer = stringUnderTest.asReadOnlyByteBuffer();
byte[] roundTripBytes = new byte[referenceBytes.length];
assertTrue(byteBuffer.remaining() == referenceBytes.length);
assertTrue(byteBuffer.isReadOnly());
byteBuffer.get(roundTripBytes);
assertTrue(classUnderTest + ".asReadOnlyByteBuffer() must give back the same bytes",
Arrays.equals(referenceBytes, roundTripBytes));
}
public void testAsReadOnlyByteBufferList() {
List<ByteBuffer> byteBuffers = stringUnderTest.asReadOnlyByteBufferList();
int bytesSeen = 0;
byte[] roundTripBytes = new byte[referenceBytes.length];
for (ByteBuffer byteBuffer : byteBuffers) {
int thisLength = byteBuffer.remaining();
assertTrue(byteBuffer.isReadOnly());
assertTrue(bytesSeen + thisLength <= referenceBytes.length);
byteBuffer.get(roundTripBytes, bytesSeen, thisLength);
bytesSeen += thisLength;
}
assertTrue(bytesSeen == referenceBytes.length);
assertTrue(classUnderTest + ".asReadOnlyByteBufferTest() must give back the same bytes",
Arrays.equals(referenceBytes, roundTripBytes));
}
public void testToByteArray() {
byte[] roundTripBytes = stringUnderTest.toByteArray();
assertTrue(classUnderTest + ".toByteArray() must give back the same bytes",
Arrays.equals(referenceBytes, roundTripBytes));
}
public void testWriteTo() throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
stringUnderTest.writeTo(bos);
byte[] roundTripBytes = bos.toByteArray();
assertTrue(classUnderTest + ".writeTo() must give back the same bytes",
Arrays.equals(referenceBytes, roundTripBytes));
}
public void testWriteTo_mutating() 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;
}
}
@Override
public void write(int b) {
// Purposefully left blank.
}
};
stringUnderTest.writeTo(os);
byte[] newBytes = stringUnderTest.toByteArray();
assertTrue(classUnderTest + ".writeTo() must not grant access to underlying array",
Arrays.equals(referenceBytes, newBytes));
}
public void testNewOutput() throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ByteString.Output output = ByteString.newOutput();
stringUnderTest.writeTo(output);
assertEquals("Output Size returns correct result",
output.size(), stringUnderTest.size());
output.writeTo(bos);
assertTrue("Output.writeTo() must give back the same bytes",
Arrays.equals(referenceBytes, bos.toByteArray()));
// write the output stream to itself! This should cause it to double
output.writeTo(output);
assertEquals("Writing an output stream to itself is successful",
stringUnderTest.concat(stringUnderTest), output.toByteString());
output.reset();
assertEquals("Output.reset() resets the output", 0, output.size());
assertEquals("Output.reset() resets the output",
ByteString.EMPTY, output.toByteString());
}
public void testHashCode() {
int hash = stringUnderTest.hashCode();
assertEquals(classUnderTest + " must have expected hashCode", expectedHashCode, hash);
}
public void testNewInput() throws IOException {
InputStream input = stringUnderTest.newInput();
assertEquals("InputStream.available() returns correct value",
stringUnderTest.size(), input.available());
boolean stillEqual = true;
for (byte referenceByte : referenceBytes) {
int expectedInt = (referenceByte & 0xFF);
stillEqual = (expectedInt == input.read());
}
assertEquals("InputStream.available() returns correct value",
0, input.available());
assertTrue(classUnderTest + " must give the same bytes from the InputStream", stillEqual);
assertEquals(classUnderTest + " InputStream must now be exhausted", -1, input.read());
}
public void testNewInput_skip() throws IOException {
InputStream input = stringUnderTest.newInput();
int stringSize = stringUnderTest.size();
int nearEndIndex = stringSize * 2 / 3;
long skipped1 = input.skip(nearEndIndex);
assertEquals("InputStream.skip()", skipped1, nearEndIndex);
assertEquals("InputStream.available()",
stringSize - skipped1, input.available());
assertTrue("InputStream.mark() is available", input.markSupported());
input.mark(0);
assertEquals("InputStream.skip(), read()",
stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
assertEquals("InputStream.available()",
stringSize - skipped1 - 1, input.available());
long skipped2 = input.skip(stringSize);
assertEquals("InputStream.skip() incomplete",
skipped2, stringSize - skipped1 - 1);
assertEquals("InputStream.skip(), no more input", 0, input.available());
assertEquals("InputStream.skip(), no more input", -1, input.read());
input.reset();
assertEquals("InputStream.reset() succeeded",
stringSize - skipped1, input.available());
assertEquals("InputStream.reset(), read()",
stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
}
public void testNewCodedInput() throws IOException {
CodedInputStream cis = stringUnderTest.newCodedInput();
byte[] roundTripBytes = cis.readRawBytes(referenceBytes.length);
assertTrue(classUnderTest + " must give the same bytes back from the CodedInputStream",
Arrays.equals(referenceBytes, roundTripBytes));
assertTrue(classUnderTest + " CodedInputStream must now be exhausted", cis.isAtEnd());
}
/**
* Make sure we keep things simple when concatenating with empty. See also
* {@link ByteStringTest#testConcat_empty()}.
*/
public void testConcat_empty() {
assertSame(classUnderTest + " concatenated with empty must give " + classUnderTest,
stringUnderTest.concat(ByteString.EMPTY), stringUnderTest);
assertSame("empty concatenated with " + classUnderTest + " must give " + classUnderTest,
ByteString.EMPTY.concat(stringUnderTest), stringUnderTest);
}
}

@ -1,354 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestRequired;
import protobuf_unittest.UnittestProto.TestRequiredForeign;
import protobuf_unittest.UnittestProto.ForeignMessage;
import junit.framework.TestCase;
import java.util.List;
/**
* Misc. unit tests for message operations that apply to both generated
* and dynamic messages.
*
* @author kenton@google.com Kenton Varda
*/
public class MessageTest extends TestCase {
// =================================================================
// Message-merging tests.
static final TestAllTypes MERGE_SOURCE =
TestAllTypes.newBuilder()
.setOptionalInt32(1)
.setOptionalString("foo")
.setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
.addRepeatedString("bar")
.build();
static final TestAllTypes MERGE_DEST =
TestAllTypes.newBuilder()
.setOptionalInt64(2)
.setOptionalString("baz")
.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build())
.addRepeatedString("qux")
.build();
static final String MERGE_RESULT_TEXT =
"optional_int32: 1\n" +
"optional_int64: 2\n" +
"optional_string: \"foo\"\n" +
"optional_foreign_message {\n" +
" c: 3\n" +
"}\n" +
"repeated_string: \"qux\"\n" +
"repeated_string: \"bar\"\n";
public void testMergeFrom() throws Exception {
TestAllTypes result =
TestAllTypes.newBuilder(MERGE_DEST)
.mergeFrom(MERGE_SOURCE).build();
assertEquals(MERGE_RESULT_TEXT, result.toString());
}
/**
* Test merging a DynamicMessage into a GeneratedMessage. As long as they
* have the same descriptor, this should work, but it is an entirely different
* code path.
*/
public void testMergeFromDynamic() throws Exception {
TestAllTypes result =
TestAllTypes.newBuilder(MERGE_DEST)
.mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
.build();
assertEquals(MERGE_RESULT_TEXT, result.toString());
}
/** Test merging two DynamicMessages. */
public void testDynamicMergeFrom() throws Exception {
DynamicMessage result =
DynamicMessage.newBuilder(MERGE_DEST)
.mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
.build();
assertEquals(MERGE_RESULT_TEXT, result.toString());
}
// =================================================================
// Required-field-related tests.
private static final TestRequired TEST_REQUIRED_UNINITIALIZED =
TestRequired.getDefaultInstance();
private static final TestRequired TEST_REQUIRED_INITIALIZED =
TestRequired.newBuilder().setA(1).setB(2).setC(3).build();
public void testRequired() throws Exception {
TestRequired.Builder builder = TestRequired.newBuilder();
assertFalse(builder.isInitialized());
builder.setA(1);
assertFalse(builder.isInitialized());
builder.setB(1);
assertFalse(builder.isInitialized());
builder.setC(1);
assertTrue(builder.isInitialized());
}
public void testRequiredForeign() throws Exception {
TestRequiredForeign.Builder builder = TestRequiredForeign.newBuilder();
assertTrue(builder.isInitialized());
builder.setOptionalMessage(TEST_REQUIRED_UNINITIALIZED);
assertFalse(builder.isInitialized());
builder.setOptionalMessage(TEST_REQUIRED_INITIALIZED);
assertTrue(builder.isInitialized());
builder.addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED);
assertFalse(builder.isInitialized());
builder.setRepeatedMessage(0, TEST_REQUIRED_INITIALIZED);
assertTrue(builder.isInitialized());
}
public void testRequiredExtension() throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
assertTrue(builder.isInitialized());
builder.setExtension(TestRequired.single, TEST_REQUIRED_UNINITIALIZED);
assertFalse(builder.isInitialized());
builder.setExtension(TestRequired.single, TEST_REQUIRED_INITIALIZED);
assertTrue(builder.isInitialized());
builder.addExtension(TestRequired.multi, TEST_REQUIRED_UNINITIALIZED);
assertFalse(builder.isInitialized());
builder.setExtension(TestRequired.multi, 0, TEST_REQUIRED_INITIALIZED);
assertTrue(builder.isInitialized());
}
public void testRequiredDynamic() throws Exception {
Descriptors.Descriptor descriptor = TestRequired.getDescriptor();
DynamicMessage.Builder builder = DynamicMessage.newBuilder(descriptor);
assertFalse(builder.isInitialized());
builder.setField(descriptor.findFieldByName("a"), 1);
assertFalse(builder.isInitialized());
builder.setField(descriptor.findFieldByName("b"), 1);
assertFalse(builder.isInitialized());
builder.setField(descriptor.findFieldByName("c"), 1);
assertTrue(builder.isInitialized());
}
public void testRequiredDynamicForeign() throws Exception {
Descriptors.Descriptor descriptor = TestRequiredForeign.getDescriptor();
DynamicMessage.Builder builder = DynamicMessage.newBuilder(descriptor);
assertTrue(builder.isInitialized());
builder.setField(descriptor.findFieldByName("optional_message"),
TEST_REQUIRED_UNINITIALIZED);
assertFalse(builder.isInitialized());
builder.setField(descriptor.findFieldByName("optional_message"),
TEST_REQUIRED_INITIALIZED);
assertTrue(builder.isInitialized());
builder.addRepeatedField(descriptor.findFieldByName("repeated_message"),
TEST_REQUIRED_UNINITIALIZED);
assertFalse(builder.isInitialized());
builder.setRepeatedField(descriptor.findFieldByName("repeated_message"), 0,
TEST_REQUIRED_INITIALIZED);
assertTrue(builder.isInitialized());
}
public void testUninitializedException() throws Exception {
try {
TestRequired.newBuilder().build();
fail("Should have thrown an exception.");
} catch (UninitializedMessageException e) {
assertEquals("Message missing required fields: a, b, c", e.getMessage());
}
}
public void testBuildPartial() throws Exception {
// We're mostly testing that no exception is thrown.
TestRequired message = TestRequired.newBuilder().buildPartial();
assertFalse(message.isInitialized());
}
public void testNestedUninitializedException() throws Exception {
try {
TestRequiredForeign.newBuilder()
.setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
.addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
.addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
.build();
fail("Should have thrown an exception.");
} catch (UninitializedMessageException e) {
assertEquals(
"Message missing required fields: " +
"optional_message.a, " +
"optional_message.b, " +
"optional_message.c, " +
"repeated_message[0].a, " +
"repeated_message[0].b, " +
"repeated_message[0].c, " +
"repeated_message[1].a, " +
"repeated_message[1].b, " +
"repeated_message[1].c",
e.getMessage());
}
}
public void testBuildNestedPartial() throws Exception {
// We're mostly testing that no exception is thrown.
TestRequiredForeign message =
TestRequiredForeign.newBuilder()
.setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
.addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
.addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
.buildPartial();
assertFalse(message.isInitialized());
}
public void testParseUnititialized() throws Exception {
try {
TestRequired.parseFrom(ByteString.EMPTY);
fail("Should have thrown an exception.");
} catch (InvalidProtocolBufferException e) {
assertEquals("Message missing required fields: a, b, c", e.getMessage());
}
}
public void testParseNestedUnititialized() throws Exception {
ByteString data =
TestRequiredForeign.newBuilder()
.setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
.addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
.addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
.buildPartial().toByteString();
try {
TestRequiredForeign.parseFrom(data);
fail("Should have thrown an exception.");
} catch (InvalidProtocolBufferException e) {
assertEquals(
"Message missing required fields: " +
"optional_message.a, " +
"optional_message.b, " +
"optional_message.c, " +
"repeated_message[0].a, " +
"repeated_message[0].b, " +
"repeated_message[0].c, " +
"repeated_message[1].a, " +
"repeated_message[1].b, " +
"repeated_message[1].c",
e.getMessage());
}
}
public void testDynamicUninitializedException() throws Exception {
try {
DynamicMessage.newBuilder(TestRequired.getDescriptor()).build();
fail("Should have thrown an exception.");
} catch (UninitializedMessageException e) {
assertEquals("Message missing required fields: a, b, c", e.getMessage());
}
}
public void testDynamicBuildPartial() throws Exception {
// We're mostly testing that no exception is thrown.
DynamicMessage message =
DynamicMessage.newBuilder(TestRequired.getDescriptor())
.buildPartial();
assertFalse(message.isInitialized());
}
public void testDynamicParseUnititialized() throws Exception {
try {
Descriptors.Descriptor descriptor = TestRequired.getDescriptor();
DynamicMessage.parseFrom(descriptor, ByteString.EMPTY);
fail("Should have thrown an exception.");
} catch (InvalidProtocolBufferException e) {
assertEquals("Message missing required fields: a, b, c", e.getMessage());
}
}
/** Test reading unset repeated message from DynamicMessage. */
public void testDynamicRepeatedMessageNull() throws Exception {
Descriptors.Descriptor descriptor = TestRequired.getDescriptor();
DynamicMessage result =
DynamicMessage.newBuilder(TestAllTypes.getDescriptor())
.mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
.build();
assertTrue(result.getField(result.getDescriptorForType()
.findFieldByName("repeated_foreign_message")) instanceof List<?>);
assertEquals(result.getRepeatedFieldCount(result.getDescriptorForType()
.findFieldByName("repeated_foreign_message")), 0);
}
/** Test reading repeated message from DynamicMessage. */
public void testDynamicRepeatedMessageNotNull() throws Exception {
TestAllTypes REPEATED_NESTED =
TestAllTypes.newBuilder()
.setOptionalInt32(1)
.setOptionalString("foo")
.setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
.addRepeatedString("bar")
.addRepeatedForeignMessage(ForeignMessage.getDefaultInstance())
.addRepeatedForeignMessage(ForeignMessage.getDefaultInstance())
.build();
Descriptors.Descriptor descriptor = TestRequired.getDescriptor();
DynamicMessage result =
DynamicMessage.newBuilder(TestAllTypes.getDescriptor())
.mergeFrom(DynamicMessage.newBuilder(REPEATED_NESTED).build())
.build();
assertTrue(result.getField(result.getDescriptorForType()
.findFieldByName("repeated_foreign_message")) instanceof List<?>);
assertEquals(result.getRepeatedFieldCount(result.getDescriptorForType()
.findFieldByName("repeated_foreign_message")), 2);
}
}

@ -1,186 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import protobuf_unittest.Vehicle;
import protobuf_unittest.Wheel;
import junit.framework.TestCase;
import java.util.List;
import java.util.ArrayList;
/**
* Test cases that exercise end-to-end use cases involving
* {@link SingleFieldBuilder} and {@link RepeatedFieldBuilder}.
*
* @author jonp@google.com (Jon Perlow)
*/
public class NestedBuildersTest extends TestCase {
public void testMessagesAndBuilders() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
vehicleBuilder.addWheelBuilder()
.setRadius(4)
.setWidth(1);
vehicleBuilder.addWheelBuilder()
.setRadius(4)
.setWidth(2);
vehicleBuilder.addWheelBuilder()
.setRadius(4)
.setWidth(3);
vehicleBuilder.addWheelBuilder()
.setRadius(4)
.setWidth(4);
vehicleBuilder.getEngineBuilder()
.setLiters(10);
Vehicle vehicle = vehicleBuilder.build();
assertEquals(4, vehicle.getWheelCount());
for (int i = 0; i < 4; i++) {
Wheel wheel = vehicle.getWheel(i);
assertEquals(4, wheel.getRadius());
assertEquals(i + 1, wheel.getWidth());
}
assertEquals(10, vehicle.getEngine().getLiters());
for (int i = 0; i < 4; i++) {
vehicleBuilder.getWheelBuilder(i)
.setRadius(5)
.setWidth(i + 10);
}
vehicleBuilder.getEngineBuilder().setLiters(20);
vehicle = vehicleBuilder.build();
for (int i = 0; i < 4; i++) {
Wheel wheel = vehicle.getWheel(i);
assertEquals(5, wheel.getRadius());
assertEquals(i + 10, wheel.getWidth());
}
assertEquals(20, vehicle.getEngine().getLiters());
assertTrue(vehicle.hasEngine());
}
public void testMessagesAreCached() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
vehicleBuilder.addWheelBuilder()
.setRadius(1)
.setWidth(2);
vehicleBuilder.addWheelBuilder()
.setRadius(3)
.setWidth(4);
vehicleBuilder.addWheelBuilder()
.setRadius(5)
.setWidth(6);
vehicleBuilder.addWheelBuilder()
.setRadius(7)
.setWidth(8);
// Make sure messages are cached.
List<Wheel> wheels = new ArrayList<Wheel>(vehicleBuilder.getWheelList());
for (int i = 0; i < wheels.size(); i++) {
assertSame(wheels.get(i), vehicleBuilder.getWheel(i));
}
// Now get builders and check they didn't change.
for (int i = 0; i < wheels.size(); i++) {
vehicleBuilder.getWheel(i);
}
for (int i = 0; i < wheels.size(); i++) {
assertSame(wheels.get(i), vehicleBuilder.getWheel(i));
}
// Change just one
vehicleBuilder.getWheelBuilder(3)
.setRadius(20).setWidth(20);
// Now get wheels and check that only that one changed
for (int i = 0; i < wheels.size(); i++) {
if (i < 3) {
assertSame(wheels.get(i), vehicleBuilder.getWheel(i));
} else {
assertNotSame(wheels.get(i), vehicleBuilder.getWheel(i));
}
}
}
public void testRemove_WithNestedBuilders() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
vehicleBuilder.addWheelBuilder()
.setRadius(1)
.setWidth(1);
vehicleBuilder.addWheelBuilder()
.setRadius(2)
.setWidth(2);
vehicleBuilder.removeWheel(0);
assertEquals(1, vehicleBuilder.getWheelCount());
assertEquals(2, vehicleBuilder.getWheel(0).getRadius());
}
public void testRemove_WithNestedMessages() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
vehicleBuilder.addWheel(Wheel.newBuilder()
.setRadius(1)
.setWidth(1));
vehicleBuilder.addWheel(Wheel.newBuilder()
.setRadius(2)
.setWidth(2));
vehicleBuilder.removeWheel(0);
assertEquals(1, vehicleBuilder.getWheelCount());
assertEquals(2, vehicleBuilder.getWheel(0).getRadius());
}
public void testMerge() {
Vehicle vehicle1 = Vehicle.newBuilder()
.addWheel(Wheel.newBuilder().setRadius(1).build())
.addWheel(Wheel.newBuilder().setRadius(2).build())
.build();
Vehicle vehicle2 = Vehicle.newBuilder()
.mergeFrom(vehicle1)
.build();
// List should be the same -- no allocation
assertSame(vehicle1.getWheelList(), vehicle2.getWheelList());
Vehicle vehicle3 = vehicle1.toBuilder().build();
assertSame(vehicle1.getWheelList(), vehicle3.getWheelList());
}
public void testGettingBuilderMarksFieldAsHaving() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
vehicleBuilder.getEngineBuilder();
Vehicle vehicle = vehicleBuilder.buildPartial();
assertTrue(vehicle.hasEngine());
}
}

@ -1,278 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import protobuf_unittest.UnittestOptimizeFor.TestOptimizedForSize;
import protobuf_unittest.UnittestOptimizeFor.TestRequiredOptimizedForSize;
import protobuf_unittest.UnittestOptimizeFor;
import protobuf_unittest.UnittestProto.ForeignMessage;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestEmptyMessage;
import protobuf_unittest.UnittestProto.TestRequired;
import protobuf_unittest.UnittestProto.TestParsingMerge;
import protobuf_unittest.UnittestProto;
import junit.framework.TestCase;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Unit test for {@link Parser}.
*
* @author liujisi@google.com (Pherl Liu)
*/
public class ParserTest extends TestCase {
public void testGeneratedMessageParserSingleton() throws Exception {
for (int i = 0; i < 10; i++) {
assertEquals(TestAllTypes.PARSER,
TestUtil.getAllSet().getParserForType());
}
}
private void assertRoundTripEquals(MessageLite message,
ExtensionRegistryLite registry)
throws Exception {
final byte[] data = message.toByteArray();
final int offset = 20;
final int length = data.length;
final int padding = 30;
Parser<? extends MessageLite> parser = message.getParserForType();
assertMessageEquals(message, parser.parseFrom(data, registry));
assertMessageEquals(message, parser.parseFrom(
generatePaddingArray(data, offset, padding),
offset, length, registry));
assertMessageEquals(message, parser.parseFrom(
message.toByteString(), registry));
assertMessageEquals(message, parser.parseFrom(
new ByteArrayInputStream(data), registry));
assertMessageEquals(message, parser.parseFrom(
CodedInputStream.newInstance(data), registry));
}
private void assertRoundTripEquals(MessageLite message) throws Exception {
final byte[] data = message.toByteArray();
final int offset = 20;
final int length = data.length;
final int padding = 30;
Parser<? extends MessageLite> parser = message.getParserForType();
assertMessageEquals(message, parser.parseFrom(data));
assertMessageEquals(message, parser.parseFrom(
generatePaddingArray(data, offset, padding),
offset, length));
assertMessageEquals(message, parser.parseFrom(message.toByteString()));
assertMessageEquals(message, parser.parseFrom(
new ByteArrayInputStream(data)));
assertMessageEquals(message, parser.parseFrom(
CodedInputStream.newInstance(data)));
}
private void assertMessageEquals(MessageLite expected, MessageLite actual)
throws Exception {
if (expected instanceof Message) {
assertEquals(expected, actual);
} else {
assertEquals(expected.toByteString(), actual.toByteString());
}
}
private byte[] generatePaddingArray(byte[] data, int offset, int padding) {
byte[] result = new byte[offset + data.length + padding];
System.arraycopy(data, 0, result, offset, data.length);
return result;
}
public void testNormalMessage() throws Exception {
assertRoundTripEquals(TestUtil.getAllSet());
}
public void testParsePartial() throws Exception {
Parser<TestRequired> parser = TestRequired.PARSER;
final String errorString =
"Should throw exceptions when the parsed message isn't initialized.";
// TestRequired.b and TestRequired.c are not set.
TestRequired partialMessage = TestRequired.newBuilder()
.setA(1).buildPartial();
// parsePartialFrom should pass.
byte[] data = partialMessage.toByteArray();
assertEquals(partialMessage, parser.parsePartialFrom(data));
assertEquals(partialMessage, parser.parsePartialFrom(
partialMessage.toByteString()));
assertEquals(partialMessage, parser.parsePartialFrom(
new ByteArrayInputStream(data)));
assertEquals(partialMessage, parser.parsePartialFrom(
CodedInputStream.newInstance(data)));
// parseFrom(ByteArray)
try {
parser.parseFrom(partialMessage.toByteArray());
fail(errorString);
} catch (InvalidProtocolBufferException e) {
// pass.
}
// parseFrom(ByteString)
try {
parser.parseFrom(partialMessage.toByteString());
fail(errorString);
} catch (InvalidProtocolBufferException e) {
// pass.
}
// parseFrom(InputStream)
try {
parser.parseFrom(new ByteArrayInputStream(partialMessage.toByteArray()));
fail(errorString);
} catch (IOException e) {
// pass.
}
// parseFrom(CodedInputStream)
try {
parser.parseFrom(CodedInputStream.newInstance(
partialMessage.toByteArray()));
fail(errorString);
} catch (IOException e) {
// pass.
}
}
public void testParseDelimitedTo() throws Exception {
// Write normal Message.
TestAllTypes normalMessage = TestUtil.getAllSet();
ByteArrayOutputStream output = new ByteArrayOutputStream();
normalMessage.writeDelimitedTo(output);
InputStream input = new ByteArrayInputStream(output.toByteArray());
assertMessageEquals(
normalMessage,
normalMessage.getParserForType().parseDelimitedFrom(input));
}
public void testParseUnknownFields() throws Exception {
// All fields will be treated as unknown fields in emptyMessage.
TestEmptyMessage emptyMessage = TestEmptyMessage.PARSER.parseFrom(
TestUtil.getAllSet().toByteString());
assertEquals(
TestUtil.getAllSet().toByteString(),
emptyMessage.toByteString());
}
public void testOptimizeForSize() throws Exception {
TestOptimizedForSize.Builder builder = TestOptimizedForSize.newBuilder();
builder.setI(12).setMsg(ForeignMessage.newBuilder().setC(34).build());
builder.setExtension(TestOptimizedForSize.testExtension, 56);
builder.setExtension(TestOptimizedForSize.testExtension2,
TestRequiredOptimizedForSize.newBuilder().setX(78).build());
TestOptimizedForSize message = builder.build();
ExtensionRegistry registry = ExtensionRegistry.newInstance();
UnittestOptimizeFor.registerAllExtensions(registry);
assertRoundTripEquals(message, registry);
}
/** Helper method for {@link #testParsingMerge()}.*/
private void assertMessageMerged(TestAllTypes allTypes)
throws Exception {
assertEquals(3, allTypes.getOptionalInt32());
assertEquals(2, allTypes.getOptionalInt64());
assertEquals("hello", allTypes.getOptionalString());
}
public void testParsingMerge() throws Exception {
// Build messages.
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestAllTypes msg1 = builder.setOptionalInt32(1).build();
builder.clear();
TestAllTypes msg2 = builder.setOptionalInt64(2).build();
builder.clear();
TestAllTypes msg3 = builder.setOptionalInt32(3)
.setOptionalString("hello").build();
// Build groups.
TestParsingMerge.RepeatedFieldsGenerator.Group1 optionalG1 =
TestParsingMerge.RepeatedFieldsGenerator.Group1.newBuilder()
.setField1(msg1).build();
TestParsingMerge.RepeatedFieldsGenerator.Group1 optionalG2 =
TestParsingMerge.RepeatedFieldsGenerator.Group1.newBuilder()
.setField1(msg2).build();
TestParsingMerge.RepeatedFieldsGenerator.Group1 optionalG3 =
TestParsingMerge.RepeatedFieldsGenerator.Group1.newBuilder()
.setField1(msg3).build();
TestParsingMerge.RepeatedFieldsGenerator.Group2 repeatedG1 =
TestParsingMerge.RepeatedFieldsGenerator.Group2.newBuilder()
.setField1(msg1).build();
TestParsingMerge.RepeatedFieldsGenerator.Group2 repeatedG2 =
TestParsingMerge.RepeatedFieldsGenerator.Group2.newBuilder()
.setField1(msg2).build();
TestParsingMerge.RepeatedFieldsGenerator.Group2 repeatedG3 =
TestParsingMerge.RepeatedFieldsGenerator.Group2.newBuilder()
.setField1(msg3).build();
// Assign and serialize RepeatedFieldsGenerator.
ByteString data = TestParsingMerge.RepeatedFieldsGenerator.newBuilder()
.addField1(msg1).addField1(msg2).addField1(msg3)
.addField2(msg1).addField2(msg2).addField2(msg3)
.addField3(msg1).addField3(msg2).addField3(msg3)
.addGroup1(optionalG1).addGroup1(optionalG2).addGroup1(optionalG3)
.addGroup2(repeatedG1).addGroup2(repeatedG2).addGroup2(repeatedG3)
.addExt1(msg1).addExt1(msg2).addExt1(msg3)
.addExt2(msg1).addExt2(msg2).addExt2(msg3)
.build().toByteString();
// Parse TestParsingMerge.
ExtensionRegistry registry = ExtensionRegistry.newInstance();
UnittestProto.registerAllExtensions(registry);
TestParsingMerge parsingMerge =
TestParsingMerge.PARSER.parseFrom(data, registry);
// Required and optional fields should be merged.
assertMessageMerged(parsingMerge.getRequiredAllTypes());
assertMessageMerged(parsingMerge.getOptionalAllTypes());
assertMessageMerged(
parsingMerge.getOptionalGroup().getOptionalGroupAllTypes());
assertMessageMerged(parsingMerge.getExtension(
TestParsingMerge.optionalExt));
// Repeated fields should not be merged.
assertEquals(3, parsingMerge.getRepeatedAllTypesCount());
assertEquals(3, parsingMerge.getRepeatedGroupCount());
assertEquals(3, parsingMerge.getExtensionCount(
TestParsingMerge.repeatedExt));
}
}

@ -1,62 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
/**
* This class tests {@link RopeByteString#substring(int, int)} by inheriting the tests from
* {@link LiteralByteStringTest}. Only a couple of methods are overridden.
*
* @author carlanton@google.com (Carl Haverl)
*/
public class RopeByteStringSubstringTest extends LiteralByteStringTest {
@Override
protected void setUp() throws Exception {
classUnderTest = "RopeByteString";
byte[] sourceBytes = ByteStringTest.getTestBytes(22341, 22337766L);
Iterator<ByteString> iter = ByteStringTest.makeConcretePieces(sourceBytes).iterator();
ByteString sourceString = iter.next();
while (iter.hasNext()) {
sourceString = sourceString.concat(iter.next());
}
int from = 1130;
int to = sourceBytes.length - 5555;
stringUnderTest = sourceString.substring(from, to);
referenceBytes = new byte[to - from];
System.arraycopy(sourceBytes, from, referenceBytes, 0, to - from);
expectedHashCode = -1259260680;
}
}

@ -1,84 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Iterator;
/**
* This class tests {@link RopeByteString} by inheriting the tests from
* {@link LiteralByteStringTest}. Only a couple of methods are overridden.
*
* <p>A full test of the result of {@link RopeByteString#substring(int, int)} is found in the
* separate class {@link RopeByteStringSubstringTest}.
*
* @author carlanton@google.com (Carl Haverl)
*/
public class RopeByteStringTest extends LiteralByteStringTest {
@Override
protected void setUp() throws Exception {
classUnderTest = "RopeByteString";
referenceBytes = ByteStringTest.getTestBytes(22341, 22337766L);
Iterator<ByteString> iter = ByteStringTest.makeConcretePieces(referenceBytes).iterator();
stringUnderTest = iter.next();
while (iter.hasNext()) {
stringUnderTest = stringUnderTest.concat(iter.next());
}
expectedHashCode = -1214197238;
}
public void testBalance() {
int numberOfPieces = 10000;
int pieceSize = 64;
byte[] testBytes = ByteStringTest.getTestBytes(numberOfPieces * pieceSize, 113377L);
// Build up a big ByteString from smaller pieces to force a rebalance
ByteString concatenated = ByteString.EMPTY;
for (int i = 0; i < numberOfPieces; ++i) {
concatenated = concatenated.concat(ByteString.copyFrom(testBytes, i * pieceSize, pieceSize));
}
assertEquals(classUnderTest + " from string must have the expected type",
classUnderTest, getActualClassName(concatenated));
assertTrue(classUnderTest + " underlying bytes must match after balancing",
Arrays.equals(testBytes, concatenated.toByteArray()));
ByteString testString = ByteString.copyFrom(testBytes);
assertTrue(classUnderTest + " balanced string must equal flat string",
concatenated.equals(testString));
assertTrue(classUnderTest + " flat string must equal balanced string",
testString.equals(concatenated));
assertEquals(classUnderTest + " balanced string must have same hash code as flat string",
testString.hashCode(), concatenated.hashCode());
}
}

@ -1,321 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import com.google.protobuf.Descriptors.FileDescriptor;
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 org.easymock.classextension.EasyMock;
import org.easymock.classextension.IMocksControl;
import org.easymock.IArgumentMatcher;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
/**
* Tests services and stubs.
*
* @author kenton@google.com Kenton Varda
*/
public class ServiceTest extends TestCase {
private IMocksControl control;
private RpcController mockController;
private final Descriptors.MethodDescriptor fooDescriptor =
TestService.getDescriptor().getMethods().get(0);
private final Descriptors.MethodDescriptor barDescriptor =
TestService.getDescriptor().getMethods().get(1);
@Override
protected void setUp() throws Exception {
super.setUp();
control = EasyMock.createStrictControl();
mockController = control.createMock(RpcController.class);
}
// =================================================================
/** Tests Service.callMethod(). */
public void testCallMethod() throws Exception {
FooRequest fooRequest = FooRequest.newBuilder().build();
BarRequest barRequest = BarRequest.newBuilder().build();
MockCallback<Message> fooCallback = new MockCallback<Message>();
MockCallback<Message> barCallback = new MockCallback<Message>();
TestService mockService = control.createMock(TestService.class);
mockService.foo(EasyMock.same(mockController), EasyMock.same(fooRequest),
this.<FooResponse>wrapsCallback(fooCallback));
mockService.bar(EasyMock.same(mockController), EasyMock.same(barRequest),
this.<BarResponse>wrapsCallback(barCallback));
control.replay();
mockService.callMethod(fooDescriptor, mockController,
fooRequest, fooCallback);
mockService.callMethod(barDescriptor, mockController,
barRequest, barCallback);
control.verify();
}
/** Tests Service.get{Request,Response}Prototype(). */
public void testGetPrototype() throws Exception {
TestService mockService = control.createMock(TestService.class);
assertSame(mockService.getRequestPrototype(fooDescriptor),
FooRequest.getDefaultInstance());
assertSame(mockService.getResponsePrototype(fooDescriptor),
FooResponse.getDefaultInstance());
assertSame(mockService.getRequestPrototype(barDescriptor),
BarRequest.getDefaultInstance());
assertSame(mockService.getResponsePrototype(barDescriptor),
BarResponse.getDefaultInstance());
}
/** Tests generated stubs. */
public void testStub() throws Exception {
FooRequest fooRequest = FooRequest.newBuilder().build();
BarRequest barRequest = BarRequest.newBuilder().build();
MockCallback<FooResponse> fooCallback = new MockCallback<FooResponse>();
MockCallback<BarResponse> barCallback = new MockCallback<BarResponse>();
RpcChannel mockChannel = control.createMock(RpcChannel.class);
TestService stub = TestService.newStub(mockChannel);
mockChannel.callMethod(
EasyMock.same(fooDescriptor),
EasyMock.same(mockController),
EasyMock.same(fooRequest),
EasyMock.same(FooResponse.getDefaultInstance()),
this.<Message>wrapsCallback(fooCallback));
mockChannel.callMethod(
EasyMock.same(barDescriptor),
EasyMock.same(mockController),
EasyMock.same(barRequest),
EasyMock.same(BarResponse.getDefaultInstance()),
this.<Message>wrapsCallback(barCallback));
control.replay();
stub.foo(mockController, fooRequest, fooCallback);
stub.bar(mockController, barRequest, barCallback);
control.verify();
}
/** Tests generated blocking stubs. */
public void testBlockingStub() throws Exception {
FooRequest fooRequest = FooRequest.newBuilder().build();
BarRequest barRequest = BarRequest.newBuilder().build();
BlockingRpcChannel mockChannel =
control.createMock(BlockingRpcChannel.class);
TestService.BlockingInterface stub =
TestService.newBlockingStub(mockChannel);
FooResponse fooResponse = FooResponse.newBuilder().build();
BarResponse barResponse = BarResponse.newBuilder().build();
EasyMock.expect(mockChannel.callBlockingMethod(
EasyMock.same(fooDescriptor),
EasyMock.same(mockController),
EasyMock.same(fooRequest),
EasyMock.same(FooResponse.getDefaultInstance()))).andReturn(fooResponse);
EasyMock.expect(mockChannel.callBlockingMethod(
EasyMock.same(barDescriptor),
EasyMock.same(mockController),
EasyMock.same(barRequest),
EasyMock.same(BarResponse.getDefaultInstance()))).andReturn(barResponse);
control.replay();
assertSame(fooResponse, stub.foo(mockController, fooRequest));
assertSame(barResponse, stub.bar(mockController, barRequest));
control.verify();
}
public void testNewReflectiveService() {
ServiceWithNoOuter.Interface impl =
control.createMock(ServiceWithNoOuter.Interface.class);
RpcController controller = control.createMock(RpcController.class);
Service service = ServiceWithNoOuter.newReflectiveService(impl);
MethodDescriptor fooMethod =
ServiceWithNoOuter.getDescriptor().findMethodByName("Foo");
MessageWithNoOuter request = MessageWithNoOuter.getDefaultInstance();
RpcCallback<Message> callback = new RpcCallback<Message>() {
public void run(Message parameter) {
// No reason this should be run.
fail();
}
};
RpcCallback<TestAllTypes> specializedCallback =
RpcUtil.specializeCallback(callback);
impl.foo(EasyMock.same(controller), EasyMock.same(request),
EasyMock.same(specializedCallback));
EasyMock.expectLastCall();
control.replay();
service.callMethod(fooMethod, controller, request, callback);
control.verify();
}
public void testNewReflectiveBlockingService() throws ServiceException {
ServiceWithNoOuter.BlockingInterface impl =
control.createMock(ServiceWithNoOuter.BlockingInterface.class);
RpcController controller = control.createMock(RpcController.class);
BlockingService service =
ServiceWithNoOuter.newReflectiveBlockingService(impl);
MethodDescriptor fooMethod =
ServiceWithNoOuter.getDescriptor().findMethodByName("Foo");
MessageWithNoOuter request = MessageWithNoOuter.getDefaultInstance();
TestAllTypes expectedResponse = TestAllTypes.getDefaultInstance();
EasyMock.expect(impl.foo(EasyMock.same(controller), EasyMock.same(request)))
.andReturn(expectedResponse);
control.replay();
Message response =
service.callBlockingMethod(fooMethod, controller, request);
assertEquals(expectedResponse, response);
control.verify();
}
public void testNoGenericServices() throws Exception {
// Non-services should be usable.
UnittestNoGenericServices.TestMessage message =
UnittestNoGenericServices.TestMessage.newBuilder()
.setA(123)
.setExtension(UnittestNoGenericServices.testExtension, 456)
.build();
assertEquals(123, message.getA());
assertEquals(1, UnittestNoGenericServices.TestEnum.FOO.getNumber());
// Build a list of the class names nested in UnittestNoGenericServices.
String outerName = "google.protobuf.no_generic_services_test." +
"UnittestNoGenericServices";
Class<?> outerClass = Class.forName(outerName);
Set<String> innerClassNames = new HashSet<String>();
for (Class<?> innerClass : outerClass.getClasses()) {
String fullName = innerClass.getName();
// Figure out the unqualified name of the inner class.
// Note: Surprisingly, the full name of an inner class will be separated
// from the outer class name by a '$' rather than a '.'. This is not
// mentioned in the documentation for java.lang.Class. I don't want to
// make assumptions, so I'm just going to accept any character as the
// separator.
assertTrue(fullName.startsWith(outerName));
if (!Service.class.isAssignableFrom(innerClass) &&
!Message.class.isAssignableFrom(innerClass) &&
!ProtocolMessageEnum.class.isAssignableFrom(innerClass)) {
// Ignore any classes not generated by the base code generator.
continue;
}
innerClassNames.add(fullName.substring(outerName.length() + 1));
}
// No service class should have been generated.
assertTrue(innerClassNames.contains("TestMessage"));
assertTrue(innerClassNames.contains("TestEnum"));
assertFalse(innerClassNames.contains("TestService"));
// But descriptors are there.
FileDescriptor file = UnittestNoGenericServices.getDescriptor();
assertEquals(1, file.getServices().size());
assertEquals("TestService", file.getServices().get(0).getName());
assertEquals(1, file.getServices().get(0).getMethods().size());
assertEquals("Foo",
file.getServices().get(0).getMethods().get(0).getName());
}
// =================================================================
/**
* wrapsCallback() is an EasyMock argument predicate. wrapsCallback(c)
* matches a callback if calling that callback causes c to be called.
* In other words, c wraps the given callback.
*/
private <Type extends Message> RpcCallback<Type> wrapsCallback(
MockCallback<?> callback) {
EasyMock.reportMatcher(new WrapsCallback(callback));
return null;
}
/** The parameter to wrapsCallback() must be a MockCallback. */
private static class MockCallback<Type extends Message>
implements RpcCallback<Type> {
private boolean called = false;
public boolean isCalled() { return called; }
public void reset() { called = false; }
public void run(Type message) { called = true; }
}
/** Implementation of the wrapsCallback() argument matcher. */
private static class WrapsCallback implements IArgumentMatcher {
private MockCallback<?> callback;
public WrapsCallback(MockCallback<?> callback) {
this.callback = callback;
}
@SuppressWarnings("unchecked")
public boolean matches(Object actual) {
if (!(actual instanceof RpcCallback)) {
return false;
}
RpcCallback actualCallback = (RpcCallback)actual;
callback.reset();
actualCallback.run(null);
return callback.isCalled();
}
public void appendTo(StringBuffer buffer) {
buffer.append("wrapsCallback(mockCallback)");
}
}
}

@ -1,64 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import junit.framework.TestCase;
/**
* Tests that proto2 api generation doesn't cause compile errors when
* compiling protocol buffers that have names that would otherwise conflict
* if not fully qualified (like @Deprecated and @Override).
*
* @author jonp@google.com (Jon Perlow)
*/
public class TestBadIdentifiers extends TestCase {
public void testCompilation() {
// If this compiles, it means the generation was correct.
TestBadIdentifiersProto.Deprecated.newBuilder();
TestBadIdentifiersProto.Override.newBuilder();
}
public void testGetDescriptor() {
Descriptors.FileDescriptor fileDescriptor =
TestBadIdentifiersProto.getDescriptor();
String descriptorField = TestBadIdentifiersProto.Descriptor
.getDefaultInstance().getDescriptor();
Descriptors.Descriptor protoDescriptor = TestBadIdentifiersProto.Descriptor
.getDefaultInstance().getDescriptorForType();
String nestedDescriptorField = TestBadIdentifiersProto.Descriptor
.NestedDescriptor.getDefaultInstance().getDescriptor();
Descriptors.Descriptor nestedProtoDescriptor = TestBadIdentifiersProto
.Descriptor.NestedDescriptor.getDefaultInstance()
.getDescriptorForType();
}
}

@ -1,536 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import com.google.protobuf.Descriptors.FieldDescriptor;
import protobuf_unittest.UnittestMset.TestMessageSet;
import protobuf_unittest.UnittestMset.TestMessageSetExtension1;
import protobuf_unittest.UnittestMset.TestMessageSetExtension2;
import protobuf_unittest.UnittestProto.OneString;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypes.NestedMessage;
import protobuf_unittest.UnittestProto.TestEmptyMessage;
import junit.framework.TestCase;
import java.io.StringReader;
/**
* Test case for {@link TextFormat}.
*
* TODO(wenboz): ExtensionTest and rest of text_format_unittest.cc.
*
* @author wenboz@google.com (Wenbo Zhu)
*/
public class TextFormatTest extends TestCase {
// A basic string with different escapable characters for testing.
private final static String kEscapeTestString =
"\"A string with ' characters \n and \r newlines and \t tabs and \001 "
+ "slashes \\";
// A representation of the above string with all the characters escaped.
private final static String kEscapeTestStringEscaped =
"\\\"A string with \\' characters \\n and \\r newlines "
+ "and \\t tabs and \\001 slashes \\\\";
private static String allFieldsSetText = TestUtil.readTextFromFile(
"text_format_unittest_data.txt");
private static String allExtensionsSetText = TestUtil.readTextFromFile(
"text_format_unittest_extensions_data.txt");
private static String exoticText =
"repeated_int32: -1\n" +
"repeated_int32: -2147483648\n" +
"repeated_int64: -1\n" +
"repeated_int64: -9223372036854775808\n" +
"repeated_uint32: 4294967295\n" +
"repeated_uint32: 2147483648\n" +
"repeated_uint64: 18446744073709551615\n" +
"repeated_uint64: 9223372036854775808\n" +
"repeated_double: 123.0\n" +
"repeated_double: 123.5\n" +
"repeated_double: 0.125\n" +
"repeated_double: .125\n" +
"repeated_double: -.125\n" +
"repeated_double: 1.23E17\n" +
"repeated_double: 1.23E+17\n" +
"repeated_double: -1.23e-17\n" +
"repeated_double: .23e+17\n" +
"repeated_double: -.23E17\n" +
"repeated_double: 1.235E22\n" +
"repeated_double: 1.235E-18\n" +
"repeated_double: 123.456789\n" +
"repeated_double: Infinity\n" +
"repeated_double: -Infinity\n" +
"repeated_double: NaN\n" +
"repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"" +
"\\341\\210\\264\"\n" +
"repeated_bytes: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\376\"\n";
private static String canonicalExoticText =
exoticText.replace(": .", ": 0.").replace(": -.", ": -0.") // short-form double
.replace("23e", "23E").replace("E+", "E").replace("0.23E17", "2.3E16");
private String messageSetText =
"[protobuf_unittest.TestMessageSetExtension1] {\n" +
" i: 123\n" +
"}\n" +
"[protobuf_unittest.TestMessageSetExtension2] {\n" +
" str: \"foo\"\n" +
"}\n";
/** Print TestAllTypes and compare with golden file. */
public void testPrintMessage() throws Exception {
String javaText = TextFormat.printToString(TestUtil.getAllSet());
// Java likes to add a trailing ".0" to floats and doubles. C printf
// (with %g format) does not. Our golden files are used for both
// C++ and Java TextFormat classes, so we need to conform.
javaText = javaText.replace(".0\n", "\n");
assertEquals(allFieldsSetText, javaText);
}
/** Print TestAllTypes as Builder and compare with golden file. */
public void testPrintMessageBuilder() throws Exception {
String javaText = TextFormat.printToString(TestUtil.getAllSetBuilder());
// Java likes to add a trailing ".0" to floats and doubles. C printf
// (with %g format) does not. Our golden files are used for both
// C++ and Java TextFormat classes, so we need to conform.
javaText = javaText.replace(".0\n", "\n");
assertEquals(allFieldsSetText, javaText);
}
/** Print TestAllExtensions and compare with golden file. */
public void testPrintExtensions() throws Exception {
String javaText = TextFormat.printToString(TestUtil.getAllExtensionsSet());
// Java likes to add a trailing ".0" to floats and doubles. C printf
// (with %g format) does not. Our golden files are used for both
// C++ and Java TextFormat classes, so we need to conform.
javaText = javaText.replace(".0\n", "\n");
assertEquals(allExtensionsSetText, javaText);
}
// Creates an example unknown field set.
private UnknownFieldSet makeUnknownFieldSet() {
return UnknownFieldSet.newBuilder()
.addField(5,
UnknownFieldSet.Field.newBuilder()
.addVarint(1)
.addFixed32(2)
.addFixed64(3)
.addLengthDelimited(ByteString.copyFromUtf8("4"))
.addGroup(
UnknownFieldSet.newBuilder()
.addField(10,
UnknownFieldSet.Field.newBuilder()
.addVarint(5)
.build())
.build())
.build())
.addField(8,
UnknownFieldSet.Field.newBuilder()
.addVarint(1)
.addVarint(2)
.addVarint(3)
.build())
.addField(15,
UnknownFieldSet.Field.newBuilder()
.addVarint(0xABCDEF1234567890L)
.addFixed32(0xABCD1234)
.addFixed64(0xABCDEF1234567890L)
.build())
.build();
}
public void testPrintUnknownFields() throws Exception {
// Test printing of unknown fields in a message.
TestEmptyMessage message =
TestEmptyMessage.newBuilder()
.setUnknownFields(makeUnknownFieldSet())
.build();
assertEquals(
"5: 1\n" +
"5: 0x00000002\n" +
"5: 0x0000000000000003\n" +
"5: \"4\"\n" +
"5 {\n" +
" 10: 5\n" +
"}\n" +
"8: 1\n" +
"8: 2\n" +
"8: 3\n" +
"15: 12379813812177893520\n" +
"15: 0xabcd1234\n" +
"15: 0xabcdef1234567890\n",
TextFormat.printToString(message));
}
public void testPrintField() throws Exception {
final FieldDescriptor dataField =
OneString.getDescriptor().findFieldByName("data");
assertEquals(
"data: \"test data\"\n",
TextFormat.printFieldToString(dataField, "test data"));
final FieldDescriptor optionalField =
TestAllTypes.getDescriptor().findFieldByName("optional_nested_message");
final Object value = NestedMessage.newBuilder().setBb(42).build();
assertEquals(
"optional_nested_message {\n bb: 42\n}\n",
TextFormat.printFieldToString(optionalField, value));
}
/**
* Helper to construct a ByteString from a String containing only 8-bit
* characters. The characters are converted directly to bytes, *not*
* encoded using UTF-8.
*/
private ByteString bytes(String str) throws Exception {
return ByteString.copyFrom(str.getBytes("ISO-8859-1"));
}
/**
* Helper to construct a ByteString from a bunch of bytes. The inputs are
* actually ints so that I can use hex notation and not get stupid errors
* about precision.
*/
private ByteString bytes(int... bytesAsInts) {
byte[] bytes = new byte[bytesAsInts.length];
for (int i = 0; i < bytesAsInts.length; i++) {
bytes[i] = (byte) bytesAsInts[i];
}
return ByteString.copyFrom(bytes);
}
public void testPrintExotic() throws Exception {
Message message = TestAllTypes.newBuilder()
// Signed vs. unsigned numbers.
.addRepeatedInt32 (-1)
.addRepeatedUint32(-1)
.addRepeatedInt64 (-1)
.addRepeatedUint64(-1)
.addRepeatedInt32 (1 << 31)
.addRepeatedUint32(1 << 31)
.addRepeatedInt64 (1l << 63)
.addRepeatedUint64(1l << 63)
// Floats of various precisions and exponents.
.addRepeatedDouble(123)
.addRepeatedDouble(123.5)
.addRepeatedDouble(0.125)
.addRepeatedDouble(.125)
.addRepeatedDouble(-.125)
.addRepeatedDouble(123e15)
.addRepeatedDouble(123e15)
.addRepeatedDouble(-1.23e-17)
.addRepeatedDouble(.23e17)
.addRepeatedDouble(-23e15)
.addRepeatedDouble(123.5e20)
.addRepeatedDouble(123.5e-20)
.addRepeatedDouble(123.456789)
.addRepeatedDouble(Double.POSITIVE_INFINITY)
.addRepeatedDouble(Double.NEGATIVE_INFINITY)
.addRepeatedDouble(Double.NaN)
// Strings and bytes that needing escaping.
.addRepeatedString("\0\001\007\b\f\n\r\t\013\\\'\"\u1234")
.addRepeatedBytes(bytes("\0\001\007\b\f\n\r\t\013\\\'\"\u00fe"))
.build();
assertEquals(canonicalExoticText, message.toString());
}
public void testPrintMessageSet() throws Exception {
TestMessageSet messageSet =
TestMessageSet.newBuilder()
.setExtension(
TestMessageSetExtension1.messageSetExtension,
TestMessageSetExtension1.newBuilder().setI(123).build())
.setExtension(
TestMessageSetExtension2.messageSetExtension,
TestMessageSetExtension2.newBuilder().setStr("foo").build())
.build();
assertEquals(messageSetText, messageSet.toString());
}
// =================================================================
public void testParse() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(allFieldsSetText, builder);
TestUtil.assertAllFieldsSet(builder.build());
}
public void testParseReader() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(new StringReader(allFieldsSetText), builder);
TestUtil.assertAllFieldsSet(builder.build());
}
public void testParseExtensions() throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
TextFormat.merge(allExtensionsSetText,
TestUtil.getExtensionRegistry(),
builder);
TestUtil.assertAllExtensionsSet(builder.build());
}
public void testParseCompatibility() throws Exception {
String original = "repeated_float: inf\n" +
"repeated_float: -inf\n" +
"repeated_float: nan\n" +
"repeated_float: inff\n" +
"repeated_float: -inff\n" +
"repeated_float: nanf\n" +
"repeated_float: 1.0f\n" +
"repeated_float: infinityf\n" +
"repeated_float: -Infinityf\n" +
"repeated_double: infinity\n" +
"repeated_double: -infinity\n" +
"repeated_double: nan\n";
String canonical = "repeated_float: Infinity\n" +
"repeated_float: -Infinity\n" +
"repeated_float: NaN\n" +
"repeated_float: Infinity\n" +
"repeated_float: -Infinity\n" +
"repeated_float: NaN\n" +
"repeated_float: 1.0\n" +
"repeated_float: Infinity\n" +
"repeated_float: -Infinity\n" +
"repeated_double: Infinity\n" +
"repeated_double: -Infinity\n" +
"repeated_double: NaN\n";
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(original, builder);
assertEquals(canonical, builder.build().toString());
}
public void testParseExotic() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(exoticText, builder);
// Too lazy to check things individually. Don't try to debug this
// if testPrintExotic() is failing.
assertEquals(canonicalExoticText, builder.build().toString());
}
public void testParseMessageSet() throws Exception {
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
extensionRegistry.add(TestMessageSetExtension2.messageSetExtension);
TestMessageSet.Builder builder = TestMessageSet.newBuilder();
TextFormat.merge(messageSetText, extensionRegistry, builder);
TestMessageSet messageSet = builder.build();
assertTrue(messageSet.hasExtension(
TestMessageSetExtension1.messageSetExtension));
assertEquals(123, messageSet.getExtension(
TestMessageSetExtension1.messageSetExtension).getI());
assertTrue(messageSet.hasExtension(
TestMessageSetExtension2.messageSetExtension));
assertEquals("foo", messageSet.getExtension(
TestMessageSetExtension2.messageSetExtension).getStr());
}
public void testParseNumericEnum() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge("optional_nested_enum: 2", builder);
assertEquals(TestAllTypes.NestedEnum.BAR, builder.getOptionalNestedEnum());
}
public void testParseAngleBrackets() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge("OptionalGroup: < a: 1 >", builder);
assertTrue(builder.hasOptionalGroup());
assertEquals(1, builder.getOptionalGroup().getA());
}
public void testParseComment() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(
"# this is a comment\n" +
"optional_int32: 1 # another comment\n" +
"optional_int64: 2\n" +
"# EOF comment", builder);
assertEquals(1, builder.getOptionalInt32());
assertEquals(2, builder.getOptionalInt64());
}
// =================================================================
public void testParseString() throws Exception {
final String zh = "\u9999\u6e2f\u4e0a\u6d77\ud84f\udf80\u8c50\u9280\u884c";
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge("optional_string: \"" + zh + "\"", builder);
assertEquals(zh, builder.getOptionalString());
}
public void testParseLongString() throws Exception {
String longText =
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890";
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge("optional_string: \"" + longText + "\"", builder);
assertEquals(longText, builder.getOptionalString());
}
public void testParseBoolean() throws Exception {
String goodText =
"repeated_bool: t repeated_bool : 0\n" +
"repeated_bool :f repeated_bool:1";
String goodTextCanonical =
"repeated_bool: true\n" +
"repeated_bool: false\n" +
"repeated_bool: false\n" +
"repeated_bool: true\n";
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(goodText, builder);
assertEquals(goodTextCanonical, builder.build().toString());
try {
TestAllTypes.Builder badBuilder = TestAllTypes.newBuilder();
TextFormat.merge("optional_bool:2", badBuilder);
fail("Should have thrown an exception.");
} catch (TextFormat.ParseException e) {
// success
}
try {
TestAllTypes.Builder badBuilder = TestAllTypes.newBuilder();
TextFormat.merge("optional_bool: foo", badBuilder);
fail("Should have thrown an exception.");
} catch (TextFormat.ParseException e) {
// success
}
}
public void testParseAdjacentStringLiterals() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge("optional_string: \"foo\" 'corge' \"grault\"", builder);
assertEquals("foocorgegrault", builder.getOptionalString());
}
public void testPrintFieldValue() throws Exception {
assertPrintFieldValue("\"Hello\"", "Hello", "repeated_string");
assertPrintFieldValue("123.0", 123f, "repeated_float");
assertPrintFieldValue("123.0", 123d, "repeated_double");
assertPrintFieldValue("123", 123, "repeated_int32");
assertPrintFieldValue("123", 123L, "repeated_int64");
assertPrintFieldValue("true", true, "repeated_bool");
assertPrintFieldValue("4294967295", 0xFFFFFFFF, "repeated_uint32");
assertPrintFieldValue("18446744073709551615", 0xFFFFFFFFFFFFFFFFL,
"repeated_uint64");
assertPrintFieldValue("\"\\001\\002\\003\"",
ByteString.copyFrom(new byte[] {1, 2, 3}), "repeated_bytes");
}
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),
value, sb);
assertEquals(expect, sb.toString());
}
public void testShortDebugString() {
assertEquals("optional_nested_message { bb: 42 } repeated_int32: 1"
+ " repeated_uint32: 2",
TextFormat.shortDebugString(TestAllTypes.newBuilder()
.addRepeatedInt32(1)
.addRepeatedUint32(2)
.setOptionalNestedMessage(
NestedMessage.newBuilder().setBb(42).build())
.build()));
}
public void testShortDebugString_unknown() {
assertEquals("5: 1 5: 0x00000002 5: 0x0000000000000003 5: \"4\" 5 { 10: 5 }"
+ " 8: 1 8: 2 8: 3 15: 12379813812177893520 15: 0xabcd1234 15:"
+ " 0xabcdef1234567890",
TextFormat.shortDebugString(makeUnknownFieldSet()));
}
public void testPrintToUnicodeString() {
assertEquals(
"optional_string: \"abc\u3042efg\"\n" +
"optional_bytes: \"\\343\\201\\202\"\n" +
"repeated_string: \"\u3093XYZ\"\n",
TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
.setOptionalString("abc\u3042efg")
.setOptionalBytes(bytes(0xe3, 0x81, 0x82))
.addRepeatedString("\u3093XYZ")
.build()));
}
public void testPrintToUnicodeString_unknown() {
assertEquals(
"1: \"\\343\\201\\202\"\n",
TextFormat.printToUnicodeString(UnknownFieldSet.newBuilder()
.addField(1,
UnknownFieldSet.Field.newBuilder()
.addLengthDelimited(bytes(0xe3, 0x81, 0x82)).build())
.build()));
}
}

@ -1,438 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import protobuf_unittest.UnittestProto;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestEmptyMessage;
import protobuf_unittest.UnittestProto.TestEmptyMessageWithExtensions;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Map;
/**
* Tests related to unknown field handling.
*
* @author kenton@google.com (Kenton Varda)
*/
public class UnknownFieldSetTest extends TestCase {
public void setUp() throws Exception {
descriptor = TestAllTypes.getDescriptor();
allFields = TestUtil.getAllSet();
allFieldsData = allFields.toByteString();
emptyMessage = TestEmptyMessage.parseFrom(allFieldsData);
unknownFields = emptyMessage.getUnknownFields();
}
UnknownFieldSet.Field getField(String name) {
Descriptors.FieldDescriptor field = descriptor.findFieldByName(name);
assertNotNull(field);
return unknownFields.getField(field.getNumber());
}
// Constructs a protocol buffer which contains fields with all the same
// numbers as allFieldsData except that each field is some other wire
// type.
ByteString getBizarroData() throws Exception {
UnknownFieldSet.Builder bizarroFields = UnknownFieldSet.newBuilder();
UnknownFieldSet.Field varintField =
UnknownFieldSet.Field.newBuilder().addVarint(1).build();
UnknownFieldSet.Field fixed32Field =
UnknownFieldSet.Field.newBuilder().addFixed32(1).build();
for (Map.Entry<Integer, UnknownFieldSet.Field> entry :
unknownFields.asMap().entrySet()) {
if (entry.getValue().getVarintList().isEmpty()) {
// Original field is not a varint, so use a varint.
bizarroFields.addField(entry.getKey(), varintField);
} else {
// Original field *is* a varint, so use something else.
bizarroFields.addField(entry.getKey(), fixed32Field);
}
}
return bizarroFields.build().toByteString();
}
Descriptors.Descriptor descriptor;
TestAllTypes allFields;
ByteString allFieldsData;
// An empty message that has been parsed from allFieldsData. So, it has
// unknown fields of every type.
TestEmptyMessage emptyMessage;
UnknownFieldSet unknownFields;
// =================================================================
public void testVarint() throws Exception {
UnknownFieldSet.Field field = getField("optional_int32");
assertEquals(1, field.getVarintList().size());
assertEquals(allFields.getOptionalInt32(),
(long) field.getVarintList().get(0));
}
public void testFixed32() throws Exception {
UnknownFieldSet.Field field = getField("optional_fixed32");
assertEquals(1, field.getFixed32List().size());
assertEquals(allFields.getOptionalFixed32(),
(int) field.getFixed32List().get(0));
}
public void testFixed64() throws Exception {
UnknownFieldSet.Field field = getField("optional_fixed64");
assertEquals(1, field.getFixed64List().size());
assertEquals(allFields.getOptionalFixed64(),
(long) field.getFixed64List().get(0));
}
public void testLengthDelimited() throws Exception {
UnknownFieldSet.Field field = getField("optional_bytes");
assertEquals(1, field.getLengthDelimitedList().size());
assertEquals(allFields.getOptionalBytes(),
field.getLengthDelimitedList().get(0));
}
public void testGroup() throws Exception {
Descriptors.FieldDescriptor nestedFieldDescriptor =
TestAllTypes.OptionalGroup.getDescriptor().findFieldByName("a");
assertNotNull(nestedFieldDescriptor);
UnknownFieldSet.Field field = getField("optionalgroup");
assertEquals(1, field.getGroupList().size());
UnknownFieldSet group = field.getGroupList().get(0);
assertEquals(1, group.asMap().size());
assertTrue(group.hasField(nestedFieldDescriptor.getNumber()));
UnknownFieldSet.Field nestedField =
group.getField(nestedFieldDescriptor.getNumber());
assertEquals(1, nestedField.getVarintList().size());
assertEquals(allFields.getOptionalGroup().getA(),
(long) nestedField.getVarintList().get(0));
}
public void testSerialize() throws Exception {
// Check that serializing the UnknownFieldSet produces the original data
// again.
ByteString data = emptyMessage.toByteString();
assertEquals(allFieldsData, data);
}
public void testCopyFrom() throws Exception {
TestEmptyMessage message =
TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).build();
assertEquals(emptyMessage.toString(), message.toString());
}
public void testMergeFrom() throws Exception {
TestEmptyMessage source =
TestEmptyMessage.newBuilder()
.setUnknownFields(
UnknownFieldSet.newBuilder()
.addField(2,
UnknownFieldSet.Field.newBuilder()
.addVarint(2).build())
.addField(3,
UnknownFieldSet.Field.newBuilder()
.addVarint(4).build())
.build())
.build();
TestEmptyMessage destination =
TestEmptyMessage.newBuilder()
.setUnknownFields(
UnknownFieldSet.newBuilder()
.addField(1,
UnknownFieldSet.Field.newBuilder()
.addVarint(1).build())
.addField(3,
UnknownFieldSet.Field.newBuilder()
.addVarint(3).build())
.build())
.mergeFrom(source)
.build();
assertEquals(
"1: 1\n" +
"2: 2\n" +
"3: 3\n" +
"3: 4\n",
destination.toString());
}
public void testClear() throws Exception {
UnknownFieldSet fields =
UnknownFieldSet.newBuilder().mergeFrom(unknownFields).clear().build();
assertTrue(fields.asMap().isEmpty());
}
public void testClearMessage() throws Exception {
TestEmptyMessage message =
TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).clear().build();
assertEquals(0, message.getSerializedSize());
}
public void testParseKnownAndUnknown() throws Exception {
// Test mixing known and unknown fields when parsing.
UnknownFieldSet fields =
UnknownFieldSet.newBuilder(unknownFields)
.addField(123456,
UnknownFieldSet.Field.newBuilder().addVarint(654321).build())
.build();
ByteString data = fields.toByteString();
TestAllTypes destination = TestAllTypes.parseFrom(data);
TestUtil.assertAllFieldsSet(destination);
assertEquals(1, destination.getUnknownFields().asMap().size());
UnknownFieldSet.Field field =
destination.getUnknownFields().getField(123456);
assertEquals(1, field.getVarintList().size());
assertEquals(654321, (long) field.getVarintList().get(0));
}
public void testWrongTypeTreatedAsUnknown() throws Exception {
// Test that fields of the wrong wire type are treated like unknown fields
// when parsing.
ByteString bizarroData = getBizarroData();
TestAllTypes allTypesMessage = TestAllTypes.parseFrom(bizarroData);
TestEmptyMessage emptyMessage = TestEmptyMessage.parseFrom(bizarroData);
// All fields should have been interpreted as unknown, so the debug strings
// should be the same.
assertEquals(emptyMessage.toString(), allTypesMessage.toString());
}
public void testUnknownExtensions() throws Exception {
// Make sure fields are properly parsed to the UnknownFieldSet even when
// they are declared as extension numbers.
TestEmptyMessageWithExtensions message =
TestEmptyMessageWithExtensions.parseFrom(allFieldsData);
assertEquals(unknownFields.asMap().size(),
message.getUnknownFields().asMap().size());
assertEquals(allFieldsData, message.toByteString());
}
public void testWrongExtensionTypeTreatedAsUnknown() throws Exception {
// Test that fields of the wrong wire type are treated like unknown fields
// when parsing extensions.
ByteString bizarroData = getBizarroData();
TestAllExtensions allExtensionsMessage =
TestAllExtensions.parseFrom(bizarroData);
TestEmptyMessage emptyMessage = TestEmptyMessage.parseFrom(bizarroData);
// All fields should have been interpreted as unknown, so the debug strings
// should be the same.
assertEquals(emptyMessage.toString(),
allExtensionsMessage.toString());
}
public void testParseUnknownEnumValue() throws Exception {
Descriptors.FieldDescriptor singularField =
TestAllTypes.getDescriptor().findFieldByName("optional_nested_enum");
Descriptors.FieldDescriptor repeatedField =
TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum");
assertNotNull(singularField);
assertNotNull(repeatedField);
ByteString data =
UnknownFieldSet.newBuilder()
.addField(singularField.getNumber(),
UnknownFieldSet.Field.newBuilder()
.addVarint(TestAllTypes.NestedEnum.BAR.getNumber())
.addVarint(5) // not valid
.build())
.addField(repeatedField.getNumber(),
UnknownFieldSet.Field.newBuilder()
.addVarint(TestAllTypes.NestedEnum.FOO.getNumber())
.addVarint(4) // not valid
.addVarint(TestAllTypes.NestedEnum.BAZ.getNumber())
.addVarint(6) // not valid
.build())
.build()
.toByteString();
{
TestAllTypes message = TestAllTypes.parseFrom(data);
assertEquals(TestAllTypes.NestedEnum.BAR,
message.getOptionalNestedEnum());
assertEquals(
Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ),
message.getRepeatedNestedEnumList());
assertEquals(Arrays.asList(5L),
message.getUnknownFields()
.getField(singularField.getNumber())
.getVarintList());
assertEquals(Arrays.asList(4L, 6L),
message.getUnknownFields()
.getField(repeatedField.getNumber())
.getVarintList());
}
{
TestAllExtensions message =
TestAllExtensions.parseFrom(data, TestUtil.getExtensionRegistry());
assertEquals(TestAllTypes.NestedEnum.BAR,
message.getExtension(UnittestProto.optionalNestedEnumExtension));
assertEquals(
Arrays.asList(TestAllTypes.NestedEnum.FOO, TestAllTypes.NestedEnum.BAZ),
message.getExtension(UnittestProto.repeatedNestedEnumExtension));
assertEquals(Arrays.asList(5L),
message.getUnknownFields()
.getField(singularField.getNumber())
.getVarintList());
assertEquals(Arrays.asList(4L, 6L),
message.getUnknownFields()
.getField(repeatedField.getNumber())
.getVarintList());
}
}
public void testLargeVarint() throws Exception {
ByteString data =
UnknownFieldSet.newBuilder()
.addField(1,
UnknownFieldSet.Field.newBuilder()
.addVarint(0x7FFFFFFFFFFFFFFFL)
.build())
.build()
.toByteString();
UnknownFieldSet parsed = UnknownFieldSet.parseFrom(data);
UnknownFieldSet.Field field = parsed.getField(1);
assertEquals(1, field.getVarintList().size());
assertEquals(0x7FFFFFFFFFFFFFFFL, (long)field.getVarintList().get(0));
}
public void testEqualsAndHashCode() {
UnknownFieldSet.Field fixed32Field =
UnknownFieldSet.Field.newBuilder()
.addFixed32(1)
.build();
UnknownFieldSet.Field fixed64Field =
UnknownFieldSet.Field.newBuilder()
.addFixed64(1)
.build();
UnknownFieldSet.Field varIntField =
UnknownFieldSet.Field.newBuilder()
.addVarint(1)
.build();
UnknownFieldSet.Field lengthDelimitedField =
UnknownFieldSet.Field.newBuilder()
.addLengthDelimited(ByteString.EMPTY)
.build();
UnknownFieldSet.Field groupField =
UnknownFieldSet.Field.newBuilder()
.addGroup(unknownFields)
.build();
UnknownFieldSet a =
UnknownFieldSet.newBuilder()
.addField(1, fixed32Field)
.build();
UnknownFieldSet b =
UnknownFieldSet.newBuilder()
.addField(1, fixed64Field)
.build();
UnknownFieldSet c =
UnknownFieldSet.newBuilder()
.addField(1, varIntField)
.build();
UnknownFieldSet d =
UnknownFieldSet.newBuilder()
.addField(1, lengthDelimitedField)
.build();
UnknownFieldSet e =
UnknownFieldSet.newBuilder()
.addField(1, groupField)
.build();
checkEqualsIsConsistent(a);
checkEqualsIsConsistent(b);
checkEqualsIsConsistent(c);
checkEqualsIsConsistent(d);
checkEqualsIsConsistent(e);
checkNotEqual(a, b);
checkNotEqual(a, c);
checkNotEqual(a, d);
checkNotEqual(a, e);
checkNotEqual(b, c);
checkNotEqual(b, d);
checkNotEqual(b, e);
checkNotEqual(c, d);
checkNotEqual(c, e);
checkNotEqual(d, e);
}
/**
* Asserts that the given field sets are not equal and have different
* hash codes.
*
* @warning It's valid for non-equal objects to have the same hash code, so
* this test is stricter than it needs to be. However, this should happen
* relatively rarely.
*/
private void checkNotEqual(UnknownFieldSet s1, UnknownFieldSet s2) {
String equalsError = String.format("%s should not be equal to %s", s1, s2);
assertFalse(equalsError, s1.equals(s2));
assertFalse(equalsError, s2.equals(s1));
assertFalse(
String.format("%s should have a different hash code from %s", s1, s2),
s1.hashCode() == s2.hashCode());
}
/**
* Asserts that the given field sets are equal and have identical hash codes.
*/
private void checkEqualsIsConsistent(UnknownFieldSet set) {
// Object should be equal to itself.
assertEquals(set, set);
// Object should be equal to a copy of itself.
UnknownFieldSet copy = UnknownFieldSet.newBuilder(set).build();
assertEquals(set, copy);
assertEquals(copy, set);
assertEquals(set.hashCode(), copy.hashCode());
}
}

@ -1,153 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import junit.framework.TestCase;
import java.util.Iterator;
import java.util.ListIterator;
/**
* Tests for {@link UnmodifiableLazyStringList}.
*
* @author jonp@google.com (Jon Perlow)
*/
public class UnmodifiableLazyStringListTest extends TestCase {
private static String STRING_A = "A";
private static String STRING_B = "B";
private static String STRING_C = "C";
private static ByteString BYTE_STRING_A = ByteString.copyFromUtf8("A");
private static ByteString BYTE_STRING_B = ByteString.copyFromUtf8("B");
private static ByteString BYTE_STRING_C = ByteString.copyFromUtf8("C");
public void testReadOnlyMethods() {
LazyStringArrayList rawList = createSampleList();
UnmodifiableLazyStringList list = new UnmodifiableLazyStringList(rawList);
assertEquals(3, list.size());
assertSame(STRING_A, list.get(0));
assertSame(STRING_B, list.get(1));
assertSame(STRING_C, list.get(2));
assertEquals(BYTE_STRING_A, list.getByteString(0));
assertEquals(BYTE_STRING_B, list.getByteString(1));
assertEquals(BYTE_STRING_C, list.getByteString(2));
}
public void testModifyMethods() {
LazyStringArrayList rawList = createSampleList();
UnmodifiableLazyStringList list = new UnmodifiableLazyStringList(rawList);
try {
list.remove(0);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
assertEquals(3, list.size());
try {
list.add(STRING_B);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
assertEquals(3, list.size());
try {
list.set(1, STRING_B);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
}
public void testIterator() {
LazyStringArrayList rawList = createSampleList();
UnmodifiableLazyStringList list = new UnmodifiableLazyStringList(rawList);
Iterator<String> iter = list.iterator();
int count = 0;
while (iter.hasNext()) {
iter.next();
count++;
try {
iter.remove();
fail();
} catch (UnsupportedOperationException e) {
// expected
}
}
assertEquals(3, count);
}
public void testListIterator() {
LazyStringArrayList rawList = createSampleList();
UnmodifiableLazyStringList list = new UnmodifiableLazyStringList(rawList);
ListIterator<String> iter = list.listIterator();
int count = 0;
while (iter.hasNext()) {
iter.next();
count++;
try {
iter.remove();
fail();
} catch (UnsupportedOperationException e) {
// expected
}
try {
iter.set("bar");
fail();
} catch (UnsupportedOperationException e) {
// expected
}
try {
iter.add("bar");
fail();
} catch (UnsupportedOperationException e) {
// expected
}
}
assertEquals(3, count);
}
private LazyStringArrayList createSampleList() {
LazyStringArrayList rawList = new LazyStringArrayList();
rawList.add(STRING_A);
rawList.add(STRING_B);
rawList.add(STRING_C);
return rawList;
}
}

@ -1,465 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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.test;
import com.google.protobuf.*;
import junit.framework.TestCase;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import protobuf_unittest.UnittestProto;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestFieldOrderings;
import protobuf_unittest.UnittestProto.TestPackedExtensions;
import protobuf_unittest.UnittestProto.TestPackedTypes;
import protobuf_unittest.UnittestMset.TestMessageSet;
import protobuf_unittest.UnittestMset.RawMessageSet;
import protobuf_unittest.UnittestMset.TestMessageSetExtension1;
import protobuf_unittest.UnittestMset.TestMessageSetExtension2;
/**
* Tests related to parsing and serialization.
*
* @author kenton@google.com (Kenton Varda)
*/
public class WireFormatTest extends TestCase {
public void testSerialization() throws Exception {
TestAllTypes message = TestUtil.getAllSet();
ByteString rawBytes = message.toByteString();
assertEquals(rawBytes.size(), message.getSerializedSize());
TestAllTypes message2 = TestAllTypes.parseFrom(rawBytes);
TestUtil.assertAllFieldsSet(message2);
}
public void testSerializationPacked() throws Exception {
TestPackedTypes message = TestUtil.getPackedSet();
ByteString rawBytes = message.toByteString();
assertEquals(rawBytes.size(), message.getSerializedSize());
TestPackedTypes message2 = TestPackedTypes.parseFrom(rawBytes);
TestUtil.assertPackedFieldsSet(message2);
}
public void testSerializeExtensions() throws Exception {
// TestAllTypes and TestAllExtensions should have compatible wire formats,
// so if we serialize a TestAllExtensions then parse it as TestAllTypes
// it should work.
TestAllExtensions message = TestUtil.getAllExtensionsSet();
ByteString rawBytes = message.toByteString();
assertEquals(rawBytes.size(), message.getSerializedSize());
TestAllTypes message2 = TestAllTypes.parseFrom(rawBytes);
TestUtil.assertAllFieldsSet(message2);
}
public void testSerializePackedExtensions() throws Exception {
// TestPackedTypes and TestPackedExtensions should have compatible wire
// formats; check that they serialize to the same string.
TestPackedExtensions message = TestUtil.getPackedExtensionsSet();
ByteString rawBytes = message.toByteString();
TestPackedTypes message2 = TestUtil.getPackedSet();
ByteString rawBytes2 = message2.toByteString();
assertEquals(rawBytes, rawBytes2);
}
public void testSerializationPackedWithoutGetSerializedSize()
throws Exception {
// Write directly to an OutputStream, without invoking getSerializedSize()
// This used to be a bug where the size of a packed field was incorrect,
// since getSerializedSize() was never invoked.
TestPackedTypes message = TestUtil.getPackedSet();
// Directly construct a CodedOutputStream around the actual OutputStream,
// in case writeTo(OutputStream output) invokes getSerializedSize();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CodedOutputStream codedOutput = CodedOutputStream.newInstance(outputStream);
message.writeTo(codedOutput);
codedOutput.flush();
TestPackedTypes message2 = TestPackedTypes.parseFrom(
outputStream.toByteArray());
TestUtil.assertPackedFieldsSet(message2);
}
public void testParseExtensions() throws Exception {
// TestAllTypes and TestAllExtensions should have compatible wire formats,
// so if we serialize a TestAllTypes then parse it as TestAllExtensions
// it should work.
TestAllTypes message = TestUtil.getAllSet();
ByteString rawBytes = message.toByteString();
ExtensionRegistry registry = TestUtil.getExtensionRegistry();
TestAllExtensions message2 =
TestAllExtensions.parseFrom(rawBytes, registry);
TestUtil.assertAllExtensionsSet(message2);
}
public void testParsePackedExtensions() throws Exception {
// Ensure that packed extensions can be properly parsed.
TestPackedExtensions message = TestUtil.getPackedExtensionsSet();
ByteString rawBytes = message.toByteString();
ExtensionRegistry registry = TestUtil.getExtensionRegistry();
TestPackedExtensions message2 =
TestPackedExtensions.parseFrom(rawBytes, registry);
TestUtil.assertPackedExtensionsSet(message2);
}
public void testExtensionsSerializedSize() throws Exception {
assertEquals(TestUtil.getAllSet().getSerializedSize(),
TestUtil.getAllExtensionsSet().getSerializedSize());
}
public void testSerializeDelimited() throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream();
TestUtil.getAllSet().writeDelimitedTo(output);
output.write(12);
TestUtil.getPackedSet().writeDelimitedTo(output);
output.write(34);
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
TestUtil.assertAllFieldsSet(TestAllTypes.parseDelimitedFrom(input));
assertEquals(12, input.read());
TestUtil.assertPackedFieldsSet(TestPackedTypes.parseDelimitedFrom(input));
assertEquals(34, input.read());
assertEquals(-1, input.read());
// We're at EOF, so parsing again should return null.
assertTrue(TestAllTypes.parseDelimitedFrom(input) == null);
}
private void assertFieldsInOrder(ByteString data) throws Exception {
CodedInputStream input = data.newCodedInput();
int previousTag = 0;
while (true) {
int tag = input.readTag();
if (tag == 0) {
break;
}
assertTrue(tag > previousTag);
previousTag = tag;
input.skipField(tag);
}
}
public void testInterleavedFieldsAndExtensions() throws Exception {
// Tests that fields are written in order even when extension ranges
// are interleaved with field numbers.
ByteString data =
TestFieldOrderings.newBuilder()
.setMyInt(1)
.setMyString("foo")
.setMyFloat(1.0F)
.setExtension(UnittestProto.myExtensionInt, 23)
.setExtension(UnittestProto.myExtensionString, "bar")
.build().toByteString();
assertFieldsInOrder(data);
Descriptors.Descriptor descriptor = TestFieldOrderings.getDescriptor();
ByteString dynamic_data =
DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor())
.setField(descriptor.findFieldByName("my_int"), 1L)
.setField(descriptor.findFieldByName("my_string"), "foo")
.setField(descriptor.findFieldByName("my_float"), 1.0F)
.setField(UnittestProto.myExtensionInt.getDescriptor(), 23)
.setField(UnittestProto.myExtensionString.getDescriptor(), "bar")
.build().toByteString();
assertFieldsInOrder(dynamic_data);
}
private ExtensionRegistry getTestFieldOrderingsRegistry() {
ExtensionRegistry result = ExtensionRegistry.newInstance();
result.add(UnittestProto.myExtensionInt);
result.add(UnittestProto.myExtensionString);
return result;
}
public void testParseMultipleExtensionRanges() throws Exception {
// Make sure we can parse a message that contains multiple extensions
// ranges.
TestFieldOrderings source =
TestFieldOrderings.newBuilder()
.setMyInt(1)
.setMyString("foo")
.setMyFloat(1.0F)
.setExtension(UnittestProto.myExtensionInt, 23)
.setExtension(UnittestProto.myExtensionString, "bar")
.build();
TestFieldOrderings dest =
TestFieldOrderings.parseFrom(source.toByteString(),
getTestFieldOrderingsRegistry());
assertEquals(source, dest);
}
public void testParseMultipleExtensionRangesDynamic() throws Exception {
// Same as above except with DynamicMessage.
Descriptors.Descriptor descriptor = TestFieldOrderings.getDescriptor();
DynamicMessage source =
DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor())
.setField(descriptor.findFieldByName("my_int"), 1L)
.setField(descriptor.findFieldByName("my_string"), "foo")
.setField(descriptor.findFieldByName("my_float"), 1.0F)
.setField(UnittestProto.myExtensionInt.getDescriptor(), 23)
.setField(UnittestProto.myExtensionString.getDescriptor(), "bar")
.build();
DynamicMessage dest =
DynamicMessage.parseFrom(descriptor, source.toByteString(),
getTestFieldOrderingsRegistry());
assertEquals(source, dest);
}
private static final int UNKNOWN_TYPE_ID = 1550055;
private static final int TYPE_ID_1 =
TestMessageSetExtension1.getDescriptor().getExtensions().get(0).getNumber();
private static final int TYPE_ID_2 =
TestMessageSetExtension2.getDescriptor().getExtensions().get(0).getNumber();
public void testSerializeMessageSetEagerly() throws Exception {
testSerializeMessageSetWithFlag(true);
}
public void testSerializeMessageSetNotEagerly() throws Exception {
testSerializeMessageSetWithFlag(false);
}
private void testSerializeMessageSetWithFlag(boolean eagerParsing)
throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
// Set up a TestMessageSet with two known messages and an unknown one.
TestMessageSet messageSet =
TestMessageSet.newBuilder()
.setExtension(
TestMessageSetExtension1.messageSetExtension,
TestMessageSetExtension1.newBuilder().setI(123).build())
.setExtension(
TestMessageSetExtension2.messageSetExtension,
TestMessageSetExtension2.newBuilder().setStr("foo").build())
.setUnknownFields(
UnknownFieldSet.newBuilder()
.addField(UNKNOWN_TYPE_ID,
UnknownFieldSet.Field.newBuilder()
.addLengthDelimited(ByteString.copyFromUtf8("bar"))
.build())
.build())
.build();
ByteString data = messageSet.toByteString();
// Parse back using RawMessageSet and check the contents.
RawMessageSet raw = RawMessageSet.parseFrom(data);
assertTrue(raw.getUnknownFields().asMap().isEmpty());
assertEquals(3, raw.getItemCount());
assertEquals(TYPE_ID_1, raw.getItem(0).getTypeId());
assertEquals(TYPE_ID_2, raw.getItem(1).getTypeId());
assertEquals(UNKNOWN_TYPE_ID, raw.getItem(2).getTypeId());
TestMessageSetExtension1 message1 =
TestMessageSetExtension1.parseFrom(
raw.getItem(0).getMessage().toByteArray());
assertEquals(123, message1.getI());
TestMessageSetExtension2 message2 =
TestMessageSetExtension2.parseFrom(
raw.getItem(1).getMessage().toByteArray());
assertEquals("foo", message2.getStr());
assertEquals("bar", raw.getItem(2).getMessage().toStringUtf8());
}
public void testParseMessageSetEagerly() throws Exception {
testParseMessageSetWithFlag(true);
}
public void testParseMessageSetNotEagerly()throws Exception {
testParseMessageSetWithFlag(false);
}
private void testParseMessageSetWithFlag(boolean eagerParsing)
throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
extensionRegistry.add(TestMessageSetExtension2.messageSetExtension);
// Set up a RawMessageSet with two known messages and an unknown one.
RawMessageSet raw =
RawMessageSet.newBuilder()
.addItem(
RawMessageSet.Item.newBuilder()
.setTypeId(TYPE_ID_1)
.setMessage(
TestMessageSetExtension1.newBuilder()
.setI(123)
.build().toByteString())
.build())
.addItem(
RawMessageSet.Item.newBuilder()
.setTypeId(TYPE_ID_2)
.setMessage(
TestMessageSetExtension2.newBuilder()
.setStr("foo")
.build().toByteString())
.build())
.addItem(
RawMessageSet.Item.newBuilder()
.setTypeId(UNKNOWN_TYPE_ID)
.setMessage(ByteString.copyFromUtf8("bar"))
.build())
.build();
ByteString data = raw.toByteString();
// Parse as a TestMessageSet and check the contents.
TestMessageSet messageSet =
TestMessageSet.parseFrom(data, extensionRegistry);
assertEquals(123, messageSet.getExtension(
TestMessageSetExtension1.messageSetExtension).getI());
assertEquals("foo", messageSet.getExtension(
TestMessageSetExtension2.messageSetExtension).getStr());
// Check for unknown field with type LENGTH_DELIMITED,
// number UNKNOWN_TYPE_ID, and contents "bar".
UnknownFieldSet unknownFields = messageSet.getUnknownFields();
assertEquals(1, unknownFields.asMap().size());
assertTrue(unknownFields.hasField(UNKNOWN_TYPE_ID));
UnknownFieldSet.Field field = unknownFields.getField(UNKNOWN_TYPE_ID);
assertEquals(1, field.getLengthDelimitedList().size());
assertEquals("bar", field.getLengthDelimitedList().get(0).toStringUtf8());
}
public void testParseMessageSetExtensionEagerly() throws Exception {
testParseMessageSetExtensionWithFlag(true);
}
public void testParseMessageSetExtensionNotEagerly() throws Exception {
testParseMessageSetExtensionWithFlag(false);
}
private void testParseMessageSetExtensionWithFlag(boolean eagerParsing)
throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
// Set up a RawMessageSet with a known messages.
int TYPE_ID_1 =
TestMessageSetExtension1
.getDescriptor().getExtensions().get(0).getNumber();
RawMessageSet raw =
RawMessageSet.newBuilder()
.addItem(
RawMessageSet.Item.newBuilder()
.setTypeId(TYPE_ID_1)
.setMessage(
TestMessageSetExtension1.newBuilder()
.setI(123)
.build().toByteString())
.build())
.build();
ByteString data = raw.toByteString();
// Parse as a TestMessageSet and check the contents.
TestMessageSet messageSet =
TestMessageSet.parseFrom(data, extensionRegistry);
assertEquals(123, messageSet.getExtension(
TestMessageSetExtension1.messageSetExtension).getI());
}
public void testMergeLazyMessageSetExtensionEagerly() throws Exception {
testMergeLazyMessageSetExtensionWithFlag(true);
}
public void testMergeLazyMessageSetExtensionNotEagerly() throws Exception {
testMergeLazyMessageSetExtensionWithFlag(false);
}
private void testMergeLazyMessageSetExtensionWithFlag(boolean eagerParsing)
throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
// Set up a RawMessageSet with a known messages.
int TYPE_ID_1 =
TestMessageSetExtension1
.getDescriptor().getExtensions().get(0).getNumber();
RawMessageSet raw =
RawMessageSet.newBuilder()
.addItem(
RawMessageSet.Item.newBuilder()
.setTypeId(TYPE_ID_1)
.setMessage(
TestMessageSetExtension1.newBuilder()
.setI(123)
.build().toByteString())
.build())
.build();
ByteString data = raw.toByteString();
// Parse as a TestMessageSet and store value into lazy field
TestMessageSet messageSet =
TestMessageSet.parseFrom(data, extensionRegistry);
// Merge lazy field check the contents.
messageSet =
messageSet.toBuilder().mergeFrom(data, extensionRegistry).build();
assertEquals(123, messageSet.getExtension(
TestMessageSetExtension1.messageSetExtension).getI());
}
}

@ -1,17 +0,0 @@
#!/bin/bash
#
# This is the top-level script we give to Kokoro as the entry point for
# running the "pull request" project:
#
# This script selects a specific Dockerfile (for building a Docker image) and
# a script to run inside that image. Then we delegate to the general
# build_and_run_docker.sh script.
# Change to repo root
cd $(dirname $0)/../../..
export DOCKERFILE_DIR=kokoro/linux/64-bit
export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
export OUTPUT_DIR=testoutput
export TEST_SET="java_compatibility"
./kokoro/linux/build_and_run_docker.sh

@ -1,5 +0,0 @@
# Config file for running tests in Kokoro
# Location of the build script in repository
build_file: "protobuf/kokoro/linux/java_compatibility/build.sh"
timeout_mins: 1440

@ -1,5 +0,0 @@
# Config file for running tests in Kokoro
# Location of the build script in repository
build_file: "protobuf/kokoro/linux/java_compatibility/build.sh"
timeout_mins: 1440

@ -62,7 +62,7 @@ build_cpp_distcheck() {
# List all files that should be included in the distribution package.
git ls-files | grep "^\(java\|python\|objectivec\|csharp\|js\|ruby\|php\|cmake\|examples\|src/google/protobuf/.*\.proto\)" |\
grep -v ".gitignore" | grep -v "java/compatibility_tests" | grep -v "java/lite/proguard.pgcfg" |\
grep -v ".gitignore" | grep -v "java/lite/proguard.pgcfg" |\
grep -v "python/compatibility_tests" | grep -v "python/docs" | grep -v "python/.repo-metadata.json" |\
grep -v "python/protobuf_distutils" | grep -v "csharp/compatibility_tests" > dist.lst
# Unzip the dist tar file.
@ -234,17 +234,6 @@ build_java_oracle7() {
use_java oracle7
build_java oracle7
}
build_java_compatibility() {
use_java jdk7
internal_build_cpp
# Use the unit-tests extracted from 2.5.0 to test the compatibility between
# 3.0.0-beta-4 and the current version.
cd java/compatibility_tests/v2.5.0
./test.sh 3.0.0-beta-4
# Test the last released and current version.
./test.sh $LAST_RELEASED
}
build_java_linkage_monitor() {
# Linkage Monitor checks compatibility with other Google libraries
# https://github.com/GoogleCloudPlatform/cloud-opensource-java/tree/master/linkage-monitor
@ -728,7 +717,6 @@ Usage: $0 { cpp |
csharp |
java_jdk7 |
java_oracle7 |
java_compatibility |
java_linkage_monitor |
objectivec_ios |
objectivec_ios_debug |

Loading…
Cancel
Save