1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
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 
31 package com.google.protobuf;
32 
33 import com.google.protobuf.Descriptors.Descriptor;
34 import com.google.protobuf.Descriptors.FieldDescriptor;
35 import com.google.protobuf.UnittestLite.TestAllExtensionsLite;
36 import com.google.protobuf.test.UnittestImport;
37 import protobuf_unittest.EnumWithNoOuter;
38 import protobuf_unittest.MessageWithNoOuter;
39 import protobuf_unittest.MultipleFilesTestProto;
40 import protobuf_unittest.NestedExtension.MyNestedExtension;
41 import protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite;
42 import protobuf_unittest.NonNestedExtension;
43 import protobuf_unittest.NonNestedExtension.MessageToBeExtended;
44 import protobuf_unittest.NonNestedExtension.MyNonNestedExtension;
45 import protobuf_unittest.NonNestedExtensionLite;
46 import protobuf_unittest.NonNestedExtensionLite.MessageLiteToBeExtended;
47 import protobuf_unittest.NonNestedExtensionLite.MyNonNestedExtensionLite;
48 import protobuf_unittest.OuterClassNameTest2OuterClass;
49 import protobuf_unittest.OuterClassNameTest3OuterClass;
50 import protobuf_unittest.OuterClassNameTestOuterClass;
51 import protobuf_unittest.ServiceWithNoOuter;
52 import protobuf_unittest.UnittestOptimizeFor.TestOptimizedForSize;
53 import protobuf_unittest.UnittestOptimizeFor.TestOptionalOptimizedForSize;
54 import protobuf_unittest.UnittestOptimizeFor.TestRequiredOptimizedForSize;
55 import protobuf_unittest.UnittestProto;
56 import protobuf_unittest.UnittestProto.ForeignEnum;
57 import protobuf_unittest.UnittestProto.ForeignMessage;
58 import protobuf_unittest.UnittestProto.ForeignMessageOrBuilder;
59 import protobuf_unittest.UnittestProto.NestedTestAllTypes;
60 import protobuf_unittest.UnittestProto.TestAllExtensions;
61 import protobuf_unittest.UnittestProto.TestAllTypes;
62 import protobuf_unittest.UnittestProto.TestAllTypes.NestedMessage;
63 import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder;
64 import protobuf_unittest.UnittestProto.TestExtremeDefaultValues;
65 import protobuf_unittest.UnittestProto.TestOneof2;
66 import protobuf_unittest.UnittestProto.TestPackedTypes;
67 import protobuf_unittest.UnittestProto.TestUnpackedTypes;
68 
69 import junit.framework.TestCase;
70 
71 import java.io.ByteArrayInputStream;
72 import java.io.ByteArrayOutputStream;
73 import java.io.ObjectInputStream;
74 import java.io.ObjectOutputStream;
75 import java.util.Arrays;
76 import java.util.Collections;
77 import java.util.Iterator;
78 import java.util.List;
79 
80 /**
81  * Unit test for generated messages and generated code.  See also
82  * {@link MessageTest}, which tests some generated message functionality.
83  *
84  * @author kenton@google.com Kenton Varda
85  */
86 public class GeneratedMessageTest extends TestCase {
87   TestUtil.ReflectionTester reflectionTester =
88     new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
89 
testDefaultInstance()90   public void testDefaultInstance() throws Exception {
91     assertSame(TestAllTypes.getDefaultInstance(),
92                TestAllTypes.getDefaultInstance().getDefaultInstanceForType());
93     assertSame(TestAllTypes.getDefaultInstance(),
94                TestAllTypes.newBuilder().getDefaultInstanceForType());
95   }
96 
testMessageOrBuilder()97   public void testMessageOrBuilder() throws Exception {
98     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
99     TestUtil.setAllFields(builder);
100     TestAllTypes message = builder.build();
101     TestUtil.assertAllFieldsSet(message);
102   }
103 
testUsingBuilderMultipleTimes()104   public void testUsingBuilderMultipleTimes() throws Exception {
105     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
106     // primitive field scalar and repeated
107     builder.setOptionalSfixed64(100);
108     builder.addRepeatedInt32(100);
109     // enum field scalar and repeated
110     builder.setOptionalImportEnum(UnittestImport.ImportEnum.IMPORT_BAR);
111     builder.addRepeatedImportEnum(UnittestImport.ImportEnum.IMPORT_BAR);
112     // proto field scalar and repeated
113     builder.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(1));
114     builder.addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(1));
115 
116     TestAllTypes value1 = builder.build();
117 
118     assertEquals(100, value1.getOptionalSfixed64());
119     assertEquals(100, value1.getRepeatedInt32(0));
120     assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
121         value1.getOptionalImportEnum());
122     assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
123         value1.getRepeatedImportEnum(0));
124     assertEquals(1, value1.getOptionalForeignMessage().getC());
125     assertEquals(1, value1.getRepeatedForeignMessage(0).getC());
126 
127     // Make sure that builder didn't update previously created values
128     builder.setOptionalSfixed64(200);
129     builder.setRepeatedInt32(0, 200);
130     builder.setOptionalImportEnum(UnittestImport.ImportEnum.IMPORT_FOO);
131     builder.setRepeatedImportEnum(0, UnittestImport.ImportEnum.IMPORT_FOO);
132     builder.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(2));
133     builder.setRepeatedForeignMessage(0, ForeignMessage.newBuilder().setC(2));
134 
135     TestAllTypes value2 = builder.build();
136 
137     // Make sure value1 didn't change.
138     assertEquals(100, value1.getOptionalSfixed64());
139     assertEquals(100, value1.getRepeatedInt32(0));
140     assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
141         value1.getOptionalImportEnum());
142     assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
143         value1.getRepeatedImportEnum(0));
144     assertEquals(1, value1.getOptionalForeignMessage().getC());
145     assertEquals(1, value1.getRepeatedForeignMessage(0).getC());
146 
147     // Make sure value2 is correct
148     assertEquals(200, value2.getOptionalSfixed64());
149     assertEquals(200, value2.getRepeatedInt32(0));
150     assertEquals(UnittestImport.ImportEnum.IMPORT_FOO,
151         value2.getOptionalImportEnum());
152     assertEquals(UnittestImport.ImportEnum.IMPORT_FOO,
153         value2.getRepeatedImportEnum(0));
154     assertEquals(2, value2.getOptionalForeignMessage().getC());
155     assertEquals(2, value2.getRepeatedForeignMessage(0).getC());
156   }
157 
testProtosShareRepeatedArraysIfDidntChange()158   public void testProtosShareRepeatedArraysIfDidntChange() throws Exception {
159     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
160     builder.addRepeatedInt32(100);
161     builder.addRepeatedForeignMessage(ForeignMessage.getDefaultInstance());
162 
163     TestAllTypes value1 = builder.build();
164     TestAllTypes value2 = value1.toBuilder().build();
165 
166     assertSame(value1.getRepeatedInt32List(), value2.getRepeatedInt32List());
167     assertSame(value1.getRepeatedForeignMessageList(),
168         value2.getRepeatedForeignMessageList());
169   }
170 
testRepeatedArraysAreImmutable()171   public void testRepeatedArraysAreImmutable() throws Exception {
172     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
173     builder.addRepeatedInt32(100);
174     builder.addRepeatedImportEnum(UnittestImport.ImportEnum.IMPORT_BAR);
175     builder.addRepeatedForeignMessage(ForeignMessage.getDefaultInstance());
176     assertIsUnmodifiable(builder.getRepeatedInt32List());
177     assertIsUnmodifiable(builder.getRepeatedImportEnumList());
178     assertIsUnmodifiable(builder.getRepeatedForeignMessageList());
179     assertIsUnmodifiable(builder.getRepeatedFloatList());
180 
181 
182     TestAllTypes value = builder.build();
183     assertIsUnmodifiable(value.getRepeatedInt32List());
184     assertIsUnmodifiable(value.getRepeatedImportEnumList());
185     assertIsUnmodifiable(value.getRepeatedForeignMessageList());
186     assertIsUnmodifiable(value.getRepeatedFloatList());
187   }
188 
testParsedMessagesAreImmutable()189   public void testParsedMessagesAreImmutable() throws Exception {
190     TestAllTypes value = TestAllTypes.parser().parseFrom(TestUtil.getAllSet().toByteString());
191     assertIsUnmodifiable(value.getRepeatedInt32List());
192     assertIsUnmodifiable(value.getRepeatedInt64List());
193     assertIsUnmodifiable(value.getRepeatedUint32List());
194     assertIsUnmodifiable(value.getRepeatedUint64List());
195     assertIsUnmodifiable(value.getRepeatedSint32List());
196     assertIsUnmodifiable(value.getRepeatedSint64List());
197     assertIsUnmodifiable(value.getRepeatedFixed32List());
198     assertIsUnmodifiable(value.getRepeatedFixed64List());
199     assertIsUnmodifiable(value.getRepeatedSfixed32List());
200     assertIsUnmodifiable(value.getRepeatedSfixed64List());
201     assertIsUnmodifiable(value.getRepeatedFloatList());
202     assertIsUnmodifiable(value.getRepeatedDoubleList());
203     assertIsUnmodifiable(value.getRepeatedBoolList());
204     assertIsUnmodifiable(value.getRepeatedStringList());
205     assertIsUnmodifiable(value.getRepeatedBytesList());
206     assertIsUnmodifiable(value.getRepeatedGroupList());
207     assertIsUnmodifiable(value.getRepeatedNestedMessageList());
208     assertIsUnmodifiable(value.getRepeatedForeignMessageList());
209     assertIsUnmodifiable(value.getRepeatedImportMessageList());
210     assertIsUnmodifiable(value.getRepeatedNestedEnumList());
211     assertIsUnmodifiable(value.getRepeatedForeignEnumList());
212     assertIsUnmodifiable(value.getRepeatedImportEnumList());
213   }
214 
assertIsUnmodifiable(List<?> list)215   private void assertIsUnmodifiable(List<?> list) {
216     if (list == Collections.emptyList()) {
217       // OKAY -- Need to check this b/c EmptyList allows you to call clear.
218     } else {
219       try {
220         list.clear();
221         fail("List wasn't immutable");
222       } catch (UnsupportedOperationException e) {
223         // good
224       }
225     }
226   }
227 
testSettersRejectNull()228   public void testSettersRejectNull() throws Exception {
229     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
230     try {
231       builder.setOptionalString(null);
232       fail("Exception was not thrown");
233     } catch (NullPointerException e) {
234       // We expect this exception.
235     }
236     try {
237       builder.setOptionalBytes(null);
238       fail("Exception was not thrown");
239     } catch (NullPointerException e) {
240       // We expect this exception.
241     }
242     try {
243       builder.setOptionalNestedMessage((TestAllTypes.NestedMessage) null);
244       fail("Exception was not thrown");
245     } catch (NullPointerException e) {
246       // We expect this exception.
247     }
248     try {
249       builder.setOptionalNestedMessage(
250           (TestAllTypes.NestedMessage.Builder) null);
251       fail("Exception was not thrown");
252     } catch (NullPointerException e) {
253       // We expect this exception.
254     }
255     try {
256       builder.setOptionalNestedEnum(null);
257       fail("Exception was not thrown");
258     } catch (NullPointerException e) {
259       // We expect this exception.
260     }
261     try {
262       builder.addRepeatedString(null);
263       fail("Exception was not thrown");
264     } catch (NullPointerException e) {
265       // We expect this exception.
266     }
267     try {
268       builder.addRepeatedBytes(null);
269       fail("Exception was not thrown");
270     } catch (NullPointerException e) {
271       // We expect this exception.
272     }
273     try {
274       builder.addRepeatedNestedMessage((TestAllTypes.NestedMessage) null);
275       fail("Exception was not thrown");
276     } catch (NullPointerException e) {
277       // We expect this exception.
278     }
279     try {
280       builder.addRepeatedNestedMessage(
281           (TestAllTypes.NestedMessage.Builder) null);
282       fail("Exception was not thrown");
283     } catch (NullPointerException e) {
284       // We expect this exception.
285     }
286     try {
287       builder.addRepeatedNestedEnum(null);
288       fail("Exception was not thrown");
289     } catch (NullPointerException e) {
290       // We expect this exception.
291     }
292   }
293 
testRepeatedSetters()294   public void testRepeatedSetters() throws Exception {
295     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
296     TestUtil.setAllFields(builder);
297     TestUtil.modifyRepeatedFields(builder);
298     TestAllTypes message = builder.build();
299     TestUtil.assertRepeatedFieldsModified(message);
300   }
301 
testRepeatedSettersRejectNull()302   public void testRepeatedSettersRejectNull() throws Exception {
303     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
304 
305     builder.addRepeatedString("one");
306     builder.addRepeatedString("two");
307     try {
308       builder.setRepeatedString(1, null);
309       fail("Exception was not thrown");
310     } catch (NullPointerException e) {
311       // We expect this exception.
312     }
313 
314     builder.addRepeatedBytes(TestUtil.toBytes("one"));
315     builder.addRepeatedBytes(TestUtil.toBytes("two"));
316     try {
317       builder.setRepeatedBytes(1, null);
318       fail("Exception was not thrown");
319     } catch (NullPointerException e) {
320       // We expect this exception.
321     }
322 
323     builder.addRepeatedNestedMessage(
324       TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
325     builder.addRepeatedNestedMessage(
326       TestAllTypes.NestedMessage.newBuilder().setBb(456).build());
327     try {
328       builder.setRepeatedNestedMessage(1, (TestAllTypes.NestedMessage) null);
329       fail("Exception was not thrown");
330     } catch (NullPointerException e) {
331       // We expect this exception.
332     }
333     try {
334       builder.setRepeatedNestedMessage(
335           1, (TestAllTypes.NestedMessage.Builder) null);
336       fail("Exception was not thrown");
337     } catch (NullPointerException e) {
338       // We expect this exception.
339     }
340 
341     builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.FOO);
342     builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAR);
343     try {
344       builder.setRepeatedNestedEnum(1, null);
345       fail("Exception was not thrown");
346     } catch (NullPointerException e) {
347       // We expect this exception.
348     }
349   }
350 
testRepeatedAppend()351   public void testRepeatedAppend() throws Exception {
352     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
353 
354     builder.addAllRepeatedInt32(Arrays.asList(1, 2, 3, 4));
355     builder.addAllRepeatedForeignEnum(Arrays.asList(ForeignEnum.FOREIGN_BAZ));
356 
357     ForeignMessage foreignMessage =
358         ForeignMessage.newBuilder().setC(12).build();
359     builder.addAllRepeatedForeignMessage(Arrays.asList(foreignMessage));
360 
361     TestAllTypes message = builder.build();
362     assertEquals(message.getRepeatedInt32List(), Arrays.asList(1, 2, 3, 4));
363     assertEquals(message.getRepeatedForeignEnumList(),
364         Arrays.asList(ForeignEnum.FOREIGN_BAZ));
365     assertEquals(1, message.getRepeatedForeignMessageCount());
366     assertEquals(12, message.getRepeatedForeignMessage(0).getC());
367   }
368 
testRepeatedAppendRejectsNull()369   public void testRepeatedAppendRejectsNull() throws Exception {
370     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
371 
372     ForeignMessage foreignMessage =
373         ForeignMessage.newBuilder().setC(12).build();
374     try {
375       builder.addAllRepeatedForeignMessage(
376           Arrays.asList(foreignMessage, (ForeignMessage) null));
377       fail("Exception was not thrown");
378     } catch (NullPointerException e) {
379       // We expect this exception.
380     }
381 
382     try {
383       builder.addAllRepeatedForeignEnum(
384           Arrays.asList(ForeignEnum.FOREIGN_BAZ, null));
385       fail("Exception was not thrown");
386     } catch (NullPointerException e) {
387       // We expect this exception.
388     }
389 
390     try {
391       builder.addAllRepeatedString(Arrays.asList("one", null));
392       fail("Exception was not thrown");
393     } catch (NullPointerException e) {
394       // We expect this exception.
395     }
396 
397     try {
398       builder.addAllRepeatedBytes(Arrays.asList(TestUtil.toBytes("one"), null));
399       fail("Exception was not thrown");
400     } catch (NullPointerException e) {
401       // We expect this exception.
402     }
403   }
404 
testRepeatedAppendIterateOnlyOnce()405   public void testRepeatedAppendIterateOnlyOnce() throws Exception {
406     // Create a Iterable that can only be iterated once.
407     Iterable<String> stringIterable = new Iterable<String>() {
408       private boolean called = false;
409       @Override
410       public Iterator<String> iterator() {
411         if (called) {
412           throw new IllegalStateException();
413         }
414         called = true;
415         return Arrays.asList("one", "two", "three").iterator();
416       }
417     };
418     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
419     builder.addAllRepeatedString(stringIterable);
420     assertEquals(3, builder.getRepeatedStringCount());
421     assertEquals("one", builder.getRepeatedString(0));
422     assertEquals("two", builder.getRepeatedString(1));
423     assertEquals("three", builder.getRepeatedString(2));
424 
425     try {
426       builder.addAllRepeatedString(stringIterable);
427       fail("Exception was not thrown");
428     } catch (IllegalStateException e) {
429       // We expect this exception.
430     }
431   }
432 
testMergeFromOtherRejectsNull()433   public void testMergeFromOtherRejectsNull() throws Exception {
434     try {
435       TestAllTypes.Builder builder = TestAllTypes.newBuilder();
436       builder.mergeFrom((TestAllTypes) null);
437       fail("Exception was not thrown");
438     } catch (NullPointerException e) {
439       // We expect this exception.
440     }
441   }
442 
testSettingForeignMessageUsingBuilder()443   public void testSettingForeignMessageUsingBuilder() throws Exception {
444     TestAllTypes message = TestAllTypes.newBuilder()
445         // Pass builder for foreign message instance.
446         .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(123))
447         .build();
448     TestAllTypes expectedMessage = TestAllTypes.newBuilder()
449         // Create expected version passing foreign message instance explicitly.
450         .setOptionalForeignMessage(
451             ForeignMessage.newBuilder().setC(123).build())
452         .build();
453     // TODO(ngd): Upgrade to using real #equals method once implemented
454     assertEquals(expectedMessage.toString(), message.toString());
455   }
456 
testSettingRepeatedForeignMessageUsingBuilder()457   public void testSettingRepeatedForeignMessageUsingBuilder() throws Exception {
458     TestAllTypes message = TestAllTypes.newBuilder()
459         // Pass builder for foreign message instance.
460         .addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(456))
461         .build();
462     TestAllTypes expectedMessage = TestAllTypes.newBuilder()
463         // Create expected version passing foreign message instance explicitly.
464         .addRepeatedForeignMessage(
465             ForeignMessage.newBuilder().setC(456).build())
466         .build();
467     assertEquals(expectedMessage.toString(), message.toString());
468   }
469 
testDefaults()470   public void testDefaults() throws Exception {
471     TestUtil.assertClear(TestAllTypes.getDefaultInstance());
472     TestUtil.assertClear(TestAllTypes.newBuilder().build());
473 
474     TestExtremeDefaultValues message =
475         TestExtremeDefaultValues.getDefaultInstance();
476     assertEquals("\u1234", message.getUtf8String());
477     assertEquals(Double.POSITIVE_INFINITY, message.getInfDouble());
478     assertEquals(Double.NEGATIVE_INFINITY, message.getNegInfDouble());
479     assertTrue(Double.isNaN(message.getNanDouble()));
480     assertEquals(Float.POSITIVE_INFINITY, message.getInfFloat());
481     assertEquals(Float.NEGATIVE_INFINITY, message.getNegInfFloat());
482     assertTrue(Float.isNaN(message.getNanFloat()));
483     assertEquals("? ? ?? ?? ??? ??/ ??-", message.getCppTrigraph());
484   }
485 
testClear()486   public void testClear() throws Exception {
487     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
488     TestUtil.assertClear(builder);
489     TestUtil.setAllFields(builder);
490     builder.clear();
491     TestUtil.assertClear(builder);
492   }
493 
testReflectionGetters()494   public void testReflectionGetters() throws Exception {
495     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
496     TestUtil.setAllFields(builder);
497     reflectionTester.assertAllFieldsSetViaReflection(builder);
498 
499     TestAllTypes message = builder.build();
500     reflectionTester.assertAllFieldsSetViaReflection(message);
501   }
502 
testReflectionSetters()503   public void testReflectionSetters() throws Exception {
504     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
505     reflectionTester.setAllFieldsViaReflection(builder);
506     TestUtil.assertAllFieldsSet(builder);
507 
508     TestAllTypes message = builder.build();
509     TestUtil.assertAllFieldsSet(message);
510   }
511 
testReflectionSettersRejectNull()512   public void testReflectionSettersRejectNull() throws Exception {
513     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
514     reflectionTester.assertReflectionSettersRejectNull(builder);
515   }
516 
testReflectionRepeatedSetters()517   public void testReflectionRepeatedSetters() throws Exception {
518     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
519     reflectionTester.setAllFieldsViaReflection(builder);
520     reflectionTester.modifyRepeatedFieldsViaReflection(builder);
521     TestUtil.assertRepeatedFieldsModified(builder);
522 
523     TestAllTypes message = builder.build();
524     TestUtil.assertRepeatedFieldsModified(message);
525   }
526 
testReflectionRepeatedSettersRejectNull()527   public void testReflectionRepeatedSettersRejectNull() throws Exception {
528     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
529     reflectionTester.assertReflectionRepeatedSettersRejectNull(builder);
530   }
531 
testReflectionDefaults()532   public void testReflectionDefaults() throws Exception {
533     reflectionTester.assertClearViaReflection(
534       TestAllTypes.getDefaultInstance());
535     reflectionTester.assertClearViaReflection(
536       TestAllTypes.newBuilder().build());
537   }
538 
testReflectionGetOneof()539   public void testReflectionGetOneof() throws Exception {
540     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
541     reflectionTester.setAllFieldsViaReflection(builder);
542     Descriptors.OneofDescriptor oneof =
543         TestAllTypes.getDescriptor().getOneofs().get(0);
544     Descriptors.FieldDescriptor field =
545         TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
546     assertSame(field, builder.getOneofFieldDescriptor(oneof));
547 
548     TestAllTypes message = builder.build();
549     assertSame(field, message.getOneofFieldDescriptor(oneof));
550   }
551 
testReflectionClearOneof()552   public void testReflectionClearOneof() throws Exception {
553     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
554     reflectionTester.setAllFieldsViaReflection(builder);
555     Descriptors.OneofDescriptor oneof =
556         TestAllTypes.getDescriptor().getOneofs().get(0);
557     Descriptors.FieldDescriptor field =
558         TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
559 
560     assertTrue(builder.hasOneof(oneof));
561     assertTrue(builder.hasField(field));
562     builder.clearOneof(oneof);
563     assertFalse(builder.hasOneof(oneof));
564     assertFalse(builder.hasField(field));
565   }
566 
testEnumInterface()567   public void testEnumInterface() throws Exception {
568     assertTrue(TestAllTypes.getDefaultInstance().getDefaultNestedEnum()
569         instanceof ProtocolMessageEnum);
570   }
571 
testEnumMap()572   public void testEnumMap() throws Exception {
573     Internal.EnumLiteMap<ForeignEnum> map = ForeignEnum.internalGetValueMap();
574 
575     for (ForeignEnum value : ForeignEnum.values()) {
576       assertEquals(value, map.findValueByNumber(value.getNumber()));
577     }
578 
579     assertTrue(map.findValueByNumber(12345) == null);
580   }
581 
testParsePackedToUnpacked()582   public void testParsePackedToUnpacked() throws Exception {
583     TestUnpackedTypes.Builder builder = TestUnpackedTypes.newBuilder();
584     TestUnpackedTypes message =
585       builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
586     TestUtil.assertUnpackedFieldsSet(message);
587   }
588 
testParseUnpackedToPacked()589   public void testParseUnpackedToPacked() throws Exception {
590     TestPackedTypes.Builder builder = TestPackedTypes.newBuilder();
591     TestPackedTypes message =
592       builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
593     TestUtil.assertPackedFieldsSet(message);
594   }
595 
596   // =================================================================
597   // Extensions.
598 
599   TestUtil.ReflectionTester extensionsReflectionTester =
600     new TestUtil.ReflectionTester(TestAllExtensions.getDescriptor(),
601                                   TestUtil.getExtensionRegistry());
602 
testExtensionMessageOrBuilder()603   public void testExtensionMessageOrBuilder() throws Exception {
604     TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
605     TestUtil.setAllExtensions(builder);
606     TestAllExtensions message = builder.build();
607     TestUtil.assertAllExtensionsSet(message);
608   }
609 
testExtensionRepeatedSetters()610   public void testExtensionRepeatedSetters() throws Exception {
611     TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
612     TestUtil.setAllExtensions(builder);
613     TestUtil.modifyRepeatedExtensions(builder);
614     TestAllExtensions message = builder.build();
615     TestUtil.assertRepeatedExtensionsModified(message);
616   }
617 
testExtensionDefaults()618   public void testExtensionDefaults() throws Exception {
619     TestUtil.assertExtensionsClear(TestAllExtensions.getDefaultInstance());
620     TestUtil.assertExtensionsClear(TestAllExtensions.newBuilder().build());
621   }
622 
testUnsetRepeatedExtensionGetField()623   public void testUnsetRepeatedExtensionGetField() {
624     TestAllExtensions message = TestAllExtensions.getDefaultInstance();
625     Object value;
626 
627     value = message.getField(UnittestProto.repeatedStringExtension.getDescriptor());
628     assertTrue(value instanceof List);
629     assertTrue(((List<?>) value).isEmpty());
630     assertIsUnmodifiable((List<?>) value);
631 
632     value = message.getField(UnittestProto.repeatedNestedMessageExtension.getDescriptor());
633     assertTrue(value instanceof List);
634     assertTrue(((List<?>) value).isEmpty());
635     assertIsUnmodifiable((List<?>) value);
636   }
637 
testExtensionReflectionGetters()638   public void testExtensionReflectionGetters() throws Exception {
639     TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
640     TestUtil.setAllExtensions(builder);
641     extensionsReflectionTester.assertAllFieldsSetViaReflection(builder);
642 
643     TestAllExtensions message = builder.build();
644     extensionsReflectionTester.assertAllFieldsSetViaReflection(message);
645   }
646 
testExtensionReflectionSetters()647   public void testExtensionReflectionSetters() throws Exception {
648     TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
649     extensionsReflectionTester.setAllFieldsViaReflection(builder);
650     TestUtil.assertAllExtensionsSet(builder);
651 
652     TestAllExtensions message = builder.build();
653     TestUtil.assertAllExtensionsSet(message);
654   }
655 
testExtensionReflectionSettersRejectNull()656   public void testExtensionReflectionSettersRejectNull() throws Exception {
657     TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
658     extensionsReflectionTester.assertReflectionSettersRejectNull(builder);
659   }
660 
testExtensionReflectionRepeatedSetters()661   public void testExtensionReflectionRepeatedSetters() throws Exception {
662     TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
663     extensionsReflectionTester.setAllFieldsViaReflection(builder);
664     extensionsReflectionTester.modifyRepeatedFieldsViaReflection(builder);
665     TestUtil.assertRepeatedExtensionsModified(builder);
666 
667     TestAllExtensions message = builder.build();
668     TestUtil.assertRepeatedExtensionsModified(message);
669   }
670 
testExtensionReflectionRepeatedSettersRejectNull()671   public void testExtensionReflectionRepeatedSettersRejectNull()
672       throws Exception {
673     TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
674     extensionsReflectionTester.assertReflectionRepeatedSettersRejectNull(
675         builder);
676   }
677 
testExtensionReflectionDefaults()678   public void testExtensionReflectionDefaults() throws Exception {
679     extensionsReflectionTester.assertClearViaReflection(
680       TestAllExtensions.getDefaultInstance());
681     extensionsReflectionTester.assertClearViaReflection(
682       TestAllExtensions.newBuilder().build());
683   }
684 
testClearExtension()685   public void testClearExtension() throws Exception {
686     // clearExtension() is not actually used in TestUtil, so try it manually.
687     assertFalse(
688       TestAllExtensions.newBuilder()
689         .setExtension(UnittestProto.optionalInt32Extension, 1)
690         .clearExtension(UnittestProto.optionalInt32Extension)
691         .hasExtension(UnittestProto.optionalInt32Extension));
692     assertEquals(0,
693       TestAllExtensions.newBuilder()
694         .addExtension(UnittestProto.repeatedInt32Extension, 1)
695         .clearExtension(UnittestProto.repeatedInt32Extension)
696         .getExtensionCount(UnittestProto.repeatedInt32Extension));
697   }
698 
testExtensionCopy()699   public void testExtensionCopy() throws Exception {
700     TestAllExtensions original = TestUtil.getAllExtensionsSet();
701     TestAllExtensions copy = TestAllExtensions.newBuilder(original).build();
702     TestUtil.assertAllExtensionsSet(copy);
703   }
704 
testExtensionMergeFrom()705   public void testExtensionMergeFrom() throws Exception {
706     TestAllExtensions original =
707       TestAllExtensions.newBuilder()
708         .setExtension(UnittestProto.optionalInt32Extension, 1).build();
709     TestAllExtensions merged =
710         TestAllExtensions.newBuilder().mergeFrom(original).build();
711     assertTrue(merged.hasExtension(UnittestProto.optionalInt32Extension));
712     assertEquals(
713         1, (int) merged.getExtension(UnittestProto.optionalInt32Extension));
714   }
715 
716   // =================================================================
717   // Lite Extensions.
718 
719   // We test lite extensions directly because they have a separate
720   // implementation from full extensions.  In contrast, we do not test
721   // lite fields directly since they are implemented exactly the same as
722   // regular fields.
723 
testLiteExtensionMessageOrBuilder()724   public void testLiteExtensionMessageOrBuilder() throws Exception {
725     TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder();
726     TestUtilLite.setAllExtensions(builder);
727     TestUtil.assertAllExtensionsSet(builder);
728 
729     TestAllExtensionsLite message = builder.build();
730     TestUtil.assertAllExtensionsSet(message);
731   }
732 
testLiteExtensionRepeatedSetters()733   public void testLiteExtensionRepeatedSetters() throws Exception {
734     TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder();
735     TestUtilLite.setAllExtensions(builder);
736     TestUtilLite.modifyRepeatedExtensions(builder);
737     TestUtil.assertRepeatedExtensionsModified(builder);
738 
739     TestAllExtensionsLite message = builder.build();
740     TestUtil.assertRepeatedExtensionsModified(message);
741   }
742 
testLiteExtensionDefaults()743   public void testLiteExtensionDefaults() throws Exception {
744     TestUtil.assertExtensionsClear(TestAllExtensionsLite.getDefaultInstance());
745     TestUtil.assertExtensionsClear(TestAllExtensionsLite.newBuilder().build());
746   }
747 
testClearLiteExtension()748   public void testClearLiteExtension() throws Exception {
749     // clearExtension() is not actually used in TestUtil, so try it manually.
750     assertFalse(
751       TestAllExtensionsLite.newBuilder()
752         .setExtension(UnittestLite.optionalInt32ExtensionLite, 1)
753         .clearExtension(UnittestLite.optionalInt32ExtensionLite)
754         .hasExtension(UnittestLite.optionalInt32ExtensionLite));
755     assertEquals(0,
756       TestAllExtensionsLite.newBuilder()
757         .addExtension(UnittestLite.repeatedInt32ExtensionLite, 1)
758         .clearExtension(UnittestLite.repeatedInt32ExtensionLite)
759         .getExtensionCount(UnittestLite.repeatedInt32ExtensionLite));
760   }
761 
testLiteExtensionCopy()762   public void testLiteExtensionCopy() throws Exception {
763     TestAllExtensionsLite original = TestUtilLite.getAllLiteExtensionsSet();
764     TestAllExtensionsLite copy =
765         TestAllExtensionsLite.newBuilder(original).build();
766     TestUtil.assertAllExtensionsSet(copy);
767   }
768 
testLiteExtensionMergeFrom()769   public void testLiteExtensionMergeFrom() throws Exception {
770     TestAllExtensionsLite original =
771       TestAllExtensionsLite.newBuilder()
772         .setExtension(UnittestLite.optionalInt32ExtensionLite, 1).build();
773     TestAllExtensionsLite merged =
774         TestAllExtensionsLite.newBuilder().mergeFrom(original).build();
775     assertTrue(merged.hasExtension(UnittestLite.optionalInt32ExtensionLite));
776     assertEquals(
777         1, (int) merged.getExtension(UnittestLite.optionalInt32ExtensionLite));
778   }
779 
780   // =================================================================
781   // multiple_files_test
782 
783   // Test that custom options of an file level enum are properly initialized.
784   // This test needs to be put before any other access to MultipleFilesTestProto
785   // or messages defined in multiple_files_test.proto because the class loading
786   // order affects initialization process of custom options.
testEnumValueOptionsInMultipleFilesMode()787   public void testEnumValueOptionsInMultipleFilesMode() throws Exception {
788     assertEquals(12345, EnumWithNoOuter.FOO.getValueDescriptor().getOptions()
789         .getExtension(MultipleFilesTestProto.enumValueOption).intValue());
790   }
791 
testMultipleFilesOption()792   public void testMultipleFilesOption() throws Exception {
793     // We mostly just want to check that things compile.
794     MessageWithNoOuter message =
795       MessageWithNoOuter.newBuilder()
796         .setNested(MessageWithNoOuter.NestedMessage.newBuilder().setI(1))
797         .addForeign(TestAllTypes.newBuilder().setOptionalInt32(1))
798         .setNestedEnum(MessageWithNoOuter.NestedEnum.BAZ)
799         .setForeignEnum(EnumWithNoOuter.BAR)
800         .build();
801     assertEquals(message, MessageWithNoOuter.parseFrom(message.toByteString()));
802 
803     assertEquals(MultipleFilesTestProto.getDescriptor(),
804                  MessageWithNoOuter.getDescriptor().getFile());
805 
806     Descriptors.FieldDescriptor field =
807       MessageWithNoOuter.getDescriptor().findFieldByName("foreign_enum");
808     assertEquals(EnumWithNoOuter.BAR.getValueDescriptor(),
809                  message.getField(field));
810 
811     assertEquals(MultipleFilesTestProto.getDescriptor(),
812                  ServiceWithNoOuter.getDescriptor().getFile());
813 
814     assertFalse(
815       TestAllExtensions.getDefaultInstance().hasExtension(
816         MultipleFilesTestProto.extensionWithOuter));
817   }
818 
testOptionalFieldWithRequiredSubfieldsOptimizedForSize()819   public void testOptionalFieldWithRequiredSubfieldsOptimizedForSize()
820     throws Exception {
821     TestOptionalOptimizedForSize message =
822         TestOptionalOptimizedForSize.getDefaultInstance();
823     assertTrue(message.isInitialized());
824 
825     message = TestOptionalOptimizedForSize.newBuilder().setO(
826         TestRequiredOptimizedForSize.newBuilder().buildPartial()
827         ).buildPartial();
828     assertFalse(message.isInitialized());
829 
830     message = TestOptionalOptimizedForSize.newBuilder().setO(
831         TestRequiredOptimizedForSize.newBuilder().setX(5).buildPartial()
832         ).buildPartial();
833     assertTrue(message.isInitialized());
834   }
835 
testUninitializedExtensionInOptimizedForSize()836   public void testUninitializedExtensionInOptimizedForSize()
837       throws Exception {
838     TestOptimizedForSize.Builder builder = TestOptimizedForSize.newBuilder();
839     builder.setExtension(TestOptimizedForSize.testExtension2,
840         TestRequiredOptimizedForSize.newBuilder().buildPartial());
841     assertFalse(builder.isInitialized());
842     assertFalse(builder.buildPartial().isInitialized());
843 
844     builder = TestOptimizedForSize.newBuilder();
845     builder.setExtension(TestOptimizedForSize.testExtension2,
846         TestRequiredOptimizedForSize.newBuilder().setX(10).buildPartial());
847     assertTrue(builder.isInitialized());
848     assertTrue(builder.buildPartial().isInitialized());
849   }
850 
testToBuilder()851   public void testToBuilder() throws Exception {
852     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
853     TestUtil.setAllFields(builder);
854     TestAllTypes message = builder.build();
855     TestUtil.assertAllFieldsSet(message);
856     TestUtil.assertAllFieldsSet(message.toBuilder().build());
857   }
858 
testFieldConstantValues()859   public void testFieldConstantValues() throws Exception {
860     assertEquals(TestAllTypes.NestedMessage.BB_FIELD_NUMBER, 1);
861     assertEquals(TestAllTypes.OPTIONAL_INT32_FIELD_NUMBER, 1);
862     assertEquals(TestAllTypes.OPTIONALGROUP_FIELD_NUMBER, 16);
863     assertEquals(TestAllTypes.OPTIONAL_NESTED_MESSAGE_FIELD_NUMBER, 18);
864     assertEquals(TestAllTypes.OPTIONAL_NESTED_ENUM_FIELD_NUMBER, 21);
865     assertEquals(TestAllTypes.REPEATED_INT32_FIELD_NUMBER, 31);
866     assertEquals(TestAllTypes.REPEATEDGROUP_FIELD_NUMBER, 46);
867     assertEquals(TestAllTypes.REPEATED_NESTED_MESSAGE_FIELD_NUMBER, 48);
868     assertEquals(TestAllTypes.REPEATED_NESTED_ENUM_FIELD_NUMBER, 51);
869   }
870 
testExtensionConstantValues()871   public void testExtensionConstantValues() throws Exception {
872     assertEquals(UnittestProto.TestRequired.SINGLE_FIELD_NUMBER, 1000);
873     assertEquals(UnittestProto.TestRequired.MULTI_FIELD_NUMBER, 1001);
874     assertEquals(UnittestProto.OPTIONAL_INT32_EXTENSION_FIELD_NUMBER, 1);
875     assertEquals(UnittestProto.OPTIONALGROUP_EXTENSION_FIELD_NUMBER, 16);
876     assertEquals(
877       UnittestProto.OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 18);
878     assertEquals(UnittestProto.OPTIONAL_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 21);
879     assertEquals(UnittestProto.REPEATED_INT32_EXTENSION_FIELD_NUMBER, 31);
880     assertEquals(UnittestProto.REPEATEDGROUP_EXTENSION_FIELD_NUMBER, 46);
881     assertEquals(
882       UnittestProto.REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 48);
883     assertEquals(UnittestProto.REPEATED_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 51);
884   }
885 
testRecursiveMessageDefaultInstance()886   public void testRecursiveMessageDefaultInstance() throws Exception {
887     UnittestProto.TestRecursiveMessage message =
888         UnittestProto.TestRecursiveMessage.getDefaultInstance();
889     assertTrue(message != null);
890     assertNotNull(message.getA());
891     assertTrue(message.getA() == message);
892   }
893 
testSerialize()894   public void testSerialize() throws Exception {
895     ByteArrayOutputStream baos = new ByteArrayOutputStream();
896     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
897     TestUtil.setAllFields(builder);
898     TestAllTypes expected = builder.build();
899     ObjectOutputStream out = new ObjectOutputStream(baos);
900     try {
901       out.writeObject(expected);
902     } finally {
903       out.close();
904     }
905     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
906     ObjectInputStream in = new ObjectInputStream(bais);
907     TestAllTypes actual = (TestAllTypes) in.readObject();
908     assertEquals(expected, actual);
909   }
910 
testSerializePartial()911   public void testSerializePartial() throws Exception {
912     ByteArrayOutputStream baos = new ByteArrayOutputStream();
913     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
914     TestAllTypes expected = builder.buildPartial();
915     ObjectOutputStream out = new ObjectOutputStream(baos);
916     try {
917       out.writeObject(expected);
918     } finally {
919       out.close();
920     }
921     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
922     ObjectInputStream in = new ObjectInputStream(bais);
923     TestAllTypes actual = (TestAllTypes) in.readObject();
924     assertEquals(expected, actual);
925   }
926 
testEnumValues()927   public void testEnumValues() {
928      assertEquals(
929          TestAllTypes.NestedEnum.BAR.getNumber(),
930          TestAllTypes.NestedEnum.BAR_VALUE);
931     assertEquals(
932         TestAllTypes.NestedEnum.BAZ.getNumber(),
933         TestAllTypes.NestedEnum.BAZ_VALUE);
934     assertEquals(
935         TestAllTypes.NestedEnum.FOO.getNumber(),
936         TestAllTypes.NestedEnum.FOO_VALUE);
937   }
938 
testNonNestedExtensionInitialization()939   public void testNonNestedExtensionInitialization() {
940     assertTrue(NonNestedExtension.nonNestedExtension
941                .getMessageDefaultInstance() instanceof MyNonNestedExtension);
942     assertEquals("nonNestedExtension",
943                  NonNestedExtension.nonNestedExtension.getDescriptor().getName());
944   }
945 
testNestedExtensionInitialization()946   public void testNestedExtensionInitialization() {
947     assertTrue(MyNestedExtension.recursiveExtension.getMessageDefaultInstance()
948                instanceof MessageToBeExtended);
949     assertEquals("recursiveExtension",
950                  MyNestedExtension.recursiveExtension.getDescriptor().getName());
951   }
952 
testNonNestedExtensionLiteInitialization()953   public void testNonNestedExtensionLiteInitialization() {
954     assertTrue(NonNestedExtensionLite.nonNestedExtensionLite
955                .getMessageDefaultInstance() instanceof MyNonNestedExtensionLite);
956   }
957 
testNestedExtensionLiteInitialization()958   public void testNestedExtensionLiteInitialization() {
959     assertTrue(MyNestedExtensionLite.recursiveExtensionLite
960                .getMessageDefaultInstance() instanceof MessageLiteToBeExtended);
961   }
962 
testInvalidations()963   public void testInvalidations() throws Exception {
964     GeneratedMessage.enableAlwaysUseFieldBuildersForTesting();
965     TestAllTypes.NestedMessage nestedMessage1 =
966         TestAllTypes.NestedMessage.newBuilder().build();
967     TestAllTypes.NestedMessage nestedMessage2 =
968         TestAllTypes.NestedMessage.newBuilder().build();
969 
970     // Set all three flavors (enum, primitive, message and singular/repeated)
971     // and verify no invalidations fired
972     TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
973 
974     TestAllTypes.Builder builder = (TestAllTypes.Builder)
975         ((GeneratedMessage) TestAllTypes.getDefaultInstance()).
976             newBuilderForType(mockParent);
977     builder.setOptionalInt32(1);
978     builder.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAR);
979     builder.setOptionalNestedMessage(nestedMessage1);
980     builder.addRepeatedInt32(1);
981     builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAR);
982     builder.addRepeatedNestedMessage(nestedMessage1);
983     assertEquals(0, mockParent.getInvalidationCount());
984 
985     // Now tell it we want changes and make sure it's only fired once
986     // And do this for each flavor
987 
988     // primitive single
989     builder.buildPartial();
990     builder.setOptionalInt32(2);
991     builder.setOptionalInt32(3);
992     assertEquals(1, mockParent.getInvalidationCount());
993 
994     // enum single
995     builder.buildPartial();
996     builder.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAZ);
997     builder.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAR);
998     assertEquals(2, mockParent.getInvalidationCount());
999 
1000     // message single
1001     builder.buildPartial();
1002     builder.setOptionalNestedMessage(nestedMessage2);
1003     builder.setOptionalNestedMessage(nestedMessage1);
1004     assertEquals(3, mockParent.getInvalidationCount());
1005 
1006     // primitive repeated
1007     builder.buildPartial();
1008     builder.addRepeatedInt32(2);
1009     builder.addRepeatedInt32(3);
1010     assertEquals(4, mockParent.getInvalidationCount());
1011 
1012     // enum repeated
1013     builder.buildPartial();
1014     builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAZ);
1015     builder.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAZ);
1016     assertEquals(5, mockParent.getInvalidationCount());
1017 
1018     // message repeated
1019     builder.buildPartial();
1020     builder.addRepeatedNestedMessage(nestedMessage2);
1021     builder.addRepeatedNestedMessage(nestedMessage1);
1022     assertEquals(6, mockParent.getInvalidationCount());
1023 
1024   }
1025 
testInvalidations_Extensions()1026   public void testInvalidations_Extensions() throws Exception {
1027     TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
1028 
1029     TestAllExtensions.Builder builder = (TestAllExtensions.Builder)
1030         ((GeneratedMessage) TestAllExtensions.getDefaultInstance()).
1031             newBuilderForType(mockParent);
1032 
1033     builder.addExtension(UnittestProto.repeatedInt32Extension, 1);
1034     builder.setExtension(UnittestProto.repeatedInt32Extension, 0, 2);
1035     builder.clearExtension(UnittestProto.repeatedInt32Extension);
1036     assertEquals(0, mockParent.getInvalidationCount());
1037 
1038     // Now tell it we want changes and make sure it's only fired once
1039     builder.buildPartial();
1040     builder.addExtension(UnittestProto.repeatedInt32Extension, 2);
1041     builder.addExtension(UnittestProto.repeatedInt32Extension, 3);
1042     assertEquals(1, mockParent.getInvalidationCount());
1043 
1044     builder.buildPartial();
1045     builder.setExtension(UnittestProto.repeatedInt32Extension, 0, 4);
1046     builder.setExtension(UnittestProto.repeatedInt32Extension, 1, 5);
1047     assertEquals(2, mockParent.getInvalidationCount());
1048 
1049     builder.buildPartial();
1050     builder.clearExtension(UnittestProto.repeatedInt32Extension);
1051     builder.clearExtension(UnittestProto.repeatedInt32Extension);
1052     assertEquals(3, mockParent.getInvalidationCount());
1053   }
1054 
testBaseMessageOrBuilder()1055   public void testBaseMessageOrBuilder() {
1056     // Mostly just makes sure the base interface exists and has some methods.
1057     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
1058     TestAllTypes message = builder.buildPartial();
1059     TestAllTypesOrBuilder builderAsInterface = (TestAllTypesOrBuilder) builder;
1060     TestAllTypesOrBuilder messageAsInterface = (TestAllTypesOrBuilder) message;
1061 
1062     assertEquals(
1063         messageAsInterface.getDefaultBool(),
1064         messageAsInterface.getDefaultBool());
1065     assertEquals(
1066         messageAsInterface.getOptionalDouble(),
1067         messageAsInterface.getOptionalDouble());
1068   }
1069 
testMessageOrBuilderGetters()1070   public void testMessageOrBuilderGetters() {
1071     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
1072 
1073     // single fields
1074     assertSame(ForeignMessage.getDefaultInstance(),
1075         builder.getOptionalForeignMessageOrBuilder());
1076     ForeignMessage.Builder subBuilder =
1077         builder.getOptionalForeignMessageBuilder();
1078     assertSame(subBuilder, builder.getOptionalForeignMessageOrBuilder());
1079 
1080     // repeated fields
1081     ForeignMessage m0 = ForeignMessage.newBuilder().buildPartial();
1082     ForeignMessage m1 = ForeignMessage.newBuilder().buildPartial();
1083     ForeignMessage m2 = ForeignMessage.newBuilder().buildPartial();
1084     builder.addRepeatedForeignMessage(m0);
1085     builder.addRepeatedForeignMessage(m1);
1086     builder.addRepeatedForeignMessage(m2);
1087     assertSame(m0, builder.getRepeatedForeignMessageOrBuilder(0));
1088     assertSame(m1, builder.getRepeatedForeignMessageOrBuilder(1));
1089     assertSame(m2, builder.getRepeatedForeignMessageOrBuilder(2));
1090     ForeignMessage.Builder b0 = builder.getRepeatedForeignMessageBuilder(0);
1091     ForeignMessage.Builder b1 = builder.getRepeatedForeignMessageBuilder(1);
1092     assertSame(b0, builder.getRepeatedForeignMessageOrBuilder(0));
1093     assertSame(b1, builder.getRepeatedForeignMessageOrBuilder(1));
1094     assertSame(m2, builder.getRepeatedForeignMessageOrBuilder(2));
1095 
1096     List<? extends ForeignMessageOrBuilder> messageOrBuilderList =
1097         builder.getRepeatedForeignMessageOrBuilderList();
1098     assertSame(b0, messageOrBuilderList.get(0));
1099     assertSame(b1, messageOrBuilderList.get(1));
1100     assertSame(m2, messageOrBuilderList.get(2));
1101   }
1102 
testGetFieldBuilder()1103   public void testGetFieldBuilder() {
1104     Descriptor descriptor = TestAllTypes.getDescriptor();
1105 
1106     FieldDescriptor fieldDescriptor =
1107         descriptor.findFieldByName("optional_nested_message");
1108     FieldDescriptor foreignFieldDescriptor =
1109         descriptor.findFieldByName("optional_foreign_message");
1110     FieldDescriptor importFieldDescriptor =
1111         descriptor.findFieldByName("optional_import_message");
1112 
1113     // Mutate the message with new field builder
1114     // Mutate nested message
1115     TestAllTypes.Builder builder1 = TestAllTypes.newBuilder();
1116     Message.Builder fieldBuilder1 = builder1.newBuilderForField(fieldDescriptor)
1117         .mergeFrom((Message) builder1.getField(fieldDescriptor));
1118     FieldDescriptor subFieldDescriptor1 =
1119         fieldBuilder1.getDescriptorForType().findFieldByName("bb");
1120     fieldBuilder1.setField(subFieldDescriptor1, 1);
1121     builder1.setField(fieldDescriptor, fieldBuilder1.build());
1122 
1123     // Mutate foreign message
1124     Message.Builder foreignFieldBuilder1 = builder1.newBuilderForField(
1125         foreignFieldDescriptor)
1126         .mergeFrom((Message) builder1.getField(foreignFieldDescriptor));
1127     FieldDescriptor subForeignFieldDescriptor1 =
1128         foreignFieldBuilder1.getDescriptorForType().findFieldByName("c");
1129     foreignFieldBuilder1.setField(subForeignFieldDescriptor1, 2);
1130     builder1.setField(foreignFieldDescriptor, foreignFieldBuilder1.build());
1131 
1132     // Mutate import message
1133     Message.Builder importFieldBuilder1 = builder1.newBuilderForField(
1134         importFieldDescriptor)
1135         .mergeFrom((Message) builder1.getField(importFieldDescriptor));
1136     FieldDescriptor subImportFieldDescriptor1 =
1137         importFieldBuilder1.getDescriptorForType().findFieldByName("d");
1138     importFieldBuilder1.setField(subImportFieldDescriptor1, 3);
1139     builder1.setField(importFieldDescriptor, importFieldBuilder1.build());
1140 
1141     Message newMessage1 = builder1.build();
1142 
1143     // Mutate the message with existing field builder
1144     // Mutate nested message
1145     TestAllTypes.Builder builder2 = TestAllTypes.newBuilder();
1146     Message.Builder fieldBuilder2 = builder2.getFieldBuilder(fieldDescriptor);
1147     FieldDescriptor subFieldDescriptor2 =
1148         fieldBuilder2.getDescriptorForType().findFieldByName("bb");
1149     fieldBuilder2.setField(subFieldDescriptor2, 1);
1150     builder2.setField(fieldDescriptor, fieldBuilder2.build());
1151 
1152     // Mutate foreign message
1153     Message.Builder foreignFieldBuilder2 = builder2.newBuilderForField(
1154         foreignFieldDescriptor)
1155         .mergeFrom((Message) builder2.getField(foreignFieldDescriptor));
1156     FieldDescriptor subForeignFieldDescriptor2 =
1157         foreignFieldBuilder2.getDescriptorForType().findFieldByName("c");
1158     foreignFieldBuilder2.setField(subForeignFieldDescriptor2, 2);
1159     builder2.setField(foreignFieldDescriptor, foreignFieldBuilder2.build());
1160 
1161     // Mutate import message
1162     Message.Builder importFieldBuilder2 = builder2.newBuilderForField(
1163         importFieldDescriptor)
1164         .mergeFrom((Message) builder2.getField(importFieldDescriptor));
1165     FieldDescriptor subImportFieldDescriptor2 =
1166         importFieldBuilder2.getDescriptorForType().findFieldByName("d");
1167     importFieldBuilder2.setField(subImportFieldDescriptor2, 3);
1168     builder2.setField(importFieldDescriptor, importFieldBuilder2.build());
1169 
1170     Message newMessage2 = builder2.build();
1171 
1172     // These two messages should be equal.
1173     assertEquals(newMessage1, newMessage2);
1174   }
1175 
testGetFieldBuilderWithInitializedValue()1176   public void testGetFieldBuilderWithInitializedValue() {
1177     Descriptor descriptor = TestAllTypes.getDescriptor();
1178     FieldDescriptor fieldDescriptor =
1179         descriptor.findFieldByName("optional_nested_message");
1180 
1181     // Before setting field, builder is initialized by default value.
1182     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
1183     NestedMessage.Builder fieldBuilder =
1184         (NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor);
1185     assertEquals(0, fieldBuilder.getBb());
1186 
1187     // Setting field value with new field builder instance.
1188     builder = TestAllTypes.newBuilder();
1189     NestedMessage.Builder newFieldBuilder =
1190         builder.getOptionalNestedMessageBuilder();
1191     newFieldBuilder.setBb(2);
1192     // Then get the field builder instance by getFieldBuilder().
1193     fieldBuilder =
1194         (NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor);
1195     // It should contain new value.
1196     assertEquals(2, fieldBuilder.getBb());
1197     // These two builder should be equal.
1198     assertSame(fieldBuilder, newFieldBuilder);
1199   }
1200 
testGetFieldBuilderNotSupportedException()1201   public void testGetFieldBuilderNotSupportedException() {
1202     Descriptor descriptor = TestAllTypes.getDescriptor();
1203     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
1204     try {
1205       builder.getFieldBuilder(descriptor.findFieldByName("optional_int32"));
1206       fail("Exception was not thrown");
1207     } catch (UnsupportedOperationException e) {
1208       // We expect this exception.
1209     }
1210     try {
1211       builder.getFieldBuilder(
1212           descriptor.findFieldByName("optional_nested_enum"));
1213       fail("Exception was not thrown");
1214     } catch (UnsupportedOperationException e) {
1215       // We expect this exception.
1216     }
1217     try {
1218       builder.getFieldBuilder(descriptor.findFieldByName("repeated_int32"));
1219       fail("Exception was not thrown");
1220     } catch (UnsupportedOperationException e) {
1221       // We expect this exception.
1222     }
1223     try {
1224       builder.getFieldBuilder(
1225           descriptor.findFieldByName("repeated_nested_enum"));
1226       fail("Exception was not thrown");
1227     } catch (UnsupportedOperationException e) {
1228       // We expect this exception.
1229     }
1230     try {
1231       builder.getFieldBuilder(
1232           descriptor.findFieldByName("repeated_nested_message"));
1233       fail("Exception was not thrown");
1234     } catch (UnsupportedOperationException e) {
1235       // We expect this exception.
1236     }
1237   }
1238 
1239   // Test that when the default outer class name conflicts with another type
1240   // defined in the proto the compiler will append a suffix to avoid the
1241   // conflict.
testConflictingOuterClassName()1242   public void testConflictingOuterClassName() {
1243     // We just need to make sure we can refer to the outer class with the
1244     // expected name. There is nothing else to test.
1245     OuterClassNameTestOuterClass.OuterClassNameTest message =
1246         OuterClassNameTestOuterClass.OuterClassNameTest.newBuilder().build();
1247     assertTrue(message.getDescriptorForType() ==
1248         OuterClassNameTestOuterClass.OuterClassNameTest.getDescriptor());
1249 
1250     OuterClassNameTest2OuterClass.TestMessage2.NestedMessage.OuterClassNameTest2
1251         message2 = OuterClassNameTest2OuterClass.TestMessage2.NestedMessage
1252             .OuterClassNameTest2.newBuilder().build();
1253     assertEquals(0, message2.getSerializedSize());
1254 
1255     OuterClassNameTest3OuterClass.TestMessage3.NestedMessage.OuterClassNameTest3
1256         enumValue = OuterClassNameTest3OuterClass.TestMessage3.NestedMessage
1257             .OuterClassNameTest3.DUMMY_VALUE;
1258     assertEquals(1, enumValue.getNumber());
1259   }
1260 
1261   // =================================================================
1262   // oneof generated code test
testOneofEnumCase()1263   public void testOneofEnumCase() throws Exception {
1264     TestOneof2 message = TestOneof2.newBuilder()
1265         .setFooInt(123).setFooString("foo").setFooCord("bar").build();
1266     TestUtil.assertAtMostOneFieldSetOneof(message);
1267   }
1268 
testClearOneof()1269   public void testClearOneof() throws Exception {
1270     TestOneof2.Builder builder = TestOneof2.newBuilder().setFooInt(123);
1271     assertEquals(TestOneof2.FooCase.FOO_INT, builder.getFooCase());
1272     builder.clearFoo();
1273     assertEquals(TestOneof2.FooCase.FOO_NOT_SET, builder.getFooCase());
1274   }
1275 
testSetOneofClearsOthers()1276   public void testSetOneofClearsOthers() throws Exception {
1277     TestOneof2.Builder builder = TestOneof2.newBuilder();
1278     TestOneof2 message =
1279         builder.setFooInt(123).setFooString("foo").buildPartial();
1280     assertTrue(message.hasFooString());
1281     TestUtil.assertAtMostOneFieldSetOneof(message);
1282 
1283     message = builder.setFooCord("bar").buildPartial();
1284     assertTrue(message.hasFooCord());
1285     TestUtil.assertAtMostOneFieldSetOneof(message);
1286 
1287     message = builder.setFooStringPiece("baz").buildPartial();
1288     assertTrue(message.hasFooStringPiece());
1289     TestUtil.assertAtMostOneFieldSetOneof(message);
1290 
1291     message = builder.setFooBytes(TestUtil.toBytes("qux")).buildPartial();
1292     assertTrue(message.hasFooBytes());
1293     TestUtil.assertAtMostOneFieldSetOneof(message);
1294 
1295     message = builder.setFooEnum(TestOneof2.NestedEnum.FOO).buildPartial();
1296     assertTrue(message.hasFooEnum());
1297     TestUtil.assertAtMostOneFieldSetOneof(message);
1298 
1299     message = builder.setFooMessage(
1300         TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).buildPartial();
1301     assertTrue(message.hasFooMessage());
1302     TestUtil.assertAtMostOneFieldSetOneof(message);
1303 
1304     message = builder.setFooInt(123).buildPartial();
1305     assertTrue(message.hasFooInt());
1306     TestUtil.assertAtMostOneFieldSetOneof(message);
1307   }
1308 
testOneofTypes()1309   public void testOneofTypes() throws Exception {
1310     // Primitive
1311     {
1312       TestOneof2.Builder builder = TestOneof2.newBuilder();
1313       assertEquals(builder.getFooInt(), 0);
1314       assertFalse(builder.hasFooInt());
1315       assertTrue(builder.setFooInt(123).hasFooInt());
1316       assertEquals(builder.getFooInt(), 123);
1317       TestOneof2 message = builder.buildPartial();
1318       assertTrue(message.hasFooInt());
1319       assertEquals(message.getFooInt(), 123);
1320 
1321       assertFalse(builder.clearFooInt().hasFooInt());
1322       TestOneof2 message2 = builder.build();
1323       assertFalse(message2.hasFooInt());
1324       assertEquals(message2.getFooInt(), 0);
1325     }
1326 
1327     // Enum
1328     {
1329       TestOneof2.Builder builder = TestOneof2.newBuilder();
1330       assertEquals(builder.getFooEnum(), TestOneof2.NestedEnum.FOO);
1331       assertTrue(builder.setFooEnum(TestOneof2.NestedEnum.BAR).hasFooEnum());
1332       assertEquals(builder.getFooEnum(), TestOneof2.NestedEnum.BAR);
1333       TestOneof2 message = builder.buildPartial();
1334       assertTrue(message.hasFooEnum());
1335       assertEquals(message.getFooEnum(), TestOneof2.NestedEnum.BAR);
1336 
1337       assertFalse(builder.clearFooEnum().hasFooEnum());
1338       TestOneof2 message2 = builder.build();
1339       assertFalse(message2.hasFooEnum());
1340       assertEquals(message2.getFooEnum(), TestOneof2.NestedEnum.FOO);
1341     }
1342 
1343     // String
1344     {
1345       TestOneof2.Builder builder = TestOneof2.newBuilder();
1346       assertEquals(builder.getFooString(), "");
1347       builder.setFooString("foo");
1348       assertTrue(builder.hasFooString());
1349       assertEquals(builder.getFooString(), "foo");
1350       TestOneof2 message = builder.buildPartial();
1351       assertTrue(message.hasFooString());
1352       assertEquals(message.getFooString(), "foo");
1353       assertEquals(message.getFooStringBytes(), TestUtil.toBytes("foo"));
1354 
1355       assertFalse(builder.clearFooString().hasFooString());
1356       TestOneof2 message2 = builder.buildPartial();
1357       assertFalse(message2.hasFooString());
1358       assertEquals(message2.getFooString(), "");
1359       assertEquals(message2.getFooStringBytes(), TestUtil.toBytes(""));
1360 
1361       // Get method should not change the oneof value.
1362       builder.setFooInt(123);
1363       assertEquals(builder.getFooString(), "");
1364       assertEquals(builder.getFooStringBytes(), TestUtil.toBytes(""));
1365       assertEquals(123, builder.getFooInt());
1366 
1367       message = builder.build();
1368       assertEquals(message.getFooString(), "");
1369       assertEquals(message.getFooStringBytes(), TestUtil.toBytes(""));
1370       assertEquals(123, message.getFooInt());
1371     }
1372 
1373     // Cord
1374     {
1375       TestOneof2.Builder builder = TestOneof2.newBuilder();
1376       assertEquals(builder.getFooCord(), "");
1377       builder.setFooCord("foo");
1378       assertTrue(builder.hasFooCord());
1379       assertEquals(builder.getFooCord(), "foo");
1380       TestOneof2 message = builder.buildPartial();
1381       assertTrue(message.hasFooCord());
1382       assertEquals(message.getFooCord(), "foo");
1383       assertEquals(message.getFooCordBytes(), TestUtil.toBytes("foo"));
1384 
1385       assertFalse(builder.clearFooCord().hasFooCord());
1386       TestOneof2 message2 = builder.build();
1387       assertFalse(message2.hasFooCord());
1388       assertEquals(message2.getFooCord(), "");
1389       assertEquals(message2.getFooCordBytes(), TestUtil.toBytes(""));
1390     }
1391 
1392     // StringPiece
1393     {
1394       TestOneof2.Builder builder = TestOneof2.newBuilder();
1395       assertEquals(builder.getFooStringPiece(), "");
1396       builder.setFooStringPiece("foo");
1397       assertTrue(builder.hasFooStringPiece());
1398       assertEquals(builder.getFooStringPiece(), "foo");
1399       TestOneof2 message = builder.buildPartial();
1400       assertTrue(message.hasFooStringPiece());
1401       assertEquals(message.getFooStringPiece(), "foo");
1402       assertEquals(message.getFooStringPieceBytes(), TestUtil.toBytes("foo"));
1403 
1404       assertFalse(builder.clearFooStringPiece().hasFooStringPiece());
1405       TestOneof2 message2 = builder.build();
1406       assertFalse(message2.hasFooStringPiece());
1407       assertEquals(message2.getFooStringPiece(), "");
1408       assertEquals(message2.getFooStringPieceBytes(), TestUtil.toBytes(""));
1409     }
1410 
1411     // Message
1412     {
1413       // set
1414       TestOneof2.Builder builder = TestOneof2.newBuilder();
1415       assertEquals(builder.getFooMessage().getQuxInt(), 0);
1416       builder.setFooMessage(
1417           TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build());
1418       assertTrue(builder.hasFooMessage());
1419       assertEquals(builder.getFooMessage().getQuxInt(), 234);
1420       TestOneof2 message = builder.buildPartial();
1421       assertTrue(message.hasFooMessage());
1422       assertEquals(message.getFooMessage().getQuxInt(), 234);
1423 
1424       // clear
1425       assertFalse(builder.clearFooMessage().hasFooString());
1426       message = builder.build();
1427       assertFalse(message.hasFooMessage());
1428       assertEquals(message.getFooMessage().getQuxInt(), 0);
1429 
1430       // nested builder
1431       builder = TestOneof2.newBuilder();
1432       assertSame(builder.getFooMessageOrBuilder(),
1433           TestOneof2.NestedMessage.getDefaultInstance());
1434       assertFalse(builder.hasFooMessage());
1435       builder.getFooMessageBuilder().setQuxInt(123);
1436       assertTrue(builder.hasFooMessage());
1437       assertEquals(builder.getFooMessage().getQuxInt(), 123);
1438       message = builder.build();
1439       assertTrue(message.hasFooMessage());
1440       assertEquals(message.getFooMessage().getQuxInt(), 123);
1441     }
1442 
1443     // LazyMessage is tested in LazyMessageLiteTest.java
1444   }
1445 
testOneofMerge()1446   public void testOneofMerge() throws Exception {
1447     // Primitive Type
1448     {
1449       TestOneof2.Builder builder = TestOneof2.newBuilder();
1450       TestOneof2 message = builder.setFooInt(123).build();
1451       TestOneof2 message2 = TestOneof2.newBuilder().mergeFrom(message).build();
1452       assertTrue(message2.hasFooInt());
1453       assertEquals(message2.getFooInt(), 123);
1454     }
1455 
1456     // String
1457     {
1458       TestOneof2.Builder builder = TestOneof2.newBuilder();
1459       TestOneof2 message = builder.setFooString("foo").build();
1460       TestOneof2 message2 = TestOneof2.newBuilder().mergeFrom(message).build();
1461       assertTrue(message2.hasFooString());
1462       assertEquals(message2.getFooString(), "foo");
1463     }
1464 
1465     // Enum
1466     {
1467       TestOneof2.Builder builder = TestOneof2.newBuilder();
1468       TestOneof2 message = builder.setFooEnum(TestOneof2.NestedEnum.BAR).build();
1469       TestOneof2 message2 = TestOneof2.newBuilder().mergeFrom(message).build();
1470       assertTrue(message2.hasFooEnum());
1471       assertEquals(message2.getFooEnum(), TestOneof2.NestedEnum.BAR);
1472     }
1473 
1474     // Message
1475     {
1476       TestOneof2.Builder builder = TestOneof2.newBuilder();
1477       TestOneof2 message = builder.setFooMessage(
1478           TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).build();
1479       TestOneof2 message2 = TestOneof2.newBuilder().mergeFrom(message).build();
1480       assertTrue(message2.hasFooMessage());
1481       assertEquals(message2.getFooMessage().getQuxInt(), 234);
1482     }
1483   }
1484 
testOneofSerialization()1485   public void testOneofSerialization() throws Exception {
1486     // Primitive Type
1487     {
1488       TestOneof2.Builder builder = TestOneof2.newBuilder();
1489       TestOneof2 message = builder.setFooInt(123).build();
1490       ByteString serialized = message.toByteString();
1491       TestOneof2 message2 = TestOneof2.parseFrom(serialized);
1492       assertTrue(message2.hasFooInt());
1493       assertEquals(message2.getFooInt(), 123);
1494     }
1495 
1496     // String
1497     {
1498       TestOneof2.Builder builder = TestOneof2.newBuilder();
1499       TestOneof2 message = builder.setFooString("foo").build();
1500       ByteString serialized = message.toByteString();
1501       TestOneof2 message2 = TestOneof2.parseFrom(serialized);
1502       assertTrue(message2.hasFooString());
1503       assertEquals(message2.getFooString(), "foo");
1504     }
1505 
1506     // Enum
1507     {
1508       TestOneof2.Builder builder = TestOneof2.newBuilder();
1509       TestOneof2 message = builder.setFooEnum(TestOneof2.NestedEnum.BAR).build();
1510       ByteString serialized = message.toByteString();
1511       TestOneof2 message2 = TestOneof2.parseFrom(serialized);
1512       assertTrue(message2.hasFooEnum());
1513       assertEquals(message2.getFooEnum(), TestOneof2.NestedEnum.BAR);
1514     }
1515 
1516     // Message
1517     {
1518       TestOneof2.Builder builder = TestOneof2.newBuilder();
1519       TestOneof2 message = builder.setFooMessage(
1520           TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).build();
1521       ByteString serialized = message.toByteString();
1522       TestOneof2 message2 = TestOneof2.parseFrom(serialized);
1523       assertTrue(message2.hasFooMessage());
1524       assertEquals(message2.getFooMessage().getQuxInt(), 234);
1525     }
1526   }
1527 
testOneofNestedBuilderOnChangePropagation()1528   public void testOneofNestedBuilderOnChangePropagation() {
1529     NestedTestAllTypes.Builder parentBuilder = NestedTestAllTypes.newBuilder();
1530     TestAllTypes.Builder builder = parentBuilder.getPayloadBuilder();
1531     builder.getOneofNestedMessageBuilder();
1532     assertTrue(builder.hasOneofNestedMessage());
1533     assertTrue(parentBuilder.hasPayload());
1534     NestedTestAllTypes message = parentBuilder.build();
1535     assertTrue(message.hasPayload());
1536     assertTrue(message.getPayload().hasOneofNestedMessage());
1537   }
1538 
testGetRepeatedFieldBuilder()1539   public void testGetRepeatedFieldBuilder() {
1540     Descriptor descriptor = TestAllTypes.getDescriptor();
1541 
1542     FieldDescriptor fieldDescriptor =
1543         descriptor.findFieldByName("repeated_nested_message");
1544     FieldDescriptor foreignFieldDescriptor =
1545         descriptor.findFieldByName("repeated_foreign_message");
1546     FieldDescriptor importFieldDescriptor =
1547         descriptor.findFieldByName("repeated_import_message");
1548 
1549     // Mutate the message with new field builder
1550     // Mutate nested message
1551     TestAllTypes.Builder builder1 = TestAllTypes.newBuilder();
1552     Message.Builder fieldBuilder1 = builder1.newBuilderForField(
1553         fieldDescriptor);
1554     FieldDescriptor subFieldDescriptor1 =
1555         fieldBuilder1.getDescriptorForType().findFieldByName("bb");
1556     fieldBuilder1.setField(subFieldDescriptor1, 1);
1557     builder1.addRepeatedField(fieldDescriptor, fieldBuilder1.build());
1558 
1559     // Mutate foreign message
1560     Message.Builder foreignFieldBuilder1 = builder1.newBuilderForField(
1561         foreignFieldDescriptor);
1562     FieldDescriptor subForeignFieldDescriptor1 =
1563         foreignFieldBuilder1.getDescriptorForType().findFieldByName("c");
1564     foreignFieldBuilder1.setField(subForeignFieldDescriptor1, 2);
1565     builder1.addRepeatedField(foreignFieldDescriptor,
1566         foreignFieldBuilder1.build());
1567 
1568     // Mutate import message
1569     Message.Builder importFieldBuilder1 = builder1.newBuilderForField(
1570         importFieldDescriptor);
1571     FieldDescriptor subImportFieldDescriptor1 =
1572         importFieldBuilder1.getDescriptorForType().findFieldByName("d");
1573     importFieldBuilder1.setField(subImportFieldDescriptor1, 3);
1574     builder1.addRepeatedField(importFieldDescriptor,
1575         importFieldBuilder1.build());
1576 
1577     Message newMessage1 = builder1.build();
1578 
1579     // Mutate the message with existing field builder
1580     // Mutate nested message
1581     TestAllTypes.Builder builder2 = TestAllTypes.newBuilder();
1582     builder2.addRepeatedNestedMessageBuilder();
1583     Message.Builder fieldBuilder2 = builder2.getRepeatedFieldBuilder(
1584         fieldDescriptor, 0);
1585     FieldDescriptor subFieldDescriptor2 =
1586         fieldBuilder2.getDescriptorForType().findFieldByName("bb");
1587     fieldBuilder2.setField(subFieldDescriptor2, 1);
1588 
1589     // Mutate foreign message
1590     Message.Builder foreignFieldBuilder2 = builder2.newBuilderForField(
1591         foreignFieldDescriptor);
1592     FieldDescriptor subForeignFieldDescriptor2 =
1593         foreignFieldBuilder2.getDescriptorForType().findFieldByName("c");
1594     foreignFieldBuilder2.setField(subForeignFieldDescriptor2, 2);
1595     builder2.addRepeatedField(foreignFieldDescriptor,
1596         foreignFieldBuilder2.build());
1597 
1598     // Mutate import message
1599     Message.Builder importFieldBuilder2 = builder2.newBuilderForField(
1600         importFieldDescriptor);
1601     FieldDescriptor subImportFieldDescriptor2 =
1602         importFieldBuilder2.getDescriptorForType().findFieldByName("d");
1603     importFieldBuilder2.setField(subImportFieldDescriptor2, 3);
1604     builder2.addRepeatedField(importFieldDescriptor,
1605         importFieldBuilder2.build());
1606 
1607     Message newMessage2 = builder2.build();
1608 
1609     // These two messages should be equal.
1610     assertEquals(newMessage1, newMessage2);
1611   }
1612 
testGetRepeatedFieldBuilderWithInitializedValue()1613   public void testGetRepeatedFieldBuilderWithInitializedValue() {
1614     Descriptor descriptor = TestAllTypes.getDescriptor();
1615     FieldDescriptor fieldDescriptor =
1616         descriptor.findFieldByName("repeated_nested_message");
1617 
1618     // Before setting field, builder is initialized by default value.
1619     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
1620     builder.addRepeatedNestedMessageBuilder();
1621     NestedMessage.Builder fieldBuilder =
1622         (NestedMessage.Builder) builder.getRepeatedFieldBuilder(fieldDescriptor, 0);
1623     assertEquals(0, fieldBuilder.getBb());
1624 
1625     // Setting field value with new field builder instance.
1626     builder = TestAllTypes.newBuilder();
1627     NestedMessage.Builder newFieldBuilder =
1628         builder.addRepeatedNestedMessageBuilder();
1629     newFieldBuilder.setBb(2);
1630     // Then get the field builder instance by getRepeatedFieldBuilder().
1631     fieldBuilder =
1632         (NestedMessage.Builder) builder.getRepeatedFieldBuilder(fieldDescriptor, 0);
1633     // It should contain new value.
1634     assertEquals(2, fieldBuilder.getBb());
1635     // These two builder should be equal.
1636     assertSame(fieldBuilder, newFieldBuilder);
1637   }
1638 
testGetRepeatedFieldBuilderNotSupportedException()1639   public void testGetRepeatedFieldBuilderNotSupportedException() {
1640     Descriptor descriptor = TestAllTypes.getDescriptor();
1641     TestAllTypes.Builder builder = TestAllTypes.newBuilder();
1642     try {
1643       builder.getRepeatedFieldBuilder(descriptor.findFieldByName("repeated_int32"), 0);
1644       fail("Exception was not thrown");
1645     } catch (UnsupportedOperationException e) {
1646       // We expect this exception.
1647     }
1648     try {
1649       builder.getRepeatedFieldBuilder(
1650           descriptor.findFieldByName("repeated_nested_enum"), 0);
1651       fail("Exception was not thrown");
1652     } catch (UnsupportedOperationException e) {
1653       // We expect this exception.
1654     }
1655     try {
1656       builder.getRepeatedFieldBuilder(descriptor.findFieldByName("optional_int32"), 0);
1657       fail("Exception was not thrown");
1658     } catch (UnsupportedOperationException e) {
1659       // We expect this exception.
1660     }
1661     try {
1662       builder.getRepeatedFieldBuilder(
1663           descriptor.findFieldByName("optional_nested_enum"), 0);
1664       fail("Exception was not thrown");
1665     } catch (UnsupportedOperationException e) {
1666       // We expect this exception.
1667     }
1668     try {
1669       builder.getRepeatedFieldBuilder(
1670           descriptor.findFieldByName("optional_nested_message"), 0);
1671       fail("Exception was not thrown");
1672     } catch (UnsupportedOperationException e) {
1673       // We expect this exception.
1674     }
1675   }
1676 }
1677