예제 #1
0
        public void TestRecoverMissingExtensions()
        {
            const int optionalInt32 = 12345678;

            TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
            builder.SetExtension(Unittest.OptionalInt32Extension, optionalInt32);
            builder.AddExtension(Unittest.RepeatedDoubleExtension, 1.1);
            builder.AddExtension(Unittest.RepeatedDoubleExtension, 1.2);
            builder.AddExtension(Unittest.RepeatedDoubleExtension, 1.3);
            TestAllExtensions msg = builder.Build();

            Assert.IsTrue(msg.HasExtension(Unittest.OptionalInt32Extension));
            Assert.AreEqual(3, msg.GetExtensionCount(Unittest.RepeatedDoubleExtension));

            byte[]            bits = msg.ToByteArray();
            TestAllExtensions copy = TestAllExtensions.ParseFrom(bits);

            Assert.IsFalse(copy.HasExtension(Unittest.OptionalInt32Extension));
            Assert.AreEqual(0, copy.GetExtensionCount(Unittest.RepeatedDoubleExtension));
            Assert.AreNotEqual(msg, copy);

            //Even though copy does not understand the typees they serialize correctly
            byte[] copybits = copy.ToByteArray();
            Assert.AreEqual(bits, copybits);

            ExtensionRegistry registry = ExtensionRegistry.CreateInstance();

            Unittest.RegisterAllExtensions(registry);

            //Now we can take those copy bits and restore the full message with extensions
            copy = TestAllExtensions.ParseFrom(copybits, registry);
            Assert.IsTrue(copy.HasExtension(Unittest.OptionalInt32Extension));
            Assert.AreEqual(3, copy.GetExtensionCount(Unittest.RepeatedDoubleExtension));

            Assert.AreEqual(msg, copy);
            Assert.AreEqual(bits, copy.ToByteArray());

            //If we modify the object this should all continue to work as before
            copybits = copy.ToBuilder().Build().ToByteArray();
            Assert.AreEqual(bits, copybits);

            //If we replace extension the object this should all continue to work as before
            copybits = copy.ToBuilder()
                       .SetExtension(Unittest.OptionalInt32Extension, optionalInt32)
                       .Build().ToByteArray();
            Assert.AreEqual(bits, copybits);
        }