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