PageRenderTime 86ms CodeModel.GetById 30ms app.highlight 48ms RepoModel.GetById 2ms app.codeStats 0ms

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

http://github.com/tomahawk-player/tomahawk
Java | 980 lines | 757 code | 129 blank | 94 comment | 8 complexity | b485e319e865fc085ccbfbc4d33a2f43 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.UnittestLite.TestAllExtensionsLite;
 34import com.google.protobuf.test.UnittestImport;
 35import protobuf_unittest.EnumWithNoOuter;
 36import protobuf_unittest.MessageWithNoOuter;
 37import protobuf_unittest.MultipleFilesTestProto;
 38import protobuf_unittest.NestedExtension.MyNestedExtension;
 39import protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite;
 40import protobuf_unittest.NonNestedExtension;
 41import protobuf_unittest.NonNestedExtension.MessageToBeExtended;
 42import protobuf_unittest.NonNestedExtension.MyNonNestedExtension;
 43import protobuf_unittest.NonNestedExtensionLite;
 44import protobuf_unittest.NonNestedExtensionLite.MessageLiteToBeExtended;
 45import protobuf_unittest.NonNestedExtensionLite.MyNonNestedExtensionLite;
 46import protobuf_unittest.ServiceWithNoOuter;
 47import protobuf_unittest.UnittestOptimizeFor.TestOptimizedForSize;
 48import protobuf_unittest.UnittestOptimizeFor.TestOptionalOptimizedForSize;
 49import protobuf_unittest.UnittestOptimizeFor.TestRequiredOptimizedForSize;
 50import protobuf_unittest.UnittestProto;
 51import protobuf_unittest.UnittestProto.ForeignEnum;
 52import protobuf_unittest.UnittestProto.ForeignMessage;
 53import protobuf_unittest.UnittestProto.ForeignMessageOrBuilder;
 54import protobuf_unittest.UnittestProto.TestAllExtensions;
 55import protobuf_unittest.UnittestProto.TestAllTypes;
 56import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder;
 57import protobuf_unittest.UnittestProto.TestExtremeDefaultValues;
 58import protobuf_unittest.UnittestProto.TestPackedTypes;
 59import protobuf_unittest.UnittestProto.TestUnpackedTypes;
 60
 61import junit.framework.TestCase;
 62
 63import java.io.ByteArrayInputStream;
 64import java.io.ByteArrayOutputStream;
 65import java.io.ObjectInputStream;
 66import java.io.ObjectOutputStream;
 67import java.util.Arrays;
 68import java.util.Collections;
 69import java.util.List;
 70
 71/**
 72 * Unit test for generated messages and generated code.  See also
 73 * {@link MessageTest}, which tests some generated message functionality.
 74 *
 75 * @author kenton@google.com Kenton Varda
 76 */
 77public class GeneratedMessageTest extends TestCase {
 78  TestUtil.ReflectionTester reflectionTester =
 79    new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
 80
 81  public void testDefaultInstance() throws Exception {
 82    assertSame(TestAllTypes.getDefaultInstance(),
 83               TestAllTypes.getDefaultInstance().getDefaultInstanceForType());
 84    assertSame(TestAllTypes.getDefaultInstance(),
 85               TestAllTypes.newBuilder().getDefaultInstanceForType());
 86  }
 87
 88  public void testMessageOrBuilder() throws Exception {
 89    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
 90    TestUtil.setAllFields(builder);
 91    TestAllTypes message = builder.build();
 92    TestUtil.assertAllFieldsSet(message);
 93  }
 94
 95  public void testUsingBuilderMultipleTimes() throws Exception {
 96    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
 97    // primitive field scalar and repeated
 98    builder.setOptionalSfixed64(100);
 99    builder.addRepeatedInt32(100);
100    // enum field scalar and repeated
101    builder.setOptionalImportEnum(UnittestImport.ImportEnum.IMPORT_BAR);
102    builder.addRepeatedImportEnum(UnittestImport.ImportEnum.IMPORT_BAR);
103    // proto field scalar and repeated
104    builder.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(1));
105    builder.addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(1));
106
107    TestAllTypes value1 = builder.build();
108
109    assertEquals(100, value1.getOptionalSfixed64());
110    assertEquals(100, value1.getRepeatedInt32(0));
111    assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
112        value1.getOptionalImportEnum());
113    assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
114        value1.getRepeatedImportEnum(0));
115    assertEquals(1, value1.getOptionalForeignMessage().getC());
116    assertEquals(1, value1.getRepeatedForeignMessage(0).getC());
117
118    // Make sure that builder didn't update previously created values
119    builder.setOptionalSfixed64(200);
120    builder.setRepeatedInt32(0, 200);
121    builder.setOptionalImportEnum(UnittestImport.ImportEnum.IMPORT_FOO);
122    builder.setRepeatedImportEnum(0, UnittestImport.ImportEnum.IMPORT_FOO);
123    builder.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(2));
124    builder.setRepeatedForeignMessage(0, ForeignMessage.newBuilder().setC(2));
125
126    TestAllTypes value2 = builder.build();
127
128    // Make sure value1 didn't change.
129    assertEquals(100, value1.getOptionalSfixed64());
130    assertEquals(100, value1.getRepeatedInt32(0));
131    assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
132        value1.getOptionalImportEnum());
133    assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
134        value1.getRepeatedImportEnum(0));
135    assertEquals(1, value1.getOptionalForeignMessage().getC());
136    assertEquals(1, value1.getRepeatedForeignMessage(0).getC());
137
138    // Make sure value2 is correct
139    assertEquals(200, value2.getOptionalSfixed64());
140    assertEquals(200, value2.getRepeatedInt32(0));
141    assertEquals(UnittestImport.ImportEnum.IMPORT_FOO,
142        value2.getOptionalImportEnum());
143    assertEquals(UnittestImport.ImportEnum.IMPORT_FOO,
144        value2.getRepeatedImportEnum(0));
145    assertEquals(2, value2.getOptionalForeignMessage().getC());
146    assertEquals(2, value2.getRepeatedForeignMessage(0).getC());
147  }
148
149  public void testProtosShareRepeatedArraysIfDidntChange() throws Exception {
150    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
151    builder.addRepeatedInt32(100);
152    builder.addRepeatedImportEnum(UnittestImport.ImportEnum.IMPORT_BAR);
153    builder.addRepeatedForeignMessage(ForeignMessage.getDefaultInstance());
154
155    TestAllTypes value1 = builder.build();
156    TestAllTypes value2 = value1.toBuilder().build();
157
158    assertSame(value1.getRepeatedInt32List(), value2.getRepeatedInt32List());
159    assertSame(value1.getRepeatedImportEnumList(),
160        value2.getRepeatedImportEnumList());
161    assertSame(value1.getRepeatedForeignMessageList(),
162        value2.getRepeatedForeignMessageList());
163  }
164
165  public void testRepeatedArraysAreImmutable() throws Exception {
166    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
167    builder.addRepeatedInt32(100);
168    builder.addRepeatedImportEnum(UnittestImport.ImportEnum.IMPORT_BAR);
169    builder.addRepeatedForeignMessage(ForeignMessage.getDefaultInstance());
170    assertIsUnmodifiable(builder.getRepeatedInt32List());
171    assertIsUnmodifiable(builder.getRepeatedImportEnumList());
172    assertIsUnmodifiable(builder.getRepeatedForeignMessageList());
173    assertIsUnmodifiable(builder.getRepeatedFloatList());
174
175
176    TestAllTypes value = builder.build();
177    assertIsUnmodifiable(value.getRepeatedInt32List());
178    assertIsUnmodifiable(value.getRepeatedImportEnumList());
179    assertIsUnmodifiable(value.getRepeatedForeignMessageList());
180    assertIsUnmodifiable(value.getRepeatedFloatList());
181  }
182
183  private void assertIsUnmodifiable(List<?> list) {
184    if (list == Collections.emptyList()) {
185      // OKAY -- Need to check this b/c EmptyList allows you to call clear.
186    } else {
187      try {
188        list.clear();
189        fail("List wasn't immutable");
190      } catch (UnsupportedOperationException e) {
191        // good
192      }
193    }
194  }
195
196  public void testSettersRejectNull() throws Exception {
197    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
198    try {
199      builder.setOptionalString(null);
200      fail("Exception was not thrown");
201    } catch (NullPointerException e) {
202      // We expect this exception.
203    }
204    try {
205      builder.setOptionalBytes(null);
206      fail("Exception was not thrown");
207    } catch (NullPointerException e) {
208      // We expect this exception.
209    }
210    try {
211      builder.setOptionalNestedMessage((TestAllTypes.NestedMessage) null);
212      fail("Exception was not thrown");
213    } catch (NullPointerException e) {
214      // We expect this exception.
215    }
216    try {
217      builder.setOptionalNestedMessage(
218          (TestAllTypes.NestedMessage.Builder) null);
219      fail("Exception was not thrown");
220    } catch (NullPointerException e) {
221      // We expect this exception.
222    }
223    try {
224      builder.setOptionalNestedEnum(null);
225      fail("Exception was not thrown");
226    } catch (NullPointerException e) {
227      // We expect this exception.
228    }
229    try {
230      builder.addRepeatedString(null);
231      fail("Exception was not thrown");
232    } catch (NullPointerException e) {
233      // We expect this exception.
234    }
235    try {
236      builder.addRepeatedBytes(null);
237      fail("Exception was not thrown");
238    } catch (NullPointerException e) {
239      // We expect this exception.
240    }
241    try {
242      builder.addRepeatedNestedMessage((TestAllTypes.NestedMessage) null);
243      fail("Exception was not thrown");
244    } catch (NullPointerException e) {
245      // We expect this exception.
246    }
247    try {
248      builder.addRepeatedNestedMessage(
249          (TestAllTypes.NestedMessage.Builder) null);
250      fail("Exception was not thrown");
251    } catch (NullPointerException e) {
252      // We expect this exception.
253    }
254    try {
255      builder.addRepeatedNestedEnum(null);
256      fail("Exception was not thrown");
257    } catch (NullPointerException e) {
258      // We expect this exception.
259    }
260  }
261
262  public void testRepeatedSetters() throws Exception {
263    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
264    TestUtil.setAllFields(builder);
265    TestUtil.modifyRepeatedFields(builder);
266    TestAllTypes message = builder.build();
267    TestUtil.assertRepeatedFieldsModified(message);
268  }
269
270  public void testRepeatedSettersRejectNull() throws Exception {
271    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
272
273    builder.addRepeatedString("one");
274    builder.addRepeatedString("two");
275    try {
276      builder.setRepeatedString(1, null);
277      fail("Exception was not thrown");
278    } catch (NullPointerException e) {
279      // We expect this exception.
280    }
281
282    builder.addRepeatedBytes(TestUtil.toBytes("one"));
283    builder.addRepeatedBytes(TestUtil.toBytes("two"));
284    try {
285      builder.setRepeatedBytes(1, null);
286      fail("Exception was not thrown");
287    } catch (NullPointerException e) {
288      // We expect this exception.
289    }
290
291    builder.addRepeatedNestedMessage(
292      TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
293    builder.addRepeatedNestedMessage(
294      TestAllTypes.NestedMessage.newBuilder().setBb(456).build());
295    try {
296      builder.setRepeatedNestedMessage(1, (TestAllTypes.NestedMessage) null);
297      fail("Exception was not thrown");
298    } catch (NullPointerException e) {
299      // We expect this exception.
300    }
301    try {
302      builder.setRepeatedNestedMessage(
303          1, (TestAllTypes.NestedMessage.Builder) null);
304      fail("Exception was not thrown");
305    } catch (NullPointerException e) {
306      // We expect this exception.
307    }
308
309    builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.FOO);
310    builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAR);
311    try {
312      builder.setRepeatedNestedEnum(1, null);
313      fail("Exception was not thrown");
314    } catch (NullPointerException e) {
315      // We expect this exception.
316    }
317  }
318
319  public void testRepeatedAppend() throws Exception {
320    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
321
322    builder.addAllRepeatedInt32(Arrays.asList(1, 2, 3, 4));
323    builder.addAllRepeatedForeignEnum(Arrays.asList(ForeignEnum.FOREIGN_BAZ));
324
325    ForeignMessage foreignMessage =
326        ForeignMessage.newBuilder().setC(12).build();
327    builder.addAllRepeatedForeignMessage(Arrays.asList(foreignMessage));
328
329    TestAllTypes message = builder.build();
330    assertEquals(message.getRepeatedInt32List(), Arrays.asList(1, 2, 3, 4));
331    assertEquals(message.getRepeatedForeignEnumList(),
332        Arrays.asList(ForeignEnum.FOREIGN_BAZ));
333    assertEquals(1, message.getRepeatedForeignMessageCount());
334    assertEquals(12, message.getRepeatedForeignMessage(0).getC());
335  }
336
337  public void testRepeatedAppendRejectsNull() throws Exception {
338    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
339
340    ForeignMessage foreignMessage =
341        ForeignMessage.newBuilder().setC(12).build();
342    try {
343      builder.addAllRepeatedForeignMessage(
344          Arrays.asList(foreignMessage, (ForeignMessage) null));
345      fail("Exception was not thrown");
346    } catch (NullPointerException e) {
347      // We expect this exception.
348    }
349
350    try {
351      builder.addAllRepeatedForeignEnum(
352          Arrays.asList(ForeignEnum.FOREIGN_BAZ, null));
353      fail("Exception was not thrown");
354    } catch (NullPointerException e) {
355      // We expect this exception.
356    }
357
358    try {
359      builder.addAllRepeatedString(Arrays.asList("one", null));
360      fail("Exception was not thrown");
361    } catch (NullPointerException e) {
362      // We expect this exception.
363    }
364
365    try {
366      builder.addAllRepeatedBytes(Arrays.asList(TestUtil.toBytes("one"), null));
367      fail("Exception was not thrown");
368    } catch (NullPointerException e) {
369      // We expect this exception.
370    }
371  }
372
373  public void testSettingForeignMessageUsingBuilder() throws Exception {
374    TestAllTypes message = TestAllTypes.newBuilder()
375        // Pass builder for foreign message instance.
376        .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(123))
377        .build();
378    TestAllTypes expectedMessage = TestAllTypes.newBuilder()
379        // Create expected version passing foreign message instance explicitly.
380        .setOptionalForeignMessage(
381            ForeignMessage.newBuilder().setC(123).build())
382        .build();
383    // TODO(ngd): Upgrade to using real #equals method once implemented
384    assertEquals(expectedMessage.toString(), message.toString());
385  }
386
387  public void testSettingRepeatedForeignMessageUsingBuilder() throws Exception {
388    TestAllTypes message = TestAllTypes.newBuilder()
389        // Pass builder for foreign message instance.
390        .addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(456))
391        .build();
392    TestAllTypes expectedMessage = TestAllTypes.newBuilder()
393        // Create expected version passing foreign message instance explicitly.
394        .addRepeatedForeignMessage(
395            ForeignMessage.newBuilder().setC(456).build())
396        .build();
397    assertEquals(expectedMessage.toString(), message.toString());
398  }
399
400  public void testDefaults() throws Exception {
401    TestUtil.assertClear(TestAllTypes.getDefaultInstance());
402    TestUtil.assertClear(TestAllTypes.newBuilder().build());
403
404    TestExtremeDefaultValues message =
405        TestExtremeDefaultValues.getDefaultInstance();
406    assertEquals("\u1234", message.getUtf8String());
407    assertEquals(Double.POSITIVE_INFINITY, message.getInfDouble());
408    assertEquals(Double.NEGATIVE_INFINITY, message.getNegInfDouble());
409    assertTrue(Double.isNaN(message.getNanDouble()));
410    assertEquals(Float.POSITIVE_INFINITY, message.getInfFloat());
411    assertEquals(Float.NEGATIVE_INFINITY, message.getNegInfFloat());
412    assertTrue(Float.isNaN(message.getNanFloat()));
413    assertEquals("? ? ?? ?? ??? ??/ ??-", message.getCppTrigraph());
414  }
415
416  public void testClear() throws Exception {
417    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
418    TestUtil.assertClear(builder);
419    TestUtil.setAllFields(builder);
420    builder.clear();
421    TestUtil.assertClear(builder);
422  }
423
424  public void testReflectionGetters() throws Exception {
425    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
426    TestUtil.setAllFields(builder);
427    reflectionTester.assertAllFieldsSetViaReflection(builder);
428
429    TestAllTypes message = builder.build();
430    reflectionTester.assertAllFieldsSetViaReflection(message);
431  }
432
433  public void testReflectionSetters() throws Exception {
434    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
435    reflectionTester.setAllFieldsViaReflection(builder);
436    TestUtil.assertAllFieldsSet(builder);
437
438    TestAllTypes message = builder.build();
439    TestUtil.assertAllFieldsSet(message);
440  }
441
442  public void testReflectionSettersRejectNull() throws Exception {
443    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
444    reflectionTester.assertReflectionSettersRejectNull(builder);
445  }
446
447  public void testReflectionRepeatedSetters() throws Exception {
448    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
449    reflectionTester.setAllFieldsViaReflection(builder);
450    reflectionTester.modifyRepeatedFieldsViaReflection(builder);
451    TestUtil.assertRepeatedFieldsModified(builder);
452
453    TestAllTypes message = builder.build();
454    TestUtil.assertRepeatedFieldsModified(message);
455  }
456
457  public void testReflectionRepeatedSettersRejectNull() throws Exception {
458    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
459    reflectionTester.assertReflectionRepeatedSettersRejectNull(builder);
460  }
461
462  public void testReflectionDefaults() throws Exception {
463    reflectionTester.assertClearViaReflection(
464      TestAllTypes.getDefaultInstance());
465    reflectionTester.assertClearViaReflection(
466      TestAllTypes.newBuilder().build());
467  }
468
469  public void testEnumInterface() throws Exception {
470    assertTrue(TestAllTypes.getDefaultInstance().getDefaultNestedEnum()
471        instanceof ProtocolMessageEnum);
472  }
473
474  public void testEnumMap() throws Exception {
475    Internal.EnumLiteMap<ForeignEnum> map = ForeignEnum.internalGetValueMap();
476
477    for (ForeignEnum value : ForeignEnum.values()) {
478      assertEquals(value, map.findValueByNumber(value.getNumber()));
479    }
480
481    assertTrue(map.findValueByNumber(12345) == null);
482  }
483
484  public void testParsePackedToUnpacked() throws Exception {
485    TestUnpackedTypes.Builder builder = TestUnpackedTypes.newBuilder();
486    TestUnpackedTypes message =
487      builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
488    TestUtil.assertUnpackedFieldsSet(message);
489  }
490
491  public void testParseUnpackedToPacked() throws Exception {
492    TestPackedTypes.Builder builder = TestPackedTypes.newBuilder();
493    TestPackedTypes message =
494      builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
495    TestUtil.assertPackedFieldsSet(message);
496  }
497
498  // =================================================================
499  // Extensions.
500
501  TestUtil.ReflectionTester extensionsReflectionTester =
502    new TestUtil.ReflectionTester(TestAllExtensions.getDescriptor(),
503                                  TestUtil.getExtensionRegistry());
504
505  public void testExtensionMessageOrBuilder() throws Exception {
506    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
507    TestUtil.setAllExtensions(builder);
508    TestAllExtensions message = builder.build();
509    TestUtil.assertAllExtensionsSet(message);
510  }
511
512  public void testExtensionRepeatedSetters() throws Exception {
513    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
514    TestUtil.setAllExtensions(builder);
515    TestUtil.modifyRepeatedExtensions(builder);
516    TestAllExtensions message = builder.build();
517    TestUtil.assertRepeatedExtensionsModified(message);
518  }
519
520  public void testExtensionDefaults() throws Exception {
521    TestUtil.assertExtensionsClear(TestAllExtensions.getDefaultInstance());
522    TestUtil.assertExtensionsClear(TestAllExtensions.newBuilder().build());
523  }
524
525  public void testExtensionReflectionGetters() throws Exception {
526    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
527    TestUtil.setAllExtensions(builder);
528    extensionsReflectionTester.assertAllFieldsSetViaReflection(builder);
529
530    TestAllExtensions message = builder.build();
531    extensionsReflectionTester.assertAllFieldsSetViaReflection(message);
532  }
533
534  public void testExtensionReflectionSetters() throws Exception {
535    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
536    extensionsReflectionTester.setAllFieldsViaReflection(builder);
537    TestUtil.assertAllExtensionsSet(builder);
538
539    TestAllExtensions message = builder.build();
540    TestUtil.assertAllExtensionsSet(message);
541  }
542
543  public void testExtensionReflectionSettersRejectNull() throws Exception {
544    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
545    extensionsReflectionTester.assertReflectionSettersRejectNull(builder);
546  }
547
548  public void testExtensionReflectionRepeatedSetters() throws Exception {
549    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
550    extensionsReflectionTester.setAllFieldsViaReflection(builder);
551    extensionsReflectionTester.modifyRepeatedFieldsViaReflection(builder);
552    TestUtil.assertRepeatedExtensionsModified(builder);
553
554    TestAllExtensions message = builder.build();
555    TestUtil.assertRepeatedExtensionsModified(message);
556  }
557
558  public void testExtensionReflectionRepeatedSettersRejectNull()
559      throws Exception {
560    TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
561    extensionsReflectionTester.assertReflectionRepeatedSettersRejectNull(
562        builder);
563  }
564
565  public void testExtensionReflectionDefaults() throws Exception {
566    extensionsReflectionTester.assertClearViaReflection(
567      TestAllExtensions.getDefaultInstance());
568    extensionsReflectionTester.assertClearViaReflection(
569      TestAllExtensions.newBuilder().build());
570  }
571
572  public void testClearExtension() throws Exception {
573    // clearExtension() is not actually used in TestUtil, so try it manually.
574    assertFalse(
575      TestAllExtensions.newBuilder()
576        .setExtension(UnittestProto.optionalInt32Extension, 1)
577        .clearExtension(UnittestProto.optionalInt32Extension)
578        .hasExtension(UnittestProto.optionalInt32Extension));
579    assertEquals(0,
580      TestAllExtensions.newBuilder()
581        .addExtension(UnittestProto.repeatedInt32Extension, 1)
582        .clearExtension(UnittestProto.repeatedInt32Extension)
583        .getExtensionCount(UnittestProto.repeatedInt32Extension));
584  }
585
586  public void testExtensionCopy() throws Exception {
587    TestAllExtensions original = TestUtil.getAllExtensionsSet();
588    TestAllExtensions copy = TestAllExtensions.newBuilder(original).build();
589    TestUtil.assertAllExtensionsSet(copy);
590  }
591
592  public void testExtensionMergeFrom() throws Exception {
593    TestAllExtensions original =
594      TestAllExtensions.newBuilder()
595        .setExtension(UnittestProto.optionalInt32Extension, 1).build();
596    TestAllExtensions merged =
597        TestAllExtensions.newBuilder().mergeFrom(original).build();
598    assertTrue(merged.hasExtension(UnittestProto.optionalInt32Extension));
599    assertEquals(
600        1, (int) merged.getExtension(UnittestProto.optionalInt32Extension));
601  }
602
603  // =================================================================
604  // Lite Extensions.
605
606  // We test lite extensions directly because they have a separate
607  // implementation from full extensions.  In contrast, we do not test
608  // lite fields directly since they are implemented exactly the same as
609  // regular fields.
610
611  public void testLiteExtensionMessageOrBuilder() throws Exception {
612    TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder();
613    TestUtil.setAllExtensions(builder);
614    TestUtil.assertAllExtensionsSet(builder);
615
616    TestAllExtensionsLite message = builder.build();
617    TestUtil.assertAllExtensionsSet(message);
618  }
619
620  public void testLiteExtensionRepeatedSetters() throws Exception {
621    TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder();
622    TestUtil.setAllExtensions(builder);
623    TestUtil.modifyRepeatedExtensions(builder);
624    TestUtil.assertRepeatedExtensionsModified(builder);
625
626    TestAllExtensionsLite message = builder.build();
627    TestUtil.assertRepeatedExtensionsModified(message);
628  }
629
630  public void testLiteExtensionDefaults() throws Exception {
631    TestUtil.assertExtensionsClear(TestAllExtensionsLite.getDefaultInstance());
632    TestUtil.assertExtensionsClear(TestAllExtensionsLite.newBuilder().build());
633  }
634
635  public void testClearLiteExtension() throws Exception {
636    // clearExtension() is not actually used in TestUtil, so try it manually.
637    assertFalse(
638      TestAllExtensionsLite.newBuilder()
639        .setExtension(UnittestLite.optionalInt32ExtensionLite, 1)
640        .clearExtension(UnittestLite.optionalInt32ExtensionLite)
641        .hasExtension(UnittestLite.optionalInt32ExtensionLite));
642    assertEquals(0,
643      TestAllExtensionsLite.newBuilder()
644        .addExtension(UnittestLite.repeatedInt32ExtensionLite, 1)
645        .clearExtension(UnittestLite.repeatedInt32ExtensionLite)
646        .getExtensionCount(UnittestLite.repeatedInt32ExtensionLite));
647  }
648
649  public void testLiteExtensionCopy() throws Exception {
650    TestAllExtensionsLite original = TestUtil.getAllLiteExtensionsSet();
651    TestAllExtensionsLite copy =
652        TestAllExtensionsLite.newBuilder(original).build();
653    TestUtil.assertAllExtensionsSet(copy);
654  }
655
656  public void testLiteExtensionMergeFrom() throws Exception {
657    TestAllExtensionsLite original =
658      TestAllExtensionsLite.newBuilder()
659        .setExtension(UnittestLite.optionalInt32ExtensionLite, 1).build();
660    TestAllExtensionsLite merged =
661        TestAllExtensionsLite.newBuilder().mergeFrom(original).build();
662    assertTrue(merged.hasExtension(UnittestLite.optionalInt32ExtensionLite));
663    assertEquals(
664        1, (int) merged.getExtension(UnittestLite.optionalInt32ExtensionLite));
665  }
666
667  // =================================================================
668  // multiple_files_test
669
670  public void testMultipleFilesOption() throws Exception {
671    // We mostly just want to check that things compile.
672    MessageWithNoOuter message =
673      MessageWithNoOuter.newBuilder()
674        .setNested(MessageWithNoOuter.NestedMessage.newBuilder().setI(1))
675        .addForeign(TestAllTypes.newBuilder().setOptionalInt32(1))
676        .setNestedEnum(MessageWithNoOuter.NestedEnum.BAZ)
677        .setForeignEnum(EnumWithNoOuter.BAR)
678        .build();
679    assertEquals(message, MessageWithNoOuter.parseFrom(message.toByteString()));
680
681    assertEquals(MultipleFilesTestProto.getDescriptor(),
682                 MessageWithNoOuter.getDescriptor().getFile());
683
684    Descriptors.FieldDescriptor field =
685      MessageWithNoOuter.getDescriptor().findFieldByName("foreign_enum");
686    assertEquals(EnumWithNoOuter.BAR.getValueDescriptor(),
687                 message.getField(field));
688
689    assertEquals(MultipleFilesTestProto.getDescriptor(),
690                 ServiceWithNoOuter.getDescriptor().getFile());
691
692    assertFalse(
693      TestAllExtensions.getDefaultInstance().hasExtension(
694        MultipleFilesTestProto.extensionWithOuter));
695  }
696
697  public void testOptionalFieldWithRequiredSubfieldsOptimizedForSize()
698    throws Exception {
699    TestOptionalOptimizedForSize message =
700        TestOptionalOptimizedForSize.getDefaultInstance();
701    assertTrue(message.isInitialized());
702
703    message = TestOptionalOptimizedForSize.newBuilder().setO(
704        TestRequiredOptimizedForSize.newBuilder().buildPartial()
705        ).buildPartial();
706    assertFalse(message.isInitialized());
707
708    message = TestOptionalOptimizedForSize.newBuilder().setO(
709        TestRequiredOptimizedForSize.newBuilder().setX(5).buildPartial()
710        ).buildPartial();
711    assertTrue(message.isInitialized());
712  }
713
714  public void testUninitializedExtensionInOptimizedForSize()
715      throws Exception {
716    TestOptimizedForSize.Builder builder = TestOptimizedForSize.newBuilder();
717    builder.setExtension(TestOptimizedForSize.testExtension2,
718        TestRequiredOptimizedForSize.newBuilder().buildPartial());
719    assertFalse(builder.isInitialized());
720    assertFalse(builder.buildPartial().isInitialized());
721
722    builder = TestOptimizedForSize.newBuilder();
723    builder.setExtension(TestOptimizedForSize.testExtension2,
724        TestRequiredOptimizedForSize.newBuilder().setX(10).buildPartial());
725    assertTrue(builder.isInitialized());
726    assertTrue(builder.buildPartial().isInitialized());
727  }
728
729  public void testToBuilder() throws Exception {
730    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
731    TestUtil.setAllFields(builder);
732    TestAllTypes message = builder.build();
733    TestUtil.assertAllFieldsSet(message);
734    TestUtil.assertAllFieldsSet(message.toBuilder().build());
735  }
736
737  public void testFieldConstantValues() throws Exception {
738    assertEquals(TestAllTypes.NestedMessage.BB_FIELD_NUMBER, 1);
739    assertEquals(TestAllTypes.OPTIONAL_INT32_FIELD_NUMBER, 1);
740    assertEquals(TestAllTypes.OPTIONALGROUP_FIELD_NUMBER, 16);
741    assertEquals(TestAllTypes.OPTIONAL_NESTED_MESSAGE_FIELD_NUMBER, 18);
742    assertEquals(TestAllTypes.OPTIONAL_NESTED_ENUM_FIELD_NUMBER, 21);
743    assertEquals(TestAllTypes.REPEATED_INT32_FIELD_NUMBER, 31);
744    assertEquals(TestAllTypes.REPEATEDGROUP_FIELD_NUMBER, 46);
745    assertEquals(TestAllTypes.REPEATED_NESTED_MESSAGE_FIELD_NUMBER, 48);
746    assertEquals(TestAllTypes.REPEATED_NESTED_ENUM_FIELD_NUMBER, 51);
747  }
748
749  public void testExtensionConstantValues() throws Exception {
750    assertEquals(UnittestProto.TestRequired.SINGLE_FIELD_NUMBER, 1000);
751    assertEquals(UnittestProto.TestRequired.MULTI_FIELD_NUMBER, 1001);
752    assertEquals(UnittestProto.OPTIONAL_INT32_EXTENSION_FIELD_NUMBER, 1);
753    assertEquals(UnittestProto.OPTIONALGROUP_EXTENSION_FIELD_NUMBER, 16);
754    assertEquals(
755      UnittestProto.OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 18);
756    assertEquals(UnittestProto.OPTIONAL_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 21);
757    assertEquals(UnittestProto.REPEATED_INT32_EXTENSION_FIELD_NUMBER, 31);
758    assertEquals(UnittestProto.REPEATEDGROUP_EXTENSION_FIELD_NUMBER, 46);
759    assertEquals(
760      UnittestProto.REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 48);
761    assertEquals(UnittestProto.REPEATED_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 51);
762  }
763
764  public void testRecursiveMessageDefaultInstance() throws Exception {
765    UnittestProto.TestRecursiveMessage message =
766        UnittestProto.TestRecursiveMessage.getDefaultInstance();
767    assertTrue(message != null);
768    assertTrue(message.getA() != null);
769    assertTrue(message.getA() == message);
770  }
771
772  public void testSerialize() throws Exception {
773    ByteArrayOutputStream baos = new ByteArrayOutputStream();
774    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
775    TestUtil.setAllFields(builder);
776    TestAllTypes expected = builder.build();
777    ObjectOutputStream out = new ObjectOutputStream(baos);
778    try {
779      out.writeObject(expected);
780    } finally {
781      out.close();
782    }
783    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
784    ObjectInputStream in = new ObjectInputStream(bais);
785    TestAllTypes actual = (TestAllTypes) in.readObject();
786    assertEquals(expected, actual);
787  }
788
789  public void testSerializePartial() throws Exception {
790    ByteArrayOutputStream baos = new ByteArrayOutputStream();
791    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
792    TestAllTypes expected = builder.buildPartial();
793    ObjectOutputStream out = new ObjectOutputStream(baos);
794    try {
795      out.writeObject(expected);
796    } finally {
797      out.close();
798    }
799    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
800    ObjectInputStream in = new ObjectInputStream(bais);
801    TestAllTypes actual = (TestAllTypes) in.readObject();
802    assertEquals(expected, actual);
803  }
804
805  public void testEnumValues() {
806     assertEquals(
807         TestAllTypes.NestedEnum.BAR.getNumber(),
808         TestAllTypes.NestedEnum.BAR_VALUE);
809    assertEquals(
810        TestAllTypes.NestedEnum.BAZ.getNumber(),
811        TestAllTypes.NestedEnum.BAZ_VALUE);
812    assertEquals(
813        TestAllTypes.NestedEnum.FOO.getNumber(),
814        TestAllTypes.NestedEnum.FOO_VALUE);
815  }
816
817  public void testNonNestedExtensionInitialization() {
818    assertTrue(NonNestedExtension.nonNestedExtension
819               .getMessageDefaultInstance() instanceof MyNonNestedExtension);
820    assertEquals("nonNestedExtension",
821                 NonNestedExtension.nonNestedExtension.getDescriptor().getName());
822  }
823
824  public void testNestedExtensionInitialization() {
825    assertTrue(MyNestedExtension.recursiveExtension.getMessageDefaultInstance()
826               instanceof MessageToBeExtended);
827    assertEquals("recursiveExtension",
828                 MyNestedExtension.recursiveExtension.getDescriptor().getName());
829  }
830
831  public void testNonNestedExtensionLiteInitialization() {
832    assertTrue(NonNestedExtensionLite.nonNestedExtensionLite
833               .getMessageDefaultInstance() instanceof MyNonNestedExtensionLite);
834  }
835
836  public void testNestedExtensionLiteInitialization() {
837    assertTrue(MyNestedExtensionLite.recursiveExtensionLite
838               .getMessageDefaultInstance() instanceof MessageLiteToBeExtended);
839  }
840
841  public void testInvalidations() throws Exception {
842    GeneratedMessage.enableAlwaysUseFieldBuildersForTesting();
843    TestAllTypes.NestedMessage nestedMessage1 =
844        TestAllTypes.NestedMessage.newBuilder().build();
845    TestAllTypes.NestedMessage nestedMessage2 =
846        TestAllTypes.NestedMessage.newBuilder().build();
847
848    // Set all three flavors (enum, primitive, message and singular/repeated)
849    // and verify no invalidations fired
850    TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
851
852    TestAllTypes.Builder builder = (TestAllTypes.Builder)
853        ((GeneratedMessage) TestAllTypes.getDefaultInstance()).
854            newBuilderForType(mockParent);
855    builder.setOptionalInt32(1);
856    builder.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAR);
857    builder.setOptionalNestedMessage(nestedMessage1);
858    builder.addRepeatedInt32(1);
859    builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAR);
860    builder.addRepeatedNestedMessage(nestedMessage1);
861    assertEquals(0, mockParent.getInvalidationCount());
862
863    // Now tell it we want changes and make sure it's only fired once
864    // And do this for each flavor
865
866    // primitive single
867    builder.buildPartial();
868    builder.setOptionalInt32(2);
869    builder.setOptionalInt32(3);
870    assertEquals(1, mockParent.getInvalidationCount());
871
872    // enum single
873    builder.buildPartial();
874    builder.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAZ);
875    builder.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAR);
876    assertEquals(2, mockParent.getInvalidationCount());
877
878    // message single
879    builder.buildPartial();
880    builder.setOptionalNestedMessage(nestedMessage2);
881    builder.setOptionalNestedMessage(nestedMessage1);
882    assertEquals(3, mockParent.getInvalidationCount());
883
884    // primitive repated
885    builder.buildPartial();
886    builder.addRepeatedInt32(2);
887    builder.addRepeatedInt32(3);
888    assertEquals(4, mockParent.getInvalidationCount());
889
890    // enum repeated
891    builder.buildPartial();
892    builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAZ);
893    builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAZ);
894    assertEquals(5, mockParent.getInvalidationCount());
895
896    // message repeated
897    builder.buildPartial();
898    builder.addRepeatedNestedMessage(nestedMessage2);
899    builder.addRepeatedNestedMessage(nestedMessage1);
900    assertEquals(6, mockParent.getInvalidationCount());
901
902  }
903
904  public void testInvalidations_Extensions() throws Exception {
905    TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
906
907    TestAllExtensions.Builder builder = (TestAllExtensions.Builder)
908        ((GeneratedMessage) TestAllExtensions.getDefaultInstance()).
909            newBuilderForType(mockParent);
910
911    builder.addExtension(UnittestProto.repeatedInt32Extension, 1);
912    builder.setExtension(UnittestProto.repeatedInt32Extension, 0, 2);
913    builder.clearExtension(UnittestProto.repeatedInt32Extension);
914    assertEquals(0, mockParent.getInvalidationCount());
915
916    // Now tell it we want changes and make sure it's only fired once
917    builder.buildPartial();
918    builder.addExtension(UnittestProto.repeatedInt32Extension, 2);
919    builder.addExtension(UnittestProto.repeatedInt32Extension, 3);
920    assertEquals(1, mockParent.getInvalidationCount());
921
922    builder.buildPartial();
923    builder.setExtension(UnittestProto.repeatedInt32Extension, 0, 4);
924    builder.setExtension(UnittestProto.repeatedInt32Extension, 1, 5);
925    assertEquals(2, mockParent.getInvalidationCount());
926
927    builder.buildPartial();
928    builder.clearExtension(UnittestProto.repeatedInt32Extension);
929    builder.clearExtension(UnittestProto.repeatedInt32Extension);
930    assertEquals(3, mockParent.getInvalidationCount());
931  }
932
933  public void testBaseMessageOrBuilder() {
934    // Mostly just makes sure the base interface exists and has some methods.
935    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
936    TestAllTypes message = builder.buildPartial();
937    TestAllTypesOrBuilder builderAsInterface = (TestAllTypesOrBuilder) builder;
938    TestAllTypesOrBuilder messageAsInterface = (TestAllTypesOrBuilder) message;
939
940    assertEquals(
941        messageAsInterface.getDefaultBool(),
942        messageAsInterface.getDefaultBool());
943    assertEquals(
944        messageAsInterface.getOptionalDouble(),
945        messageAsInterface.getOptionalDouble());
946  }
947
948  public void testMessageOrBuilderGetters() {
949    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
950
951    // single fields
952    assertSame(ForeignMessage.getDefaultInstance(),
953        builder.getOptionalForeignMessageOrBuilder());
954    ForeignMessage.Builder subBuilder =
955        builder.getOptionalForeignMessageBuilder();
956    assertSame(subBuilder, builder.getOptionalForeignMessageOrBuilder());
957
958    // repeated fields
959    ForeignMessage m0 = ForeignMessage.newBuilder().buildPartial();
960    ForeignMessage m1 = ForeignMessage.newBuilder().buildPartial();
961    ForeignMessage m2 = ForeignMessage.newBuilder().buildPartial();
962    builder.addRepeatedForeignMessage(m0);
963    builder.addRepeatedForeignMessage(m1);
964    builder.addRepeatedForeignMessage(m2);
965    assertSame(m0, builder.getRepeatedForeignMessageOrBuilder(0));
966    assertSame(m1, builder.getRepeatedForeignMessageOrBuilder(1));
967    assertSame(m2, builder.getRepeatedForeignMessageOrBuilder(2));
968    ForeignMessage.Builder b0 = builder.getRepeatedForeignMessageBuilder(0);
969    ForeignMessage.Builder b1 = builder.getRepeatedForeignMessageBuilder(1);
970    assertSame(b0, builder.getRepeatedForeignMessageOrBuilder(0));
971    assertSame(b1, builder.getRepeatedForeignMessageOrBuilder(1));
972    assertSame(m2, builder.getRepeatedForeignMessageOrBuilder(2));
973
974    List<? extends ForeignMessageOrBuilder> messageOrBuilderList =
975        builder.getRepeatedForeignMessageOrBuilderList();
976    assertSame(b0, messageOrBuilderList.get(0));
977    assertSame(b1, messageOrBuilderList.get(1));
978    assertSame(m2, messageOrBuilderList.get(2));
979  }
980}