PageRenderTime 124ms CodeModel.GetById 90ms app.highlight 27ms RepoModel.GetById 1ms app.codeStats 1ms

/thirdparty/breakpad/third_party/protobuf/protobuf/java/src/test/java/com/google/protobuf/DescriptorsTest.java

http://github.com/tomahawk-player/tomahawk
Java | 460 lines | 345 code | 64 blank | 51 comment | 16 complexity | 6c9aecc21a8c0d8f5577c6e5d6abce14 MD5 | raw file
  1// Protocol Buffers - Google's data interchange format
  2// Copyright 2008 Google Inc.  All rights reserved.
  3// http://code.google.com/p/protobuf/
  4//
  5// Redistribution and use in source and binary forms, with or without
  6// modification, are permitted provided that the following conditions are
  7// met:
  8//
  9//     * Redistributions of source code must retain the above copyright
 10// notice, this list of conditions and the following disclaimer.
 11//     * Redistributions in binary form must reproduce the above
 12// copyright notice, this list of conditions and the following disclaimer
 13// in the documentation and/or other materials provided with the
 14// distribution.
 15//     * Neither the name of Google Inc. nor the names of its
 16// contributors may be used to endorse or promote products derived from
 17// this software without specific prior written permission.
 18//
 19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 30
 31package com.google.protobuf;
 32
 33import com.google.protobuf.DescriptorProtos.DescriptorProto;
 34import com.google.protobuf.DescriptorProtos.FieldDescriptorProto;
 35import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
 36import com.google.protobuf.Descriptors.DescriptorValidationException;
 37import com.google.protobuf.Descriptors.FileDescriptor;
 38import com.google.protobuf.Descriptors.Descriptor;
 39import com.google.protobuf.Descriptors.FieldDescriptor;
 40import com.google.protobuf.Descriptors.EnumDescriptor;
 41import com.google.protobuf.Descriptors.EnumValueDescriptor;
 42import com.google.protobuf.Descriptors.ServiceDescriptor;
 43import com.google.protobuf.Descriptors.MethodDescriptor;
 44
 45import com.google.protobuf.test.UnittestImport;
 46import com.google.protobuf.test.UnittestImport.ImportEnum;
 47import com.google.protobuf.test.UnittestImport.ImportMessage;
 48import protobuf_unittest.UnittestProto;
 49import protobuf_unittest.UnittestProto.ForeignEnum;
 50import protobuf_unittest.UnittestProto.ForeignMessage;
 51import protobuf_unittest.UnittestProto.TestAllTypes;
 52import protobuf_unittest.UnittestProto.TestAllExtensions;
 53import protobuf_unittest.UnittestProto.TestExtremeDefaultValues;
 54import protobuf_unittest.UnittestProto.TestRequired;
 55import protobuf_unittest.UnittestProto.TestService;
 56import protobuf_unittest.UnittestCustomOptions;
 57
 58
 59import junit.framework.TestCase;
 60
 61import java.util.Arrays;
 62import java.util.Collections;
 63
 64/**
 65 * Unit test for {@link Descriptors}.
 66 *
 67 * @author kenton@google.com Kenton Varda
 68 */
 69public class DescriptorsTest extends TestCase {
 70
 71  // Regression test for bug where referencing a FieldDescriptor.Type value
 72  // before a FieldDescriptorProto.Type value would yield a
 73  // ExceptionInInitializerError.
 74  @SuppressWarnings("unused")
 75  private static final Object STATIC_INIT_TEST = FieldDescriptor.Type.BOOL;
 76
 77  public void testFieldTypeEnumMapping() throws Exception {
 78    assertEquals(FieldDescriptor.Type.values().length,
 79        FieldDescriptorProto.Type.values().length);
 80    for (FieldDescriptor.Type type : FieldDescriptor.Type.values()) {
 81      FieldDescriptorProto.Type protoType = type.toProto();
 82      assertEquals("TYPE_" + type.name(), protoType.name());
 83      assertEquals(type, FieldDescriptor.Type.valueOf(protoType));
 84    }
 85  }
 86
 87  public void testFileDescriptor() throws Exception {
 88    FileDescriptor file = UnittestProto.getDescriptor();
 89
 90    assertEquals("google/protobuf/unittest.proto", file.getName());
 91    assertEquals("protobuf_unittest", file.getPackage());
 92
 93    assertEquals("UnittestProto", file.getOptions().getJavaOuterClassname());
 94    assertEquals("google/protobuf/unittest.proto",
 95                 file.toProto().getName());
 96
 97    assertEquals(Arrays.asList(UnittestImport.getDescriptor()),
 98                 file.getDependencies());
 99
100    Descriptor messageType = TestAllTypes.getDescriptor();
101    assertEquals(messageType, file.getMessageTypes().get(0));
102    assertEquals(messageType, file.findMessageTypeByName("TestAllTypes"));
103    assertNull(file.findMessageTypeByName("NoSuchType"));
104    assertNull(file.findMessageTypeByName("protobuf_unittest.TestAllTypes"));
105    for (int i = 0; i < file.getMessageTypes().size(); i++) {
106      assertEquals(i, file.getMessageTypes().get(i).getIndex());
107    }
108
109    EnumDescriptor enumType = ForeignEnum.getDescriptor();
110    assertEquals(enumType, file.getEnumTypes().get(0));
111    assertEquals(enumType, file.findEnumTypeByName("ForeignEnum"));
112    assertNull(file.findEnumTypeByName("NoSuchType"));
113    assertNull(file.findEnumTypeByName("protobuf_unittest.ForeignEnum"));
114    assertEquals(Arrays.asList(ImportEnum.getDescriptor()),
115                 UnittestImport.getDescriptor().getEnumTypes());
116    for (int i = 0; i < file.getEnumTypes().size(); i++) {
117      assertEquals(i, file.getEnumTypes().get(i).getIndex());
118    }
119
120    ServiceDescriptor service = TestService.getDescriptor();
121    assertEquals(service, file.getServices().get(0));
122    assertEquals(service, file.findServiceByName("TestService"));
123    assertNull(file.findServiceByName("NoSuchType"));
124    assertNull(file.findServiceByName("protobuf_unittest.TestService"));
125    assertEquals(Collections.emptyList(),
126                 UnittestImport.getDescriptor().getServices());
127    for (int i = 0; i < file.getServices().size(); i++) {
128      assertEquals(i, file.getServices().get(i).getIndex());
129    }
130
131    FieldDescriptor extension =
132      UnittestProto.optionalInt32Extension.getDescriptor();
133    assertEquals(extension, file.getExtensions().get(0));
134    assertEquals(extension,
135                 file.findExtensionByName("optional_int32_extension"));
136    assertNull(file.findExtensionByName("no_such_ext"));
137    assertNull(file.findExtensionByName(
138      "protobuf_unittest.optional_int32_extension"));
139    assertEquals(Collections.emptyList(),
140                 UnittestImport.getDescriptor().getExtensions());
141    for (int i = 0; i < file.getExtensions().size(); i++) {
142      assertEquals(i, file.getExtensions().get(i).getIndex());
143    }
144  }
145
146  public void testDescriptor() throws Exception {
147    Descriptor messageType = TestAllTypes.getDescriptor();
148    Descriptor nestedType = TestAllTypes.NestedMessage.getDescriptor();
149
150    assertEquals("TestAllTypes", messageType.getName());
151    assertEquals("protobuf_unittest.TestAllTypes", messageType.getFullName());
152    assertEquals(UnittestProto.getDescriptor(), messageType.getFile());
153    assertNull(messageType.getContainingType());
154    assertEquals(DescriptorProtos.MessageOptions.getDefaultInstance(),
155                 messageType.getOptions());
156    assertEquals("TestAllTypes", messageType.toProto().getName());
157
158    assertEquals("NestedMessage", nestedType.getName());
159    assertEquals("protobuf_unittest.TestAllTypes.NestedMessage",
160                 nestedType.getFullName());
161    assertEquals(UnittestProto.getDescriptor(), nestedType.getFile());
162    assertEquals(messageType, nestedType.getContainingType());
163
164    FieldDescriptor field = messageType.getFields().get(0);
165    assertEquals("optional_int32", field.getName());
166    assertEquals(field, messageType.findFieldByName("optional_int32"));
167    assertNull(messageType.findFieldByName("no_such_field"));
168    assertEquals(field, messageType.findFieldByNumber(1));
169    assertNull(messageType.findFieldByNumber(571283));
170    for (int i = 0; i < messageType.getFields().size(); i++) {
171      assertEquals(i, messageType.getFields().get(i).getIndex());
172    }
173
174    assertEquals(nestedType, messageType.getNestedTypes().get(0));
175    assertEquals(nestedType, messageType.findNestedTypeByName("NestedMessage"));
176    assertNull(messageType.findNestedTypeByName("NoSuchType"));
177    for (int i = 0; i < messageType.getNestedTypes().size(); i++) {
178      assertEquals(i, messageType.getNestedTypes().get(i).getIndex());
179    }
180
181    EnumDescriptor enumType = TestAllTypes.NestedEnum.getDescriptor();
182    assertEquals(enumType, messageType.getEnumTypes().get(0));
183    assertEquals(enumType, messageType.findEnumTypeByName("NestedEnum"));
184    assertNull(messageType.findEnumTypeByName("NoSuchType"));
185    for (int i = 0; i < messageType.getEnumTypes().size(); i++) {
186      assertEquals(i, messageType.getEnumTypes().get(i).getIndex());
187    }
188  }
189
190  public void testFieldDescriptor() throws Exception {
191    Descriptor messageType = TestAllTypes.getDescriptor();
192    FieldDescriptor primitiveField =
193      messageType.findFieldByName("optional_int32");
194    FieldDescriptor enumField =
195      messageType.findFieldByName("optional_nested_enum");
196    FieldDescriptor messageField =
197      messageType.findFieldByName("optional_foreign_message");
198    FieldDescriptor cordField =
199      messageType.findFieldByName("optional_cord");
200    FieldDescriptor extension =
201      UnittestProto.optionalInt32Extension.getDescriptor();
202    FieldDescriptor nestedExtension = TestRequired.single.getDescriptor();
203
204    assertEquals("optional_int32", primitiveField.getName());
205    assertEquals("protobuf_unittest.TestAllTypes.optional_int32",
206                 primitiveField.getFullName());
207    assertEquals(1, primitiveField.getNumber());
208    assertEquals(messageType, primitiveField.getContainingType());
209    assertEquals(UnittestProto.getDescriptor(), primitiveField.getFile());
210    assertEquals(FieldDescriptor.Type.INT32, primitiveField.getType());
211    assertEquals(FieldDescriptor.JavaType.INT, primitiveField.getJavaType());
212    assertEquals(DescriptorProtos.FieldOptions.getDefaultInstance(),
213                 primitiveField.getOptions());
214    assertFalse(primitiveField.isExtension());
215    assertEquals("optional_int32", primitiveField.toProto().getName());
216
217    assertEquals("optional_nested_enum", enumField.getName());
218    assertEquals(FieldDescriptor.Type.ENUM, enumField.getType());
219    assertEquals(FieldDescriptor.JavaType.ENUM, enumField.getJavaType());
220    assertEquals(TestAllTypes.NestedEnum.getDescriptor(),
221                 enumField.getEnumType());
222
223    assertEquals("optional_foreign_message", messageField.getName());
224    assertEquals(FieldDescriptor.Type.MESSAGE, messageField.getType());
225    assertEquals(FieldDescriptor.JavaType.MESSAGE, messageField.getJavaType());
226    assertEquals(ForeignMessage.getDescriptor(), messageField.getMessageType());
227
228    assertEquals("optional_cord", cordField.getName());
229    assertEquals(FieldDescriptor.Type.STRING, cordField.getType());
230    assertEquals(FieldDescriptor.JavaType.STRING, cordField.getJavaType());
231    assertEquals(DescriptorProtos.FieldOptions.CType.CORD,
232                 cordField.getOptions().getCtype());
233
234    assertEquals("optional_int32_extension", extension.getName());
235    assertEquals("protobuf_unittest.optional_int32_extension",
236                 extension.getFullName());
237    assertEquals(1, extension.getNumber());
238    assertEquals(TestAllExtensions.getDescriptor(),
239                 extension.getContainingType());
240    assertEquals(UnittestProto.getDescriptor(), extension.getFile());
241    assertEquals(FieldDescriptor.Type.INT32, extension.getType());
242    assertEquals(FieldDescriptor.JavaType.INT, extension.getJavaType());
243    assertEquals(DescriptorProtos.FieldOptions.getDefaultInstance(),
244                 extension.getOptions());
245    assertTrue(extension.isExtension());
246    assertEquals(null, extension.getExtensionScope());
247    assertEquals("optional_int32_extension", extension.toProto().getName());
248
249    assertEquals("single", nestedExtension.getName());
250    assertEquals("protobuf_unittest.TestRequired.single",
251                 nestedExtension.getFullName());
252    assertEquals(TestRequired.getDescriptor(),
253                 nestedExtension.getExtensionScope());
254  }
255
256  public void testFieldDescriptorLabel() throws Exception {
257    FieldDescriptor requiredField =
258      TestRequired.getDescriptor().findFieldByName("a");
259    FieldDescriptor optionalField =
260      TestAllTypes.getDescriptor().findFieldByName("optional_int32");
261    FieldDescriptor repeatedField =
262      TestAllTypes.getDescriptor().findFieldByName("repeated_int32");
263
264    assertTrue(requiredField.isRequired());
265    assertFalse(requiredField.isRepeated());
266    assertFalse(optionalField.isRequired());
267    assertFalse(optionalField.isRepeated());
268    assertFalse(repeatedField.isRequired());
269    assertTrue(repeatedField.isRepeated());
270  }
271
272  public void testFieldDescriptorDefault() throws Exception {
273    Descriptor d = TestAllTypes.getDescriptor();
274    assertFalse(d.findFieldByName("optional_int32").hasDefaultValue());
275    assertEquals(0, d.findFieldByName("optional_int32").getDefaultValue());
276    assertTrue(d.findFieldByName("default_int32").hasDefaultValue());
277    assertEquals(41, d.findFieldByName("default_int32").getDefaultValue());
278
279    d = TestExtremeDefaultValues.getDescriptor();
280    assertEquals(
281      ByteString.copyFrom(
282        "\0\001\007\b\f\n\r\t\013\\\'\"\u00fe".getBytes("ISO-8859-1")),
283      d.findFieldByName("escaped_bytes").getDefaultValue());
284    assertEquals(-1, d.findFieldByName("large_uint32").getDefaultValue());
285    assertEquals(-1L, d.findFieldByName("large_uint64").getDefaultValue());
286  }
287
288  public void testEnumDescriptor() throws Exception {
289    EnumDescriptor enumType = ForeignEnum.getDescriptor();
290    EnumDescriptor nestedType = TestAllTypes.NestedEnum.getDescriptor();
291
292    assertEquals("ForeignEnum", enumType.getName());
293    assertEquals("protobuf_unittest.ForeignEnum", enumType.getFullName());
294    assertEquals(UnittestProto.getDescriptor(), enumType.getFile());
295    assertNull(enumType.getContainingType());
296    assertEquals(DescriptorProtos.EnumOptions.getDefaultInstance(),
297                 enumType.getOptions());
298
299    assertEquals("NestedEnum", nestedType.getName());
300    assertEquals("protobuf_unittest.TestAllTypes.NestedEnum",
301                 nestedType.getFullName());
302    assertEquals(UnittestProto.getDescriptor(), nestedType.getFile());
303    assertEquals(TestAllTypes.getDescriptor(), nestedType.getContainingType());
304
305    EnumValueDescriptor value = ForeignEnum.FOREIGN_FOO.getValueDescriptor();
306    assertEquals(value, enumType.getValues().get(0));
307    assertEquals("FOREIGN_FOO", value.getName());
308    assertEquals(4, value.getNumber());
309    assertEquals(value, enumType.findValueByName("FOREIGN_FOO"));
310    assertEquals(value, enumType.findValueByNumber(4));
311    assertNull(enumType.findValueByName("NO_SUCH_VALUE"));
312    for (int i = 0; i < enumType.getValues().size(); i++) {
313      assertEquals(i, enumType.getValues().get(i).getIndex());
314    }
315  }
316
317  public void testServiceDescriptor() throws Exception {
318    ServiceDescriptor service = TestService.getDescriptor();
319
320    assertEquals("TestService", service.getName());
321    assertEquals("protobuf_unittest.TestService", service.getFullName());
322    assertEquals(UnittestProto.getDescriptor(), service.getFile());
323
324    assertEquals(2, service.getMethods().size());
325
326    MethodDescriptor fooMethod = service.getMethods().get(0);
327    assertEquals("Foo", fooMethod.getName());
328    assertEquals(UnittestProto.FooRequest.getDescriptor(),
329                 fooMethod.getInputType());
330    assertEquals(UnittestProto.FooResponse.getDescriptor(),
331                 fooMethod.getOutputType());
332    assertEquals(fooMethod, service.findMethodByName("Foo"));
333
334    MethodDescriptor barMethod = service.getMethods().get(1);
335    assertEquals("Bar", barMethod.getName());
336    assertEquals(UnittestProto.BarRequest.getDescriptor(),
337                 barMethod.getInputType());
338    assertEquals(UnittestProto.BarResponse.getDescriptor(),
339                 barMethod.getOutputType());
340    assertEquals(barMethod, service.findMethodByName("Bar"));
341
342    assertNull(service.findMethodByName("NoSuchMethod"));
343
344    for (int i = 0; i < service.getMethods().size(); i++) {
345      assertEquals(i, service.getMethods().get(i).getIndex());
346    }
347  }
348
349
350  public void testCustomOptions() throws Exception {
351    Descriptor descriptor =
352      UnittestCustomOptions.TestMessageWithCustomOptions.getDescriptor();
353
354    assertTrue(
355      descriptor.getOptions().hasExtension(UnittestCustomOptions.messageOpt1));
356    assertEquals(Integer.valueOf(-56),
357      descriptor.getOptions().getExtension(UnittestCustomOptions.messageOpt1));
358
359    FieldDescriptor field = descriptor.findFieldByName("field1");
360    assertNotNull(field);
361
362    assertTrue(
363      field.getOptions().hasExtension(UnittestCustomOptions.fieldOpt1));
364    assertEquals(Long.valueOf(8765432109L),
365      field.getOptions().getExtension(UnittestCustomOptions.fieldOpt1));
366
367    EnumDescriptor enumType =
368      UnittestCustomOptions.TestMessageWithCustomOptions.AnEnum.getDescriptor();
369
370    assertTrue(
371      enumType.getOptions().hasExtension(UnittestCustomOptions.enumOpt1));
372    assertEquals(Integer.valueOf(-789),
373      enumType.getOptions().getExtension(UnittestCustomOptions.enumOpt1));
374
375    ServiceDescriptor service =
376      UnittestCustomOptions.TestServiceWithCustomOptions.getDescriptor();
377
378    assertTrue(
379      service.getOptions().hasExtension(UnittestCustomOptions.serviceOpt1));
380    assertEquals(Long.valueOf(-9876543210L),
381      service.getOptions().getExtension(UnittestCustomOptions.serviceOpt1));
382
383    MethodDescriptor method = service.findMethodByName("Foo");
384    assertNotNull(method);
385
386    assertTrue(
387      method.getOptions().hasExtension(UnittestCustomOptions.methodOpt1));
388    assertEquals(UnittestCustomOptions.MethodOpt1.METHODOPT1_VAL2,
389      method.getOptions().getExtension(UnittestCustomOptions.methodOpt1));
390  }
391
392  /**
393   * Test that the FieldDescriptor.Type enum is the same as the
394   * WireFormat.FieldType enum.
395   */
396  public void testFieldTypeTablesMatch() throws Exception {
397    FieldDescriptor.Type[] values1 = FieldDescriptor.Type.values();
398    WireFormat.FieldType[] values2 = WireFormat.FieldType.values();
399
400    assertEquals(values1.length, values2.length);
401
402    for (int i = 0; i < values1.length; i++) {
403      assertEquals(values1[i].toString(), values2[i].toString());
404    }
405  }
406
407  /**
408   * Test that the FieldDescriptor.JavaType enum is the same as the
409   * WireFormat.JavaType enum.
410   */
411  public void testJavaTypeTablesMatch() throws Exception {
412    FieldDescriptor.JavaType[] values1 = FieldDescriptor.JavaType.values();
413    WireFormat.JavaType[] values2 = WireFormat.JavaType.values();
414
415    assertEquals(values1.length, values2.length);
416
417    for (int i = 0; i < values1.length; i++) {
418      assertEquals(values1[i].toString(), values2[i].toString());
419    }
420  }
421
422  public void testEnormousDescriptor() throws Exception {
423    // The descriptor for this file is larger than 64k, yet it did not cause
424    // a compiler error due to an over-long string literal.
425    assertTrue(
426        UnittestEnormousDescriptor.getDescriptor()
427          .toProto().getSerializedSize() > 65536);
428  }
429  
430  /**
431   * Tests that the DescriptorValidationException works as intended.
432   */
433  public void testDescriptorValidatorException() throws Exception {
434    FileDescriptorProto fileDescriptorProto = FileDescriptorProto.newBuilder()
435      .setName("foo.proto")
436      .addMessageType(DescriptorProto.newBuilder()
437      .setName("Foo")
438        .addField(FieldDescriptorProto.newBuilder()
439          .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)
440          .setType(FieldDescriptorProto.Type.TYPE_INT32)
441          .setName("foo")
442          .setNumber(1)
443          .setDefaultValue("invalid")
444          .build())
445        .build())
446      .build();
447    try {
448      Descriptors.FileDescriptor.buildFrom(fileDescriptorProto, 
449          new FileDescriptor[0]);
450      fail("DescriptorValidationException expected");
451    } catch (DescriptorValidationException e) {
452      // Expected; check that the error message contains some useful hints
453      assertTrue(e.getMessage().indexOf("foo") != -1);
454      assertTrue(e.getMessage().indexOf("Foo") != -1);
455      assertTrue(e.getMessage().indexOf("invalid") != -1);
456      assertTrue(e.getCause() instanceof NumberFormatException);
457      assertTrue(e.getCause().getMessage().indexOf("invalid") != -1);
458    }
459  }
460}