diff options
Diffstat (limited to 'src/ProtocolBuffers.Test')
24 files changed, 8134 insertions, 7453 deletions
diff --git a/src/ProtocolBuffers.Test/AbstractMessageTest.cs b/src/ProtocolBuffers.Test/AbstractMessageTest.cs index 3f7b8648..e300ac94 100644 --- a/src/ProtocolBuffers.Test/AbstractMessageTest.cs +++ b/src/ProtocolBuffers.Test/AbstractMessageTest.cs @@ -1,419 +1,476 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Collections.Generic; -using Google.ProtocolBuffers.Descriptors; -using NUnit.Framework; -using Google.ProtocolBuffers.TestProtos; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class AbstractMessageTest { - - [Test] - public void Clear() { - AbstractMessageWrapper message = new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder(TestUtil.GetAllSet())).Clear().Build(); - TestUtil.AssertClear((TestAllTypes) message.WrappedMessage); - } - - [Test] - public void Copy() { - AbstractMessageWrapper message = new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder()).MergeFrom(TestUtil.GetAllSet()).Build(); - TestUtil.AssertAllFieldsSet((TestAllTypes) message.WrappedMessage); - } - - [Test] - public void SerializedSize() { - TestAllTypes message = TestUtil.GetAllSet(); - IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetAllSet()); - - Assert.AreEqual(message.SerializedSize, abstractMessage.SerializedSize); - } - - [Test] - public void Serialization() { - IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetAllSet()); - TestUtil.AssertAllFieldsSet(TestAllTypes.ParseFrom(abstractMessage.ToByteString())); - Assert.AreEqual(TestUtil.GetAllSet().ToByteString(), abstractMessage.ToByteString()); - } - - [Test] - public void Parsing() { - IBuilder builder = new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder()); - AbstractMessageWrapper message = (AbstractMessageWrapper) builder.WeakMergeFrom(TestUtil.GetAllSet().ToByteString()).WeakBuild(); - TestUtil.AssertAllFieldsSet((TestAllTypes) message.WrappedMessage); - } - - [Test] - public void PackedSerialization() { - IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetPackedSet()); - TestUtil.AssertPackedFieldsSet(TestPackedTypes.ParseFrom(abstractMessage.ToByteString())); - Assert.AreEqual(TestUtil.GetPackedSet().ToByteString(), abstractMessage.ToByteString()); - } - - [Test] - public void PackedParsing() { - AbstractMessageWrapper.Builder builder = new AbstractMessageWrapper.Builder(TestPackedTypes.CreateBuilder()); - AbstractMessageWrapper message = builder.MergeFrom(TestUtil.GetPackedSet().ToByteString()).Build(); - TestUtil.AssertPackedFieldsSet((TestPackedTypes)message.WrappedMessage); - } - - [Test] - public void OptimizedForSize() { - // We're mostly only Checking that this class was compiled successfully. - TestOptimizedForSize message = TestOptimizedForSize.CreateBuilder().SetI(1).Build(); - message = TestOptimizedForSize.ParseFrom(message.ToByteString()); - Assert.AreEqual(2, message.SerializedSize); - } - - // ----------------------------------------------------------------- - // Tests for isInitialized(). - - private static readonly TestRequired TestRequiredUninitialized = TestRequired.DefaultInstance; - private static readonly TestRequired TestRequiredInitialized = TestRequired.CreateBuilder().SetA(1).SetB(2).SetC(3).Build(); - - [Test] - public void IsInitialized() { - TestRequired.Builder builder = TestRequired.CreateBuilder(); - AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder); - - Assert.IsFalse(abstractBuilder.IsInitialized); - builder.A = 1; - Assert.IsFalse(abstractBuilder.IsInitialized); - builder.B = 1; - Assert.IsFalse(abstractBuilder.IsInitialized); - builder.C = 1; - Assert.IsTrue(abstractBuilder.IsInitialized); - } - - [Test] - public void ForeignIsInitialized() { - TestRequiredForeign.Builder builder = TestRequiredForeign.CreateBuilder(); - AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder); - - Assert.IsTrue(abstractBuilder.IsInitialized); - - builder.SetOptionalMessage(TestRequiredUninitialized); - Assert.IsFalse(abstractBuilder.IsInitialized); - - builder.SetOptionalMessage(TestRequiredInitialized); - Assert.IsTrue(abstractBuilder.IsInitialized); - - builder.AddRepeatedMessage(TestRequiredUninitialized); - Assert.IsFalse(abstractBuilder.IsInitialized); - - builder.SetRepeatedMessage(0, TestRequiredInitialized); - Assert.IsTrue(abstractBuilder.IsInitialized); - } - - // ----------------------------------------------------------------- - // Tests for mergeFrom - - static readonly TestAllTypes MergeSource = TestAllTypes.CreateBuilder() - .SetOptionalInt32(1) - .SetOptionalString("foo") - .SetOptionalForeignMessage(ForeignMessage.DefaultInstance) - .AddRepeatedString("bar") - .Build(); - - static readonly TestAllTypes MergeDest = TestAllTypes.CreateBuilder() - .SetOptionalInt64(2) - .SetOptionalString("baz") - .SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(3).Build()) - .AddRepeatedString("qux") - .Build(); - - const string MergeResultText = "optional_int32: 1\n" + - "optional_int64: 2\n" + - "optional_string: \"foo\"\n" + - "optional_foreign_message {\n" + - " c: 3\n" + - "}\n" + - "repeated_string: \"qux\"\n" + - "repeated_string: \"bar\"\n"; - - [Test] - public void MergeFrom() { - AbstractMessageWrapper result = (AbstractMessageWrapper) - new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder(MergeDest)) - .MergeFrom(MergeSource) - .Build(); - - Assert.AreEqual(MergeResultText, result.ToString()); - } - - // ----------------------------------------------------------------- - // Tests for equals and hashCode - - [Test] - public void EqualsAndHashCode() { - TestAllTypes a = TestUtil.GetAllSet(); - TestAllTypes b = TestAllTypes.CreateBuilder().Build(); - TestAllTypes c = TestAllTypes.CreateBuilder(b).AddRepeatedString("x").Build(); - TestAllTypes d = TestAllTypes.CreateBuilder(c).AddRepeatedString("y").Build(); - TestAllExtensions e = TestUtil.GetAllExtensionsSet(); - TestAllExtensions f = TestAllExtensions.CreateBuilder(e) - .AddExtension(UnitTestProtoFile.RepeatedInt32Extension, 999).Build(); - - CheckEqualsIsConsistent(a); - CheckEqualsIsConsistent(b); - CheckEqualsIsConsistent(c); - CheckEqualsIsConsistent(d); - CheckEqualsIsConsistent(e); - CheckEqualsIsConsistent(f); - - CheckNotEqual(a, b); - CheckNotEqual(a, c); - CheckNotEqual(a, d); - CheckNotEqual(a, e); - CheckNotEqual(a, f); - - CheckNotEqual(b, c); - CheckNotEqual(b, d); - CheckNotEqual(b, e); - CheckNotEqual(b, f); - - CheckNotEqual(c, d); - CheckNotEqual(c, e); - CheckNotEqual(c, f); - - CheckNotEqual(d, e); - CheckNotEqual(d, f); - - CheckNotEqual(e, f); - - // Deserializing into the TestEmptyMessage such that every field is an UnknownFieldSet.Field - TestEmptyMessage eUnknownFields = TestEmptyMessage.ParseFrom(e.ToByteArray()); - TestEmptyMessage fUnknownFields = TestEmptyMessage.ParseFrom(f.ToByteArray()); - CheckNotEqual(eUnknownFields, fUnknownFields); - CheckEqualsIsConsistent(eUnknownFields); - CheckEqualsIsConsistent(fUnknownFields); - - // Subseqent reconstitutions should be identical - TestEmptyMessage eUnknownFields2 = TestEmptyMessage.ParseFrom(e.ToByteArray()); - CheckEqualsIsConsistent(eUnknownFields, eUnknownFields2); - } - - /// <summary> - /// Asserts that the given protos are equal and have the same hash code. - /// </summary> - private static void CheckEqualsIsConsistent(IMessage message) { - // Object should be equal to itself. - Assert.AreEqual(message, message); - - // Object should be equal to a dynamic copy of itself. - DynamicMessage dynamic = DynamicMessage.CreateBuilder(message).Build(); - CheckEqualsIsConsistent(message, dynamic); - } - - /// <summary> - /// Asserts that the given protos are equal and have the same hash code. - /// </summary> - private static void CheckEqualsIsConsistent(IMessage message1, IMessage message2) { - Assert.AreEqual(message1, message2); - Assert.AreEqual(message2, message1); - Assert.AreEqual(message2.GetHashCode(), message1.GetHashCode()); - } - - /// <summary> - /// Asserts that the given protos are not equal and have different hash codes. - /// </summary> - /// <remarks> - /// It's valid for non-equal objects to have the same hash code, so - /// this test is stricter than it needs to be. However, this should happen - /// relatively rarely. (If this test fails, it's probably still due to a bug.) - /// </remarks> - private static void CheckNotEqual(IMessage m1, IMessage m2) { - String equalsError = string.Format("{0} should not be equal to {1}", m1, m2); - Assert.IsFalse(m1.Equals(m2), equalsError); - Assert.IsFalse(m2.Equals(m1), equalsError); - - Assert.IsFalse(m1.GetHashCode() == m2.GetHashCode(), - string.Format("{0} should have a different hash code from {1}", m1, m2)); - } - - /// <summary> - /// Extends AbstractMessage and wraps some other message object. The methods - /// of the Message interface which aren't explicitly implemented by - /// AbstractMessage are forwarded to the wrapped object. This allows us to - /// test that AbstractMessage's implementations work even if the wrapped - /// object does not use them. - /// </summary> - private class AbstractMessageWrapper : AbstractMessage<AbstractMessageWrapper, AbstractMessageWrapper.Builder> { - private readonly IMessage wrappedMessage; - - public IMessage WrappedMessage { - get { return wrappedMessage; } - } - - public AbstractMessageWrapper(IMessage wrappedMessage) { - this.wrappedMessage = wrappedMessage; - } - - public override MessageDescriptor DescriptorForType { - get { return wrappedMessage.DescriptorForType; } - } - - public override AbstractMessageWrapper DefaultInstanceForType { - get { return new AbstractMessageWrapper(wrappedMessage.WeakDefaultInstanceForType); } - } - - public override IDictionary<FieldDescriptor, object> AllFields { - get { return wrappedMessage.AllFields; } - } - - public override bool HasField(FieldDescriptor field) { - return wrappedMessage.HasField(field); - } - - public override object this[FieldDescriptor field] { - get { return wrappedMessage[field]; } - } - - public override object this[FieldDescriptor field, int index] { - get { return wrappedMessage[field, index]; } - } - - public override int GetRepeatedFieldCount(FieldDescriptor field) { - return wrappedMessage.GetRepeatedFieldCount(field); - } - - public override UnknownFieldSet UnknownFields { - get { return wrappedMessage.UnknownFields; } - } - - public override Builder CreateBuilderForType() { - return new Builder(wrappedMessage.WeakCreateBuilderForType()); - } - - public override Builder ToBuilder() { - return new Builder(wrappedMessage.WeakToBuilder()); - } - - internal class Builder : AbstractBuilder<AbstractMessageWrapper, Builder> { - private readonly IBuilder wrappedBuilder; - - protected override Builder ThisBuilder { - get { return this; } - } - - internal Builder(IBuilder wrappedBuilder) { - this.wrappedBuilder = wrappedBuilder; - } - - public override Builder MergeFrom(AbstractMessageWrapper other) { - wrappedBuilder.WeakMergeFrom(other.wrappedMessage); - return this; - } - - public override bool IsInitialized { - get { return wrappedBuilder.IsInitialized; } - } - - public override IDictionary<FieldDescriptor, object> AllFields { - get { return wrappedBuilder.AllFields; } - } - - public override object this[FieldDescriptor field] { - get { return wrappedBuilder[field]; } - set { wrappedBuilder[field] = value; } - } - - public override MessageDescriptor DescriptorForType { - get { return wrappedBuilder.DescriptorForType; } - } - - public override int GetRepeatedFieldCount(FieldDescriptor field) { - return wrappedBuilder.GetRepeatedFieldCount(field); - } - - public override object this[FieldDescriptor field, int index] { - get { return wrappedBuilder[field, index]; } - set { wrappedBuilder[field, index] = value; } - } - - public override bool HasField(FieldDescriptor field) { - return wrappedBuilder.HasField(field); - } - - public override UnknownFieldSet UnknownFields { - get { return wrappedBuilder.UnknownFields; } - set { wrappedBuilder.UnknownFields = value; } - } - - public override AbstractMessageWrapper Build() { - return new AbstractMessageWrapper(wrappedBuilder.WeakBuild()); - } - - public override AbstractMessageWrapper BuildPartial() { - return new AbstractMessageWrapper(wrappedBuilder.WeakBuildPartial()); - } - - public override Builder Clone() { - return new Builder(wrappedBuilder.WeakClone()); - } - - public override AbstractMessageWrapper DefaultInstanceForType { - get { return new AbstractMessageWrapper(wrappedBuilder.WeakDefaultInstanceForType); } - } - - public override Builder ClearField(FieldDescriptor field) { - wrappedBuilder.WeakClearField(field); - return this; - } - - public override Builder AddRepeatedField(FieldDescriptor field, object value) { - wrappedBuilder.WeakAddRepeatedField(field, value); - return this; - } - - public override IBuilder CreateBuilderForField(FieldDescriptor field) { - wrappedBuilder.CreateBuilderForField(field); - return this; - } - - public override Builder MergeFrom(IMessage other) { - wrappedBuilder.WeakMergeFrom(other); - return this; - } - - public override Builder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry) { - wrappedBuilder.WeakMergeFrom(input, extensionRegistry); - return this; - } - } - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System;
+using System.Collections.Generic;
+using Google.ProtocolBuffers.Descriptors;
+using NUnit.Framework;
+using Google.ProtocolBuffers.TestProtos;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class AbstractMessageTest
+ {
+ [Test]
+ public void Clear()
+ {
+ AbstractMessageWrapper message =
+ new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder(TestUtil.GetAllSet())).Clear().Build();
+ TestUtil.AssertClear((TestAllTypes) message.WrappedMessage);
+ }
+
+ [Test]
+ public void Copy()
+ {
+ AbstractMessageWrapper message =
+ new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder()).MergeFrom(TestUtil.GetAllSet()).Build();
+ TestUtil.AssertAllFieldsSet((TestAllTypes) message.WrappedMessage);
+ }
+
+ [Test]
+ public void SerializedSize()
+ {
+ TestAllTypes message = TestUtil.GetAllSet();
+ IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetAllSet());
+
+ Assert.AreEqual(message.SerializedSize, abstractMessage.SerializedSize);
+ }
+
+ [Test]
+ public void Serialization()
+ {
+ IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetAllSet());
+ TestUtil.AssertAllFieldsSet(TestAllTypes.ParseFrom(abstractMessage.ToByteString()));
+ Assert.AreEqual(TestUtil.GetAllSet().ToByteString(), abstractMessage.ToByteString());
+ }
+
+ [Test]
+ public void Parsing()
+ {
+ IBuilder builder = new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder());
+ AbstractMessageWrapper message =
+ (AbstractMessageWrapper) builder.WeakMergeFrom(TestUtil.GetAllSet().ToByteString()).WeakBuild();
+ TestUtil.AssertAllFieldsSet((TestAllTypes) message.WrappedMessage);
+ }
+
+ [Test]
+ public void PackedSerialization()
+ {
+ IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetPackedSet());
+ TestUtil.AssertPackedFieldsSet(TestPackedTypes.ParseFrom(abstractMessage.ToByteString()));
+ Assert.AreEqual(TestUtil.GetPackedSet().ToByteString(), abstractMessage.ToByteString());
+ }
+
+ [Test]
+ public void PackedParsing()
+ {
+ AbstractMessageWrapper.Builder builder = new AbstractMessageWrapper.Builder(TestPackedTypes.CreateBuilder());
+ AbstractMessageWrapper message = builder.MergeFrom(TestUtil.GetPackedSet().ToByteString()).Build();
+ TestUtil.AssertPackedFieldsSet((TestPackedTypes) message.WrappedMessage);
+ }
+
+ [Test]
+ public void OptimizedForSize()
+ {
+ // We're mostly only Checking that this class was compiled successfully.
+ TestOptimizedForSize message = TestOptimizedForSize.CreateBuilder().SetI(1).Build();
+ message = TestOptimizedForSize.ParseFrom(message.ToByteString());
+ Assert.AreEqual(2, message.SerializedSize);
+ }
+
+ // -----------------------------------------------------------------
+ // Tests for isInitialized().
+
+ private static readonly TestRequired TestRequiredUninitialized = TestRequired.DefaultInstance;
+
+ private static readonly TestRequired TestRequiredInitialized =
+ TestRequired.CreateBuilder().SetA(1).SetB(2).SetC(3).Build();
+
+ [Test]
+ public void IsInitialized()
+ {
+ TestRequired.Builder builder = TestRequired.CreateBuilder();
+ AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder);
+
+ Assert.IsFalse(abstractBuilder.IsInitialized);
+ builder.A = 1;
+ Assert.IsFalse(abstractBuilder.IsInitialized);
+ builder.B = 1;
+ Assert.IsFalse(abstractBuilder.IsInitialized);
+ builder.C = 1;
+ Assert.IsTrue(abstractBuilder.IsInitialized);
+ }
+
+ [Test]
+ public void ForeignIsInitialized()
+ {
+ TestRequiredForeign.Builder builder = TestRequiredForeign.CreateBuilder();
+ AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder);
+
+ Assert.IsTrue(abstractBuilder.IsInitialized);
+
+ builder.SetOptionalMessage(TestRequiredUninitialized);
+ Assert.IsFalse(abstractBuilder.IsInitialized);
+
+ builder.SetOptionalMessage(TestRequiredInitialized);
+ Assert.IsTrue(abstractBuilder.IsInitialized);
+
+ builder.AddRepeatedMessage(TestRequiredUninitialized);
+ Assert.IsFalse(abstractBuilder.IsInitialized);
+
+ builder.SetRepeatedMessage(0, TestRequiredInitialized);
+ Assert.IsTrue(abstractBuilder.IsInitialized);
+ }
+
+ // -----------------------------------------------------------------
+ // Tests for mergeFrom
+
+ private static readonly TestAllTypes MergeSource = TestAllTypes.CreateBuilder()
+ .SetOptionalInt32(1)
+ .SetOptionalString("foo")
+ .SetOptionalForeignMessage(ForeignMessage.DefaultInstance)
+ .AddRepeatedString("bar")
+ .Build();
+
+ private static readonly TestAllTypes MergeDest = TestAllTypes.CreateBuilder()
+ .SetOptionalInt64(2)
+ .SetOptionalString("baz")
+ .SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(3).Build())
+ .AddRepeatedString("qux")
+ .Build();
+
+ private const string MergeResultText = "optional_int32: 1\n" +
+ "optional_int64: 2\n" +
+ "optional_string: \"foo\"\n" +
+ "optional_foreign_message {\n" +
+ " c: 3\n" +
+ "}\n" +
+ "repeated_string: \"qux\"\n" +
+ "repeated_string: \"bar\"\n";
+
+ [Test]
+ public void MergeFrom()
+ {
+ AbstractMessageWrapper result = (AbstractMessageWrapper)
+ new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder(MergeDest))
+ .MergeFrom(MergeSource)
+ .Build();
+
+ Assert.AreEqual(MergeResultText, result.ToString());
+ }
+
+ // -----------------------------------------------------------------
+ // Tests for equals and hashCode
+
+ [Test]
+ public void EqualsAndHashCode()
+ {
+ TestAllTypes a = TestUtil.GetAllSet();
+ TestAllTypes b = TestAllTypes.CreateBuilder().Build();
+ TestAllTypes c = TestAllTypes.CreateBuilder(b).AddRepeatedString("x").Build();
+ TestAllTypes d = TestAllTypes.CreateBuilder(c).AddRepeatedString("y").Build();
+ TestAllExtensions e = TestUtil.GetAllExtensionsSet();
+ TestAllExtensions f = TestAllExtensions.CreateBuilder(e)
+ .AddExtension(UnitTestProtoFile.RepeatedInt32Extension, 999).Build();
+
+ CheckEqualsIsConsistent(a);
+ CheckEqualsIsConsistent(b);
+ CheckEqualsIsConsistent(c);
+ CheckEqualsIsConsistent(d);
+ CheckEqualsIsConsistent(e);
+ CheckEqualsIsConsistent(f);
+
+ CheckNotEqual(a, b);
+ CheckNotEqual(a, c);
+ CheckNotEqual(a, d);
+ CheckNotEqual(a, e);
+ CheckNotEqual(a, f);
+
+ CheckNotEqual(b, c);
+ CheckNotEqual(b, d);
+ CheckNotEqual(b, e);
+ CheckNotEqual(b, f);
+
+ CheckNotEqual(c, d);
+ CheckNotEqual(c, e);
+ CheckNotEqual(c, f);
+
+ CheckNotEqual(d, e);
+ CheckNotEqual(d, f);
+
+ CheckNotEqual(e, f);
+
+ // Deserializing into the TestEmptyMessage such that every field is an UnknownFieldSet.Field
+ TestEmptyMessage eUnknownFields = TestEmptyMessage.ParseFrom(e.ToByteArray());
+ TestEmptyMessage fUnknownFields = TestEmptyMessage.ParseFrom(f.ToByteArray());
+ CheckNotEqual(eUnknownFields, fUnknownFields);
+ CheckEqualsIsConsistent(eUnknownFields);
+ CheckEqualsIsConsistent(fUnknownFields);
+
+ // Subseqent reconstitutions should be identical
+ TestEmptyMessage eUnknownFields2 = TestEmptyMessage.ParseFrom(e.ToByteArray());
+ CheckEqualsIsConsistent(eUnknownFields, eUnknownFields2);
+ }
+
+ /// <summary>
+ /// Asserts that the given protos are equal and have the same hash code.
+ /// </summary>
+ private static void CheckEqualsIsConsistent(IMessage message)
+ {
+ // Object should be equal to itself.
+ Assert.AreEqual(message, message);
+
+ // Object should be equal to a dynamic copy of itself.
+ DynamicMessage dynamic = DynamicMessage.CreateBuilder(message).Build();
+ CheckEqualsIsConsistent(message, dynamic);
+ }
+
+ /// <summary>
+ /// Asserts that the given protos are equal and have the same hash code.
+ /// </summary>
+ private static void CheckEqualsIsConsistent(IMessage message1, IMessage message2)
+ {
+ Assert.AreEqual(message1, message2);
+ Assert.AreEqual(message2, message1);
+ Assert.AreEqual(message2.GetHashCode(), message1.GetHashCode());
+ }
+
+ /// <summary>
+ /// Asserts that the given protos are not equal and have different hash codes.
+ /// </summary>
+ /// <remarks>
+ /// It's valid for non-equal objects to have the same hash code, so
+ /// this test is stricter than it needs to be. However, this should happen
+ /// relatively rarely. (If this test fails, it's probably still due to a bug.)
+ /// </remarks>
+ private static void CheckNotEqual(IMessage m1, IMessage m2)
+ {
+ String equalsError = string.Format("{0} should not be equal to {1}", m1, m2);
+ Assert.IsFalse(m1.Equals(m2), equalsError);
+ Assert.IsFalse(m2.Equals(m1), equalsError);
+
+ Assert.IsFalse(m1.GetHashCode() == m2.GetHashCode(),
+ string.Format("{0} should have a different hash code from {1}", m1, m2));
+ }
+
+ /// <summary>
+ /// Extends AbstractMessage and wraps some other message object. The methods
+ /// of the Message interface which aren't explicitly implemented by
+ /// AbstractMessage are forwarded to the wrapped object. This allows us to
+ /// test that AbstractMessage's implementations work even if the wrapped
+ /// object does not use them.
+ /// </summary>
+ private class AbstractMessageWrapper : AbstractMessage<AbstractMessageWrapper, AbstractMessageWrapper.Builder>
+ {
+ private readonly IMessage wrappedMessage;
+
+ public IMessage WrappedMessage
+ {
+ get { return wrappedMessage; }
+ }
+
+ public AbstractMessageWrapper(IMessage wrappedMessage)
+ {
+ this.wrappedMessage = wrappedMessage;
+ }
+
+ public override MessageDescriptor DescriptorForType
+ {
+ get { return wrappedMessage.DescriptorForType; }
+ }
+
+ public override AbstractMessageWrapper DefaultInstanceForType
+ {
+ get { return new AbstractMessageWrapper(wrappedMessage.WeakDefaultInstanceForType); }
+ }
+
+ public override IDictionary<FieldDescriptor, object> AllFields
+ {
+ get { return wrappedMessage.AllFields; }
+ }
+
+ public override bool HasField(FieldDescriptor field)
+ {
+ return wrappedMessage.HasField(field);
+ }
+
+ public override object this[FieldDescriptor field]
+ {
+ get { return wrappedMessage[field]; }
+ }
+
+ public override object this[FieldDescriptor field, int index]
+ {
+ get { return wrappedMessage[field, index]; }
+ }
+
+ public override int GetRepeatedFieldCount(FieldDescriptor field)
+ {
+ return wrappedMessage.GetRepeatedFieldCount(field);
+ }
+
+ public override UnknownFieldSet UnknownFields
+ {
+ get { return wrappedMessage.UnknownFields; }
+ }
+
+ public override Builder CreateBuilderForType()
+ {
+ return new Builder(wrappedMessage.WeakCreateBuilderForType());
+ }
+
+ public override Builder ToBuilder()
+ {
+ return new Builder(wrappedMessage.WeakToBuilder());
+ }
+
+ internal class Builder : AbstractBuilder<AbstractMessageWrapper, Builder>
+ {
+ private readonly IBuilder wrappedBuilder;
+
+ protected override Builder ThisBuilder
+ {
+ get { return this; }
+ }
+
+ internal Builder(IBuilder wrappedBuilder)
+ {
+ this.wrappedBuilder = wrappedBuilder;
+ }
+
+ public override Builder MergeFrom(AbstractMessageWrapper other)
+ {
+ wrappedBuilder.WeakMergeFrom(other.wrappedMessage);
+ return this;
+ }
+
+ public override bool IsInitialized
+ {
+ get { return wrappedBuilder.IsInitialized; }
+ }
+
+ public override IDictionary<FieldDescriptor, object> AllFields
+ {
+ get { return wrappedBuilder.AllFields; }
+ }
+
+ public override object this[FieldDescriptor field]
+ {
+ get { return wrappedBuilder[field]; }
+ set { wrappedBuilder[field] = value; }
+ }
+
+ public override MessageDescriptor DescriptorForType
+ {
+ get { return wrappedBuilder.DescriptorForType; }
+ }
+
+ public override int GetRepeatedFieldCount(FieldDescriptor field)
+ {
+ return wrappedBuilder.GetRepeatedFieldCount(field);
+ }
+
+ public override object this[FieldDescriptor field, int index]
+ {
+ get { return wrappedBuilder[field, index]; }
+ set { wrappedBuilder[field, index] = value; }
+ }
+
+ public override bool HasField(FieldDescriptor field)
+ {
+ return wrappedBuilder.HasField(field);
+ }
+
+ public override UnknownFieldSet UnknownFields
+ {
+ get { return wrappedBuilder.UnknownFields; }
+ set { wrappedBuilder.UnknownFields = value; }
+ }
+
+ public override AbstractMessageWrapper Build()
+ {
+ return new AbstractMessageWrapper(wrappedBuilder.WeakBuild());
+ }
+
+ public override AbstractMessageWrapper BuildPartial()
+ {
+ return new AbstractMessageWrapper(wrappedBuilder.WeakBuildPartial());
+ }
+
+ public override Builder Clone()
+ {
+ return new Builder(wrappedBuilder.WeakClone());
+ }
+
+ public override AbstractMessageWrapper DefaultInstanceForType
+ {
+ get { return new AbstractMessageWrapper(wrappedBuilder.WeakDefaultInstanceForType); }
+ }
+
+ public override Builder ClearField(FieldDescriptor field)
+ {
+ wrappedBuilder.WeakClearField(field);
+ return this;
+ }
+
+ public override Builder AddRepeatedField(FieldDescriptor field, object value)
+ {
+ wrappedBuilder.WeakAddRepeatedField(field, value);
+ return this;
+ }
+
+ public override IBuilder CreateBuilderForField(FieldDescriptor field)
+ {
+ wrappedBuilder.CreateBuilderForField(field);
+ return this;
+ }
+
+ public override Builder MergeFrom(IMessage other)
+ {
+ wrappedBuilder.WeakMergeFrom(other);
+ return this;
+ }
+
+ public override Builder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry)
+ {
+ wrappedBuilder.WeakMergeFrom(input, extensionRegistry);
+ return this;
+ }
+ }
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/ByteStringTest.cs b/src/ProtocolBuffers.Test/ByteStringTest.cs index 6106368f..0ba665de 100644 --- a/src/ProtocolBuffers.Test/ByteStringTest.cs +++ b/src/ProtocolBuffers.Test/ByteStringTest.cs @@ -1,117 +1,131 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System.Text; -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class ByteStringTest { - [Test] - public void EmptyByteStringHasZeroSize() { - Assert.AreEqual(0, ByteString.Empty.Length); - } - - [Test] - public void CopyFromStringWithExplicitEncoding() { - ByteString bs = ByteString.CopyFrom("AB", Encoding.Unicode); - Assert.AreEqual(4, bs.Length); - Assert.AreEqual(65, bs[0]); - Assert.AreEqual(0, bs[1]); - Assert.AreEqual(66, bs[2]); - Assert.AreEqual(0, bs[3]); - } - - [Test] - public void IsEmptyWhenEmpty() { - Assert.IsTrue(ByteString.CopyFromUtf8("").IsEmpty); - } - - [Test] - public void IsEmptyWhenNotEmpty() { - Assert.IsFalse(ByteString.CopyFromUtf8("X").IsEmpty); - } - - [Test] - public void CopyFromByteArrayCopiesContents() { - byte[] data = new byte[1]; - data[0] = 10; - ByteString bs = ByteString.CopyFrom(data); - Assert.AreEqual(10, bs[0]); - data[0] = 5; - Assert.AreEqual(10, bs[0]); - } - - [Test] - public void ToByteArrayCopiesContents() { - ByteString bs = ByteString.CopyFromUtf8("Hello"); - byte[] data = bs.ToByteArray(); - Assert.AreEqual('H', data[0]); - Assert.AreEqual('H', bs[0]); - data[0] = 0; - Assert.AreEqual(0, data[0]); - Assert.AreEqual('H', bs[0]); - } - - [Test] - public void CopyFromUtf8UsesUtf8() { - ByteString bs = ByteString.CopyFromUtf8("\u20ac"); - Assert.AreEqual(3, bs.Length); - Assert.AreEqual(0xe2, bs[0]); - Assert.AreEqual(0x82, bs[1]); - Assert.AreEqual(0xac, bs[2]); - } - - [Test] - public void CopyFromPortion() { - byte[] data = new byte[]{0, 1, 2, 3, 4, 5, 6}; - ByteString bs = ByteString.CopyFrom(data, 2, 3); - Assert.AreEqual(3, bs.Length); - Assert.AreEqual(2, bs[0]); - Assert.AreEqual(3, bs[1]); - } - - [Test] - public void ToStringUtf8() { - ByteString bs = ByteString.CopyFromUtf8("\u20ac"); - Assert.AreEqual("\u20ac", bs.ToStringUtf8()); - } - - [Test] - public void ToStringWithExplicitEncoding() { - ByteString bs = ByteString.CopyFrom("\u20ac", Encoding.Unicode); - Assert.AreEqual("\u20ac", bs.ToString(Encoding.Unicode)); - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System.Text;
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class ByteStringTest
+ {
+ [Test]
+ public void EmptyByteStringHasZeroSize()
+ {
+ Assert.AreEqual(0, ByteString.Empty.Length);
+ }
+
+ [Test]
+ public void CopyFromStringWithExplicitEncoding()
+ {
+ ByteString bs = ByteString.CopyFrom("AB", Encoding.Unicode);
+ Assert.AreEqual(4, bs.Length);
+ Assert.AreEqual(65, bs[0]);
+ Assert.AreEqual(0, bs[1]);
+ Assert.AreEqual(66, bs[2]);
+ Assert.AreEqual(0, bs[3]);
+ }
+
+ [Test]
+ public void IsEmptyWhenEmpty()
+ {
+ Assert.IsTrue(ByteString.CopyFromUtf8("").IsEmpty);
+ }
+
+ [Test]
+ public void IsEmptyWhenNotEmpty()
+ {
+ Assert.IsFalse(ByteString.CopyFromUtf8("X").IsEmpty);
+ }
+
+ [Test]
+ public void CopyFromByteArrayCopiesContents()
+ {
+ byte[] data = new byte[1];
+ data[0] = 10;
+ ByteString bs = ByteString.CopyFrom(data);
+ Assert.AreEqual(10, bs[0]);
+ data[0] = 5;
+ Assert.AreEqual(10, bs[0]);
+ }
+
+ [Test]
+ public void ToByteArrayCopiesContents()
+ {
+ ByteString bs = ByteString.CopyFromUtf8("Hello");
+ byte[] data = bs.ToByteArray();
+ Assert.AreEqual('H', data[0]);
+ Assert.AreEqual('H', bs[0]);
+ data[0] = 0;
+ Assert.AreEqual(0, data[0]);
+ Assert.AreEqual('H', bs[0]);
+ }
+
+ [Test]
+ public void CopyFromUtf8UsesUtf8()
+ {
+ ByteString bs = ByteString.CopyFromUtf8("\u20ac");
+ Assert.AreEqual(3, bs.Length);
+ Assert.AreEqual(0xe2, bs[0]);
+ Assert.AreEqual(0x82, bs[1]);
+ Assert.AreEqual(0xac, bs[2]);
+ }
+
+ [Test]
+ public void CopyFromPortion()
+ {
+ byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6};
+ ByteString bs = ByteString.CopyFrom(data, 2, 3);
+ Assert.AreEqual(3, bs.Length);
+ Assert.AreEqual(2, bs[0]);
+ Assert.AreEqual(3, bs[1]);
+ }
+
+ [Test]
+ public void ToStringUtf8()
+ {
+ ByteString bs = ByteString.CopyFromUtf8("\u20ac");
+ Assert.AreEqual("\u20ac", bs.ToStringUtf8());
+ }
+
+ [Test]
+ public void ToStringWithExplicitEncoding()
+ {
+ ByteString bs = ByteString.CopyFrom("\u20ac", Encoding.Unicode);
+ Assert.AreEqual("\u20ac", bs.ToString(Encoding.Unicode));
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/CSharpOptionsTest.cs b/src/ProtocolBuffers.Test/CSharpOptionsTest.cs index 2c755972..3901933b 100644 --- a/src/ProtocolBuffers.Test/CSharpOptionsTest.cs +++ b/src/ProtocolBuffers.Test/CSharpOptionsTest.cs @@ -1,104 +1,127 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using Google.ProtocolBuffers.DescriptorProtos; -using Google.ProtocolBuffers.Descriptors; -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class DescriptorUtilTest { - [Test] - public void ExplicitNamespace() { - FileDescriptorProto proto = new FileDescriptorProto.Builder { - Name = "x", Package = "pack", Options = new FileOptions.Builder().SetExtension(CSharpOptions.CSharpFileOptions, - new CSharpFileOptions.Builder { Namespace = "Foo.Bar" }.Build()).Build() - }.Build(); - FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null); - Assert.AreEqual("Foo.Bar", descriptor.CSharpOptions.Namespace); - } - - [Test] - public void NoNamespaceFallsBackToPackage() { - FileDescriptorProto proto = new FileDescriptorProto.Builder { Name = "x", Package = "pack" }.Build(); - FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null); - Assert.AreEqual("pack", descriptor.CSharpOptions.Namespace); - } - - [Test] - public void NoNamespaceOrPackageFallsBackToEmptyString() { - FileDescriptorProto proto = new FileDescriptorProto.Builder { Name = "x" }.Build(); - FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null); - Assert.AreEqual("", descriptor.CSharpOptions.Namespace); - } - - [Test] - public void ExplicitlyNamedFileClass() { - FileDescriptorProto proto = new FileDescriptorProto.Builder { - Name = "x", Options = new FileOptions.Builder().SetExtension(CSharpOptions.CSharpFileOptions, - new CSharpFileOptions.Builder { UmbrellaClassname = "Foo" }.Build()).Build() - }.Build(); - FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null); - Assert.AreEqual("Foo", descriptor.CSharpOptions.UmbrellaClassname); - } - - [Test] - public void ImplicitFileClassWithProtoSuffix() { - FileDescriptorProto proto = new FileDescriptorProto.Builder { Name = "foo_bar.proto" }.Build(); - FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null); - Assert.AreEqual("FooBar", descriptor.CSharpOptions.UmbrellaClassname); - } - - [Test] - public void ImplicitFileClassWithProtoDevelSuffix() { - FileDescriptorProto proto = new FileDescriptorProto.Builder { Name = "foo_bar.protodevel" }.Build(); - FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null); - Assert.AreEqual("FooBar", descriptor.CSharpOptions.UmbrellaClassname); - } - - [Test] - public void ImplicitFileClassWithNoSuffix() { - FileDescriptorProto proto = new FileDescriptorProto.Builder { Name = "foo_bar" }.Build(); - FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null); - Assert.AreEqual("FooBar", descriptor.CSharpOptions.UmbrellaClassname); - } - - [Test] - public void ImplicitFileClassWithDirectoryStructure() { - FileDescriptorProto proto = new FileDescriptorProto.Builder { Name = "x/y/foo_bar" }.Build(); - FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null); - Assert.AreEqual("FooBar", descriptor.CSharpOptions.UmbrellaClassname); - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using Google.ProtocolBuffers.DescriptorProtos;
+using Google.ProtocolBuffers.Descriptors;
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class DescriptorUtilTest
+ {
+ [Test]
+ public void ExplicitNamespace()
+ {
+ FileDescriptorProto proto = new FileDescriptorProto.Builder
+ {
+ Name = "x",
+ Package = "pack",
+ Options =
+ new FileOptions.Builder().SetExtension(
+ CSharpOptions.CSharpFileOptions,
+ new CSharpFileOptions.Builder {Namespace = "Foo.Bar"}.Build()).
+ Build()
+ }.Build();
+ FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null);
+ Assert.AreEqual("Foo.Bar", descriptor.CSharpOptions.Namespace);
+ }
+
+ [Test]
+ public void NoNamespaceFallsBackToPackage()
+ {
+ FileDescriptorProto proto = new FileDescriptorProto.Builder {Name = "x", Package = "pack"}.Build();
+ FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null);
+ Assert.AreEqual("pack", descriptor.CSharpOptions.Namespace);
+ }
+
+ [Test]
+ public void NoNamespaceOrPackageFallsBackToEmptyString()
+ {
+ FileDescriptorProto proto = new FileDescriptorProto.Builder {Name = "x"}.Build();
+ FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null);
+ Assert.AreEqual("", descriptor.CSharpOptions.Namespace);
+ }
+
+ [Test]
+ public void ExplicitlyNamedFileClass()
+ {
+ FileDescriptorProto proto = new FileDescriptorProto.Builder
+ {
+ Name = "x",
+ Options =
+ new FileOptions.Builder().SetExtension(
+ CSharpOptions.CSharpFileOptions,
+ new CSharpFileOptions.Builder {UmbrellaClassname = "Foo"}.Build())
+ .Build()
+ }.Build();
+ FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null);
+ Assert.AreEqual("Foo", descriptor.CSharpOptions.UmbrellaClassname);
+ }
+
+ [Test]
+ public void ImplicitFileClassWithProtoSuffix()
+ {
+ FileDescriptorProto proto = new FileDescriptorProto.Builder {Name = "foo_bar.proto"}.Build();
+ FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null);
+ Assert.AreEqual("FooBar", descriptor.CSharpOptions.UmbrellaClassname);
+ }
+
+ [Test]
+ public void ImplicitFileClassWithProtoDevelSuffix()
+ {
+ FileDescriptorProto proto = new FileDescriptorProto.Builder {Name = "foo_bar.protodevel"}.Build();
+ FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null);
+ Assert.AreEqual("FooBar", descriptor.CSharpOptions.UmbrellaClassname);
+ }
+
+ [Test]
+ public void ImplicitFileClassWithNoSuffix()
+ {
+ FileDescriptorProto proto = new FileDescriptorProto.Builder {Name = "foo_bar"}.Build();
+ FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null);
+ Assert.AreEqual("FooBar", descriptor.CSharpOptions.UmbrellaClassname);
+ }
+
+ [Test]
+ public void ImplicitFileClassWithDirectoryStructure()
+ {
+ FileDescriptorProto proto = new FileDescriptorProto.Builder {Name = "x/y/foo_bar"}.Build();
+ FileDescriptor descriptor = FileDescriptor.BuildFrom(proto, null);
+ Assert.AreEqual("FooBar", descriptor.CSharpOptions.UmbrellaClassname);
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/CodedInputStreamTest.cs b/src/ProtocolBuffers.Test/CodedInputStreamTest.cs index 037e9a00..878febee 100644 --- a/src/ProtocolBuffers.Test/CodedInputStreamTest.cs +++ b/src/ProtocolBuffers.Test/CodedInputStreamTest.cs @@ -1,459 +1,526 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.IO; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; -using System.Diagnostics; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class CodedInputStreamTest { - - /// <summary> - /// Helper to construct a byte array from a bunch of bytes. The inputs are - /// actually ints so that I can use hex notation and not get stupid errors - /// about precision. - /// </summary> - private static byte[] Bytes(params int[] bytesAsInts) { - byte[] bytes = new byte[bytesAsInts.Length]; - for (int i = 0; i < bytesAsInts.Length; i++) { - bytes[i] = (byte)bytesAsInts[i]; - } - return bytes; - } - - /// <summary> - /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and - /// </summary> - private static void AssertReadVarint(byte[] data, ulong value) { - CodedInputStream input = CodedInputStream.CreateInstance(data); - Assert.AreEqual((uint)value, input.ReadRawVarint32()); - - input = CodedInputStream.CreateInstance(data); - Assert.AreEqual(value, input.ReadRawVarint64()); - Assert.IsTrue(input.IsAtEnd); - - // Try different block sizes. - for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) { - input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize)); - Assert.AreEqual((uint)value, input.ReadRawVarint32()); - - input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize)); - Assert.AreEqual(value, input.ReadRawVarint64()); - Assert.IsTrue(input.IsAtEnd); - } - - // Try reading directly from a MemoryStream. We want to verify that it - // doesn't read past the end of the input, so write an extra byte - this - // lets us test the position at the end. - MemoryStream memoryStream = new MemoryStream(); - memoryStream.Write(data, 0, data.Length); - memoryStream.WriteByte(0); - memoryStream.Position = 0; - Assert.AreEqual((uint)value, CodedInputStream.ReadRawVarint32(memoryStream)); - Assert.AreEqual(data.Length, memoryStream.Position); - } - - /// <summary> - /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and - /// expects them to fail with an InvalidProtocolBufferException whose - /// description matches the given one. - /// </summary> - private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) { - CodedInputStream input = CodedInputStream.CreateInstance(data); - try { - input.ReadRawVarint32(); - Assert.Fail("Should have thrown an exception."); - } catch (InvalidProtocolBufferException e) { - Assert.AreEqual(expected.Message, e.Message); - } - - input = CodedInputStream.CreateInstance(data); - try { - input.ReadRawVarint64(); - Assert.Fail("Should have thrown an exception."); - } catch (InvalidProtocolBufferException e) { - Assert.AreEqual(expected.Message, e.Message); - } - - // Make sure we get the same error when reading directly from a Stream. - try { - CodedInputStream.ReadRawVarint32(new MemoryStream(data)); - Assert.Fail("Should have thrown an exception."); - } catch (InvalidProtocolBufferException e) { - Assert.AreEqual(expected.Message, e.Message); - } - } - - [Test] - public void ReadVarint() { - AssertReadVarint(Bytes(0x00), 0); - AssertReadVarint(Bytes(0x01), 1); - AssertReadVarint(Bytes(0x7f), 127); - // 14882 - AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7)); - // 2961488830 - AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b), - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (0x0bL << 28)); - - // 64-bit - // 7256456126 - AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b), - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (0x1bL << 28)); - // 41256202580718336 - AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49), - (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | - (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49)); - // 11964378330978735131 - AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01), - (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | - (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) | - (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63)); - - // Failures - AssertReadVarintFailure( - InvalidProtocolBufferException.MalformedVarint(), - Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x00)); - AssertReadVarintFailure( - InvalidProtocolBufferException.TruncatedMessage(), - Bytes(0x80)); - } - - /// <summary> - /// Parses the given bytes using ReadRawLittleEndian32() and checks - /// that the result matches the given value. - /// </summary> - private static void AssertReadLittleEndian32(byte[] data, uint value) { - CodedInputStream input = CodedInputStream.CreateInstance(data); - Assert.AreEqual(value, input.ReadRawLittleEndian32()); - Assert.IsTrue(input.IsAtEnd); - - // Try different block sizes. - for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { - input = CodedInputStream.CreateInstance( - new SmallBlockInputStream(data, blockSize)); - Assert.AreEqual(value, input.ReadRawLittleEndian32()); - Assert.IsTrue(input.IsAtEnd); - } - } - - /// <summary> - /// Parses the given bytes using ReadRawLittleEndian64() and checks - /// that the result matches the given value. - /// </summary> - private static void AssertReadLittleEndian64(byte[] data, ulong value) { - CodedInputStream input = CodedInputStream.CreateInstance(data); - Assert.AreEqual(value, input.ReadRawLittleEndian64()); - Assert.IsTrue(input.IsAtEnd); - - // Try different block sizes. - for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { - input = CodedInputStream.CreateInstance( - new SmallBlockInputStream(data, blockSize)); - Assert.AreEqual(value, input.ReadRawLittleEndian64()); - Assert.IsTrue(input.IsAtEnd); - } - } - - [Test] - public void ReadLittleEndian() { - AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678); - AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0); - - AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12), - 0x123456789abcdef0L); - AssertReadLittleEndian64( - Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL); - } - - [Test] - public void DecodeZigZag32() { - Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0)); - Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1)); - Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2)); - Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3)); - Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE)); - Assert.AreEqual(unchecked((int)0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF)); - Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE)); - Assert.AreEqual(unchecked((int)0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF)); - } - - [Test] - public void DecodeZigZag64() { - Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0)); - Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1)); - Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2)); - Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3)); - Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL)); - Assert.AreEqual(unchecked((long)0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL)); - Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL)); - Assert.AreEqual(unchecked((long)0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL)); - Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL)); - Assert.AreEqual(unchecked((long)0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL)); - } - - [Test] - public void ReadWholeMessage() { - TestAllTypes message = TestUtil.GetAllSet(); - - byte[] rawBytes = message.ToByteArray(); - Assert.AreEqual(rawBytes.Length, message.SerializedSize); - TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes); - TestUtil.AssertAllFieldsSet(message2); - - // Try different block sizes. - for (int blockSize = 1; blockSize < 256; blockSize *= 2) { - message2 = TestAllTypes.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize)); - TestUtil.AssertAllFieldsSet(message2); - } - } - - [Test] - public void SkipWholeMessage() { - TestAllTypes message = TestUtil.GetAllSet(); - byte[] rawBytes = message.ToByteArray(); - - // Create two parallel inputs. Parse one as unknown fields while using - // skipField() to skip each field on the other. Expect the same tags. - CodedInputStream input1 = CodedInputStream.CreateInstance(rawBytes); - CodedInputStream input2 = CodedInputStream.CreateInstance(rawBytes); - UnknownFieldSet.Builder unknownFields = UnknownFieldSet.CreateBuilder(); - - while (true) { - uint tag = input1.ReadTag(); - Assert.AreEqual(tag, input2.ReadTag()); - if (tag == 0) { - break; - } - unknownFields.MergeFieldFrom(tag, input1); - input2.SkipField(tag); - } - } - - /// <summary> - /// Test that a bug in SkipRawBytes has been fixed: if the skip - /// skips exactly up to a limit, this should bnot break things - /// </summary> - [Test] - public void SkipRawBytesBug() { - byte[] rawBytes = new byte[] { 1, 2 }; - CodedInputStream input = CodedInputStream.CreateInstance(rawBytes); - - int limit = input.PushLimit(1); - input.SkipRawBytes(1); - input.PopLimit(limit); - Assert.AreEqual(2, input.ReadRawByte()); - } - - public void ReadHugeBlob() { - // Allocate and initialize a 1MB blob. - byte[] blob = new byte[1 << 20]; - for (int i = 0; i < blob.Length; i++) { - blob[i] = (byte)i; - } - - // Make a message containing it. - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - builder.SetOptionalBytes(ByteString.CopyFrom(blob)); - TestAllTypes message = builder.Build(); - - // Serialize and parse it. Make sure to parse from an InputStream, not - // directly from a ByteString, so that CodedInputStream uses buffered - // reading. - TestAllTypes message2 = TestAllTypes.ParseFrom(message.ToByteString().CreateCodedInput()); - - Assert.AreEqual(message.OptionalBytes, message2.OptionalBytes); - - // Make sure all the other fields were parsed correctly. - TestAllTypes message3 = TestAllTypes.CreateBuilder(message2) - .SetOptionalBytes(TestUtil.GetAllSet().OptionalBytes) - .Build(); - TestUtil.AssertAllFieldsSet(message3); - } - - [Test] - public void ReadMaliciouslyLargeBlob() { - MemoryStream ms = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(ms); - - uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); - output.WriteRawVarint32(tag); - output.WriteRawVarint32(0x7FFFFFFF); - output.WriteRawBytes(new byte[32]); // Pad with a few random bytes. - output.Flush(); - ms.Position = 0; - - CodedInputStream input = CodedInputStream.CreateInstance(ms); - Assert.AreEqual(tag, input.ReadTag()); - - try { - input.ReadBytes(); - Assert.Fail("Should have thrown an exception!"); - } catch (InvalidProtocolBufferException) { - // success. - } - } - - private static TestRecursiveMessage MakeRecursiveMessage(int depth) { - if (depth == 0) { - return TestRecursiveMessage.CreateBuilder().SetI(5).Build(); - } else { - return TestRecursiveMessage.CreateBuilder() - .SetA(MakeRecursiveMessage(depth - 1)).Build(); - } - } - - private static void AssertMessageDepth(TestRecursiveMessage message, int depth) { - if (depth == 0) { - Assert.IsFalse(message.HasA); - Assert.AreEqual(5, message.I); - } else { - Assert.IsTrue(message.HasA); - AssertMessageDepth(message.A, depth - 1); - } - } - - [Test] - public void MaliciousRecursion() { - ByteString data64 = MakeRecursiveMessage(64).ToByteString(); - ByteString data65 = MakeRecursiveMessage(65).ToByteString(); - - AssertMessageDepth(TestRecursiveMessage.ParseFrom(data64), 64); - - try { - TestRecursiveMessage.ParseFrom(data65); - Assert.Fail("Should have thrown an exception!"); - } catch (InvalidProtocolBufferException) { - // success. - } - - CodedInputStream input = data64.CreateCodedInput(); - input.SetRecursionLimit(8); - try { - TestRecursiveMessage.ParseFrom(input); - Assert.Fail("Should have thrown an exception!"); - } catch (InvalidProtocolBufferException) { - // success. - } - } - - [Test] - public void SizeLimit() { - // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't - // apply to the latter case. - MemoryStream ms = new MemoryStream(TestUtil.GetAllSet().ToByteString().ToByteArray()); - CodedInputStream input = CodedInputStream.CreateInstance(ms); - input.SetSizeLimit(16); - - try { - TestAllTypes.ParseFrom(input); - Assert.Fail("Should have thrown an exception!"); - } catch (InvalidProtocolBufferException) { - // success. - } - } - - [Test] - public void ResetSizeCounter() { - CodedInputStream input = CodedInputStream.CreateInstance( - new SmallBlockInputStream(new byte[256], 8)); - input.SetSizeLimit(16); - input.ReadRawBytes(16); - - try { - input.ReadRawByte(); - Assert.Fail("Should have thrown an exception!"); - } catch (InvalidProtocolBufferException) { - // Success. - } - - input.ResetSizeCounter(); - input.ReadRawByte(); // No exception thrown. - - try { - input.ReadRawBytes(16); // Hits limit again. - Assert.Fail("Should have thrown an exception!"); - } catch (InvalidProtocolBufferException) { - // Success. - } - } - - /// <summary> - /// Tests that if we read an string that contains invalid UTF-8, no exception - /// is thrown. Instead, the invalid bytes are replaced with the Unicode - /// "replacement character" U+FFFD. - /// </summary> - [Test] - public void ReadInvalidUtf8() { - MemoryStream ms = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(ms); - - uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); - output.WriteRawVarint32(tag); - output.WriteRawVarint32(1); - output.WriteRawBytes(new byte[] { 0x80 }); - output.Flush(); - ms.Position = 0; - - CodedInputStream input = CodedInputStream.CreateInstance(ms); - Assert.AreEqual(tag, input.ReadTag()); - string text = input.ReadString(); - Assert.AreEqual('\ufffd', text[0]); - } - - /// <summary> - /// A stream which limits the number of bytes it reads at a time. - /// We use this to make sure that CodedInputStream doesn't screw up when - /// reading in small blocks. - /// </summary> - private sealed class SmallBlockInputStream : MemoryStream { - private readonly int blockSize; - - public SmallBlockInputStream(byte[] data, int blockSize) - : base(data) { - this.blockSize = blockSize; - } - - public override int Read(byte[] buffer, int offset, int count) { - return base.Read(buffer, offset, Math.Min(count, blockSize)); - } - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System;
+using System.IO;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+using System.Diagnostics;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class CodedInputStreamTest
+ {
+ /// <summary>
+ /// Helper to construct a byte array from a bunch of bytes. The inputs are
+ /// actually ints so that I can use hex notation and not get stupid errors
+ /// about precision.
+ /// </summary>
+ private static byte[] Bytes(params int[] bytesAsInts)
+ {
+ byte[] bytes = new byte[bytesAsInts.Length];
+ for (int i = 0; i < bytesAsInts.Length; i++)
+ {
+ bytes[i] = (byte) bytesAsInts[i];
+ }
+ return bytes;
+ }
+
+ /// <summary>
+ /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
+ /// </summary>
+ private static void AssertReadVarint(byte[] data, ulong value)
+ {
+ CodedInputStream input = CodedInputStream.CreateInstance(data);
+ Assert.AreEqual((uint) value, input.ReadRawVarint32());
+
+ input = CodedInputStream.CreateInstance(data);
+ Assert.AreEqual(value, input.ReadRawVarint64());
+ Assert.IsTrue(input.IsAtEnd);
+
+ // Try different block sizes.
+ for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
+ {
+ input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
+ Assert.AreEqual((uint) value, input.ReadRawVarint32());
+
+ input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
+ Assert.AreEqual(value, input.ReadRawVarint64());
+ Assert.IsTrue(input.IsAtEnd);
+ }
+
+ // Try reading directly from a MemoryStream. We want to verify that it
+ // doesn't read past the end of the input, so write an extra byte - this
+ // lets us test the position at the end.
+ MemoryStream memoryStream = new MemoryStream();
+ memoryStream.Write(data, 0, data.Length);
+ memoryStream.WriteByte(0);
+ memoryStream.Position = 0;
+ Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream));
+ Assert.AreEqual(data.Length, memoryStream.Position);
+ }
+
+ /// <summary>
+ /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
+ /// expects them to fail with an InvalidProtocolBufferException whose
+ /// description matches the given one.
+ /// </summary>
+ private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data)
+ {
+ CodedInputStream input = CodedInputStream.CreateInstance(data);
+ try
+ {
+ input.ReadRawVarint32();
+ Assert.Fail("Should have thrown an exception.");
+ }
+ catch (InvalidProtocolBufferException e)
+ {
+ Assert.AreEqual(expected.Message, e.Message);
+ }
+
+ input = CodedInputStream.CreateInstance(data);
+ try
+ {
+ input.ReadRawVarint64();
+ Assert.Fail("Should have thrown an exception.");
+ }
+ catch (InvalidProtocolBufferException e)
+ {
+ Assert.AreEqual(expected.Message, e.Message);
+ }
+
+ // Make sure we get the same error when reading directly from a Stream.
+ try
+ {
+ CodedInputStream.ReadRawVarint32(new MemoryStream(data));
+ Assert.Fail("Should have thrown an exception.");
+ }
+ catch (InvalidProtocolBufferException e)
+ {
+ Assert.AreEqual(expected.Message, e.Message);
+ }
+ }
+
+ [Test]
+ public void ReadVarint()
+ {
+ AssertReadVarint(Bytes(0x00), 0);
+ AssertReadVarint(Bytes(0x01), 1);
+ AssertReadVarint(Bytes(0x7f), 127);
+ // 14882
+ AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
+ // 2961488830
+ AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
+ (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
+ (0x0bL << 28));
+
+ // 64-bit
+ // 7256456126
+ AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
+ (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
+ (0x1bL << 28));
+ // 41256202580718336
+ AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
+ (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
+ (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
+ // 11964378330978735131
+ AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
+ (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
+ (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
+ (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
+
+ // Failures
+ AssertReadVarintFailure(
+ InvalidProtocolBufferException.MalformedVarint(),
+ Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
+ 0x00));
+ AssertReadVarintFailure(
+ InvalidProtocolBufferException.TruncatedMessage(),
+ Bytes(0x80));
+ }
+
+ /// <summary>
+ /// Parses the given bytes using ReadRawLittleEndian32() and checks
+ /// that the result matches the given value.
+ /// </summary>
+ private static void AssertReadLittleEndian32(byte[] data, uint value)
+ {
+ CodedInputStream input = CodedInputStream.CreateInstance(data);
+ Assert.AreEqual(value, input.ReadRawLittleEndian32());
+ Assert.IsTrue(input.IsAtEnd);
+
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
+ {
+ input = CodedInputStream.CreateInstance(
+ new SmallBlockInputStream(data, blockSize));
+ Assert.AreEqual(value, input.ReadRawLittleEndian32());
+ Assert.IsTrue(input.IsAtEnd);
+ }
+ }
+
+ /// <summary>
+ /// Parses the given bytes using ReadRawLittleEndian64() and checks
+ /// that the result matches the given value.
+ /// </summary>
+ private static void AssertReadLittleEndian64(byte[] data, ulong value)
+ {
+ CodedInputStream input = CodedInputStream.CreateInstance(data);
+ Assert.AreEqual(value, input.ReadRawLittleEndian64());
+ Assert.IsTrue(input.IsAtEnd);
+
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
+ {
+ input = CodedInputStream.CreateInstance(
+ new SmallBlockInputStream(data, blockSize));
+ Assert.AreEqual(value, input.ReadRawLittleEndian64());
+ Assert.IsTrue(input.IsAtEnd);
+ }
+ }
+
+ [Test]
+ public void ReadLittleEndian()
+ {
+ AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
+ AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
+
+ AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
+ 0x123456789abcdef0L);
+ AssertReadLittleEndian64(
+ Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
+ }
+
+ [Test]
+ public void DecodeZigZag32()
+ {
+ Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0));
+ Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1));
+ Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2));
+ Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3));
+ Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE));
+ Assert.AreEqual(unchecked((int) 0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF));
+ Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE));
+ Assert.AreEqual(unchecked((int) 0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF));
+ }
+
+ [Test]
+ public void DecodeZigZag64()
+ {
+ Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0));
+ Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1));
+ Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2));
+ Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3));
+ Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
+ Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
+ Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
+ Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
+ Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
+ Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
+ }
+
+ [Test]
+ public void ReadWholeMessage()
+ {
+ TestAllTypes message = TestUtil.GetAllSet();
+
+ byte[] rawBytes = message.ToByteArray();
+ Assert.AreEqual(rawBytes.Length, message.SerializedSize);
+ TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
+ TestUtil.AssertAllFieldsSet(message2);
+
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize < 256; blockSize *= 2)
+ {
+ message2 = TestAllTypes.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
+ TestUtil.AssertAllFieldsSet(message2);
+ }
+ }
+
+ [Test]
+ public void SkipWholeMessage()
+ {
+ TestAllTypes message = TestUtil.GetAllSet();
+ byte[] rawBytes = message.ToByteArray();
+
+ // Create two parallel inputs. Parse one as unknown fields while using
+ // skipField() to skip each field on the other. Expect the same tags.
+ CodedInputStream input1 = CodedInputStream.CreateInstance(rawBytes);
+ CodedInputStream input2 = CodedInputStream.CreateInstance(rawBytes);
+ UnknownFieldSet.Builder unknownFields = UnknownFieldSet.CreateBuilder();
+
+ while (true)
+ {
+ uint tag = input1.ReadTag();
+ Assert.AreEqual(tag, input2.ReadTag());
+ if (tag == 0)
+ {
+ break;
+ }
+ unknownFields.MergeFieldFrom(tag, input1);
+ input2.SkipField(tag);
+ }
+ }
+
+ /// <summary>
+ /// Test that a bug in SkipRawBytes has been fixed: if the skip
+ /// skips exactly up to a limit, this should bnot break things
+ /// </summary>
+ [Test]
+ public void SkipRawBytesBug()
+ {
+ byte[] rawBytes = new byte[] {1, 2};
+ CodedInputStream input = CodedInputStream.CreateInstance(rawBytes);
+
+ int limit = input.PushLimit(1);
+ input.SkipRawBytes(1);
+ input.PopLimit(limit);
+ Assert.AreEqual(2, input.ReadRawByte());
+ }
+
+ public void ReadHugeBlob()
+ {
+ // Allocate and initialize a 1MB blob.
+ byte[] blob = new byte[1 << 20];
+ for (int i = 0; i < blob.Length; i++)
+ {
+ blob[i] = (byte) i;
+ }
+
+ // Make a message containing it.
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TestUtil.SetAllFields(builder);
+ builder.SetOptionalBytes(ByteString.CopyFrom(blob));
+ TestAllTypes message = builder.Build();
+
+ // Serialize and parse it. Make sure to parse from an InputStream, not
+ // directly from a ByteString, so that CodedInputStream uses buffered
+ // reading.
+ TestAllTypes message2 = TestAllTypes.ParseFrom(message.ToByteString().CreateCodedInput());
+
+ Assert.AreEqual(message.OptionalBytes, message2.OptionalBytes);
+
+ // Make sure all the other fields were parsed correctly.
+ TestAllTypes message3 = TestAllTypes.CreateBuilder(message2)
+ .SetOptionalBytes(TestUtil.GetAllSet().OptionalBytes)
+ .Build();
+ TestUtil.AssertAllFieldsSet(message3);
+ }
+
+ [Test]
+ public void ReadMaliciouslyLargeBlob()
+ {
+ MemoryStream ms = new MemoryStream();
+ CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
+
+ uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
+ output.WriteRawVarint32(tag);
+ output.WriteRawVarint32(0x7FFFFFFF);
+ output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
+ output.Flush();
+ ms.Position = 0;
+
+ CodedInputStream input = CodedInputStream.CreateInstance(ms);
+ Assert.AreEqual(tag, input.ReadTag());
+
+ try
+ {
+ input.ReadBytes();
+ Assert.Fail("Should have thrown an exception!");
+ }
+ catch (InvalidProtocolBufferException)
+ {
+ // success.
+ }
+ }
+
+ private static TestRecursiveMessage MakeRecursiveMessage(int depth)
+ {
+ if (depth == 0)
+ {
+ return TestRecursiveMessage.CreateBuilder().SetI(5).Build();
+ }
+ else
+ {
+ return TestRecursiveMessage.CreateBuilder()
+ .SetA(MakeRecursiveMessage(depth - 1)).Build();
+ }
+ }
+
+ private static void AssertMessageDepth(TestRecursiveMessage message, int depth)
+ {
+ if (depth == 0)
+ {
+ Assert.IsFalse(message.HasA);
+ Assert.AreEqual(5, message.I);
+ }
+ else
+ {
+ Assert.IsTrue(message.HasA);
+ AssertMessageDepth(message.A, depth - 1);
+ }
+ }
+
+ [Test]
+ public void MaliciousRecursion()
+ {
+ ByteString data64 = MakeRecursiveMessage(64).ToByteString();
+ ByteString data65 = MakeRecursiveMessage(65).ToByteString();
+
+ AssertMessageDepth(TestRecursiveMessage.ParseFrom(data64), 64);
+
+ try
+ {
+ TestRecursiveMessage.ParseFrom(data65);
+ Assert.Fail("Should have thrown an exception!");
+ }
+ catch (InvalidProtocolBufferException)
+ {
+ // success.
+ }
+
+ CodedInputStream input = data64.CreateCodedInput();
+ input.SetRecursionLimit(8);
+ try
+ {
+ TestRecursiveMessage.ParseFrom(input);
+ Assert.Fail("Should have thrown an exception!");
+ }
+ catch (InvalidProtocolBufferException)
+ {
+ // success.
+ }
+ }
+
+ [Test]
+ public void SizeLimit()
+ {
+ // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
+ // apply to the latter case.
+ MemoryStream ms = new MemoryStream(TestUtil.GetAllSet().ToByteString().ToByteArray());
+ CodedInputStream input = CodedInputStream.CreateInstance(ms);
+ input.SetSizeLimit(16);
+
+ try
+ {
+ TestAllTypes.ParseFrom(input);
+ Assert.Fail("Should have thrown an exception!");
+ }
+ catch (InvalidProtocolBufferException)
+ {
+ // success.
+ }
+ }
+
+ [Test]
+ public void ResetSizeCounter()
+ {
+ CodedInputStream input = CodedInputStream.CreateInstance(
+ new SmallBlockInputStream(new byte[256], 8));
+ input.SetSizeLimit(16);
+ input.ReadRawBytes(16);
+
+ try
+ {
+ input.ReadRawByte();
+ Assert.Fail("Should have thrown an exception!");
+ }
+ catch (InvalidProtocolBufferException)
+ {
+ // Success.
+ }
+
+ input.ResetSizeCounter();
+ input.ReadRawByte(); // No exception thrown.
+
+ try
+ {
+ input.ReadRawBytes(16); // Hits limit again.
+ Assert.Fail("Should have thrown an exception!");
+ }
+ catch (InvalidProtocolBufferException)
+ {
+ // Success.
+ }
+ }
+
+ /// <summary>
+ /// Tests that if we read an string that contains invalid UTF-8, no exception
+ /// is thrown. Instead, the invalid bytes are replaced with the Unicode
+ /// "replacement character" U+FFFD.
+ /// </summary>
+ [Test]
+ public void ReadInvalidUtf8()
+ {
+ MemoryStream ms = new MemoryStream();
+ CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
+
+ uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
+ output.WriteRawVarint32(tag);
+ output.WriteRawVarint32(1);
+ output.WriteRawBytes(new byte[] {0x80});
+ output.Flush();
+ ms.Position = 0;
+
+ CodedInputStream input = CodedInputStream.CreateInstance(ms);
+ Assert.AreEqual(tag, input.ReadTag());
+ string text = input.ReadString();
+ Assert.AreEqual('\ufffd', text[0]);
+ }
+
+ /// <summary>
+ /// A stream which limits the number of bytes it reads at a time.
+ /// We use this to make sure that CodedInputStream doesn't screw up when
+ /// reading in small blocks.
+ /// </summary>
+ private sealed class SmallBlockInputStream : MemoryStream
+ {
+ private readonly int blockSize;
+
+ public SmallBlockInputStream(byte[] data, int blockSize)
+ : base(data)
+ {
+ this.blockSize = blockSize;
+ }
+
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ return base.Read(buffer, offset, Math.Min(count, blockSize));
+ }
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs b/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs index a8291a23..3dd2e0c3 100644 --- a/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs +++ b/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs @@ -1,270 +1,292 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System.IO; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class CodedOutputStreamTest { - - /// <summary> - /// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and - /// checks that the result matches the given bytes - /// </summary> - private static void AssertWriteVarint(byte[] data, ulong value) { - // Only do 32-bit write if the value fits in 32 bits. - if ((value >> 32) == 0) { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput); - output.WriteRawVarint32((uint) value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - // Also try computing size. - Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value)); - } - - { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput); - output.WriteRawVarint64(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - // Also try computing size. - Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value)); - } - - // Try different buffer sizes. - for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) { - // Only do 32-bit write if the value fits in 32 bits. - if ((value >> 32) == 0) { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = - CodedOutputStream.CreateInstance(rawOutput, bufferSize); - output.WriteRawVarint32((uint) value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - } - - { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput, bufferSize); - output.WriteRawVarint64(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - } - } - } - - /// <summary> - /// Tests WriteRawVarint32() and WriteRawVarint64() - /// </summary> - [Test] - public void WriteVarint() { - AssertWriteVarint(new byte[] {0x00}, 0); - AssertWriteVarint(new byte[] {0x01}, 1); - AssertWriteVarint(new byte[] {0x7f}, 127); - // 14882 - AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7)); - // 2961488830 - AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b}, - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (0x0bL << 28)); - - // 64-bit - // 7256456126 - AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b}, - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (0x1bL << 28)); - // 41256202580718336 - AssertWriteVarint( - new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49}, - (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | - (0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49)); - // 11964378330978735131 - AssertWriteVarint( - new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01}, - unchecked((ulong) - ((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | - (0x3bL << 28) | (0x56L << 35) | (0x00L << 42) | - (0x05L << 49) | (0x26L << 56) | (0x01L << 63)))); - } - - /// <summary> - /// Parses the given bytes using WriteRawLittleEndian32() and checks - /// that the result matches the given value. - /// </summary> - private static void AssertWriteLittleEndian32(byte[] data, uint value) { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput); - output.WriteRawLittleEndian32(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - // Try different buffer sizes. - for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) { - rawOutput = new MemoryStream(); - output = CodedOutputStream.CreateInstance(rawOutput, bufferSize); - output.WriteRawLittleEndian32(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - } - } - - /// <summary> - /// Parses the given bytes using WriteRawLittleEndian64() and checks - /// that the result matches the given value. - /// </summary> - private static void AssertWriteLittleEndian64(byte[] data, ulong value) { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput); - output.WriteRawLittleEndian64(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - // Try different block sizes. - for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { - rawOutput = new MemoryStream(); - output = CodedOutputStream.CreateInstance(rawOutput, blockSize); - output.WriteRawLittleEndian64(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - } - } - - /// <summary> - /// Tests writeRawLittleEndian32() and writeRawLittleEndian64(). - /// </summary> - [Test] - public void WriteLittleEndian() { - AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678); - AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0); - - AssertWriteLittleEndian64( - new byte[]{0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}, - 0x123456789abcdef0L); - AssertWriteLittleEndian64( - new byte[]{0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a}, - 0x9abcdef012345678UL); - } - - [Test] - public void WriteWholeMessage() { - TestAllTypes message = TestUtil.GetAllSet(); - - byte[] rawBytes = message.ToByteArray(); - TestUtil.AssertEqualBytes(TestUtil.GoldenMessage.ToByteArray(), rawBytes); - - // Try different block sizes. - for (int blockSize = 1; blockSize < 256; blockSize *= 2) { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = - CodedOutputStream.CreateInstance(rawOutput, blockSize); - message.WriteTo(output); - output.Flush(); - TestUtil.AssertEqualBytes(rawBytes, rawOutput.ToArray()); - } - } - - /// <summary> - /// Tests writing a whole message with every packed field type. Ensures the - /// wire format of packed fields is compatible with C++. - /// </summary> - [Test] - public void WriteWholePackedFieldsMessage() { - TestPackedTypes message = TestUtil.GetPackedSet(); - - byte[] rawBytes = message.ToByteArray(); - TestUtil.AssertEqualBytes(TestUtil.GetGoldenPackedFieldsMessage().ToByteArray(), - rawBytes); - } - - [Test] - public void EncodeZigZag32() { - Assert.AreEqual(0, CodedOutputStream.EncodeZigZag32( 0)); - Assert.AreEqual(1, CodedOutputStream.EncodeZigZag32(-1)); - Assert.AreEqual(2, CodedOutputStream.EncodeZigZag32( 1)); - Assert.AreEqual(3, CodedOutputStream.EncodeZigZag32(-2)); - Assert.AreEqual(0x7FFFFFFE, CodedOutputStream.EncodeZigZag32(0x3FFFFFFF)); - Assert.AreEqual(0x7FFFFFFF, CodedOutputStream.EncodeZigZag32(unchecked((int)0xC0000000))); - Assert.AreEqual(0xFFFFFFFE, CodedOutputStream.EncodeZigZag32(0x7FFFFFFF)); - Assert.AreEqual(0xFFFFFFFF, CodedOutputStream.EncodeZigZag32(unchecked((int)0x80000000))); - } - - [Test] - public void EncodeZigZag64() { - Assert.AreEqual(0, CodedOutputStream.EncodeZigZag64( 0)); - Assert.AreEqual(1, CodedOutputStream.EncodeZigZag64(-1)); - Assert.AreEqual(2, CodedOutputStream.EncodeZigZag64( 1)); - Assert.AreEqual(3, CodedOutputStream.EncodeZigZag64(-2)); - Assert.AreEqual(0x000000007FFFFFFEL, - CodedOutputStream.EncodeZigZag64(unchecked((long)0x000000003FFFFFFFUL))); - Assert.AreEqual(0x000000007FFFFFFFL, - CodedOutputStream.EncodeZigZag64(unchecked((long)0xFFFFFFFFC0000000UL))); - Assert.AreEqual(0x00000000FFFFFFFEL, - CodedOutputStream.EncodeZigZag64(unchecked((long)0x000000007FFFFFFFUL))); - Assert.AreEqual(0x00000000FFFFFFFFL, - CodedOutputStream.EncodeZigZag64(unchecked((long)0xFFFFFFFF80000000UL))); - Assert.AreEqual(0xFFFFFFFFFFFFFFFEL, - CodedOutputStream.EncodeZigZag64(unchecked((long)0x7FFFFFFFFFFFFFFFUL))); - Assert.AreEqual(0xFFFFFFFFFFFFFFFFL, - CodedOutputStream.EncodeZigZag64(unchecked((long)0x8000000000000000UL))); - } - - [Test] - public void RoundTripZigZag32() { - // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1) - // were chosen semi-randomly via keyboard bashing. - Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(0))); - Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(1))); - Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-1))); - Assert.AreEqual(14927, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(14927))); - Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-3612))); - } - - [Test] - public void RoundTripZigZag64() { - Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(0))); - Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(1))); - Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-1))); - Assert.AreEqual(14927, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(14927))); - Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-3612))); - - Assert.AreEqual(856912304801416L, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(856912304801416L))); - Assert.AreEqual(-75123905439571256L, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-75123905439571256L))); - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System.IO;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class CodedOutputStreamTest
+ {
+ /// <summary>
+ /// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and
+ /// checks that the result matches the given bytes
+ /// </summary>
+ private static void AssertWriteVarint(byte[] data, ulong value)
+ {
+ // Only do 32-bit write if the value fits in 32 bits.
+ if ((value >> 32) == 0)
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput);
+ output.WriteRawVarint32((uint) value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+ // Also try computing size.
+ Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value));
+ }
+
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput);
+ output.WriteRawVarint64(value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+
+ // Also try computing size.
+ Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value));
+ }
+
+ // Try different buffer sizes.
+ for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
+ {
+ // Only do 32-bit write if the value fits in 32 bits.
+ if ((value >> 32) == 0)
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output =
+ CodedOutputStream.CreateInstance(rawOutput, bufferSize);
+ output.WriteRawVarint32((uint) value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+ }
+
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput, bufferSize);
+ output.WriteRawVarint64(value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+ }
+ }
+ }
+
+ /// <summary>
+ /// Tests WriteRawVarint32() and WriteRawVarint64()
+ /// </summary>
+ [Test]
+ public void WriteVarint()
+ {
+ AssertWriteVarint(new byte[] {0x00}, 0);
+ AssertWriteVarint(new byte[] {0x01}, 1);
+ AssertWriteVarint(new byte[] {0x7f}, 127);
+ // 14882
+ AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7));
+ // 2961488830
+ AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b},
+ (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
+ (0x0bL << 28));
+
+ // 64-bit
+ // 7256456126
+ AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b},
+ (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
+ (0x1bL << 28));
+ // 41256202580718336
+ AssertWriteVarint(
+ new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49},
+ (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
+ (0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49));
+ // 11964378330978735131
+ AssertWriteVarint(
+ new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01},
+ unchecked((ulong)
+ ((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
+ (0x3bL << 28) | (0x56L << 35) | (0x00L << 42) |
+ (0x05L << 49) | (0x26L << 56) | (0x01L << 63))));
+ }
+
+ /// <summary>
+ /// Parses the given bytes using WriteRawLittleEndian32() and checks
+ /// that the result matches the given value.
+ /// </summary>
+ private static void AssertWriteLittleEndian32(byte[] data, uint value)
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput);
+ output.WriteRawLittleEndian32(value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+
+ // Try different buffer sizes.
+ for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
+ {
+ rawOutput = new MemoryStream();
+ output = CodedOutputStream.CreateInstance(rawOutput, bufferSize);
+ output.WriteRawLittleEndian32(value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+ }
+ }
+
+ /// <summary>
+ /// Parses the given bytes using WriteRawLittleEndian64() and checks
+ /// that the result matches the given value.
+ /// </summary>
+ private static void AssertWriteLittleEndian64(byte[] data, ulong value)
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput);
+ output.WriteRawLittleEndian64(value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
+ {
+ rawOutput = new MemoryStream();
+ output = CodedOutputStream.CreateInstance(rawOutput, blockSize);
+ output.WriteRawLittleEndian64(value);
+ output.Flush();
+ Assert.AreEqual(data, rawOutput.ToArray());
+ }
+ }
+
+ /// <summary>
+ /// Tests writeRawLittleEndian32() and writeRawLittleEndian64().
+ /// </summary>
+ [Test]
+ public void WriteLittleEndian()
+ {
+ AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678);
+ AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0);
+
+ AssertWriteLittleEndian64(
+ new byte[] {0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12},
+ 0x123456789abcdef0L);
+ AssertWriteLittleEndian64(
+ new byte[] {0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a},
+ 0x9abcdef012345678UL);
+ }
+
+ [Test]
+ public void WriteWholeMessage()
+ {
+ TestAllTypes message = TestUtil.GetAllSet();
+
+ byte[] rawBytes = message.ToByteArray();
+ TestUtil.AssertEqualBytes(TestUtil.GoldenMessage.ToByteArray(), rawBytes);
+
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize < 256; blockSize *= 2)
+ {
+ MemoryStream rawOutput = new MemoryStream();
+ CodedOutputStream output =
+ CodedOutputStream.CreateInstance(rawOutput, blockSize);
+ message.WriteTo(output);
+ output.Flush();
+ TestUtil.AssertEqualBytes(rawBytes, rawOutput.ToArray());
+ }
+ }
+
+ /// <summary>
+ /// Tests writing a whole message with every packed field type. Ensures the
+ /// wire format of packed fields is compatible with C++.
+ /// </summary>
+ [Test]
+ public void WriteWholePackedFieldsMessage()
+ {
+ TestPackedTypes message = TestUtil.GetPackedSet();
+
+ byte[] rawBytes = message.ToByteArray();
+ TestUtil.AssertEqualBytes(TestUtil.GetGoldenPackedFieldsMessage().ToByteArray(),
+ rawBytes);
+ }
+
+ [Test]
+ public void EncodeZigZag32()
+ {
+ Assert.AreEqual(0, CodedOutputStream.EncodeZigZag32(0));
+ Assert.AreEqual(1, CodedOutputStream.EncodeZigZag32(-1));
+ Assert.AreEqual(2, CodedOutputStream.EncodeZigZag32(1));
+ Assert.AreEqual(3, CodedOutputStream.EncodeZigZag32(-2));
+ Assert.AreEqual(0x7FFFFFFE, CodedOutputStream.EncodeZigZag32(0x3FFFFFFF));
+ Assert.AreEqual(0x7FFFFFFF, CodedOutputStream.EncodeZigZag32(unchecked((int) 0xC0000000)));
+ Assert.AreEqual(0xFFFFFFFE, CodedOutputStream.EncodeZigZag32(0x7FFFFFFF));
+ Assert.AreEqual(0xFFFFFFFF, CodedOutputStream.EncodeZigZag32(unchecked((int) 0x80000000)));
+ }
+
+ [Test]
+ public void EncodeZigZag64()
+ {
+ Assert.AreEqual(0, CodedOutputStream.EncodeZigZag64(0));
+ Assert.AreEqual(1, CodedOutputStream.EncodeZigZag64(-1));
+ Assert.AreEqual(2, CodedOutputStream.EncodeZigZag64(1));
+ Assert.AreEqual(3, CodedOutputStream.EncodeZigZag64(-2));
+ Assert.AreEqual(0x000000007FFFFFFEL,
+ CodedOutputStream.EncodeZigZag64(unchecked((long) 0x000000003FFFFFFFUL)));
+ Assert.AreEqual(0x000000007FFFFFFFL,
+ CodedOutputStream.EncodeZigZag64(unchecked((long) 0xFFFFFFFFC0000000UL)));
+ Assert.AreEqual(0x00000000FFFFFFFEL,
+ CodedOutputStream.EncodeZigZag64(unchecked((long) 0x000000007FFFFFFFUL)));
+ Assert.AreEqual(0x00000000FFFFFFFFL,
+ CodedOutputStream.EncodeZigZag64(unchecked((long) 0xFFFFFFFF80000000UL)));
+ Assert.AreEqual(0xFFFFFFFFFFFFFFFEL,
+ CodedOutputStream.EncodeZigZag64(unchecked((long) 0x7FFFFFFFFFFFFFFFUL)));
+ Assert.AreEqual(0xFFFFFFFFFFFFFFFFL,
+ CodedOutputStream.EncodeZigZag64(unchecked((long) 0x8000000000000000UL)));
+ }
+
+ [Test]
+ public void RoundTripZigZag32()
+ {
+ // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
+ // were chosen semi-randomly via keyboard bashing.
+ Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(0)));
+ Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(1)));
+ Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-1)));
+ Assert.AreEqual(14927, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(14927)));
+ Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-3612)));
+ }
+
+ [Test]
+ public void RoundTripZigZag64()
+ {
+ Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(0)));
+ Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(1)));
+ Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-1)));
+ Assert.AreEqual(14927, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(14927)));
+ Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-3612)));
+
+ Assert.AreEqual(856912304801416L,
+ CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(856912304801416L)));
+ Assert.AreEqual(-75123905439571256L,
+ CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-75123905439571256L)));
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs b/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs index 6b42209b..c339cef6 100644 --- a/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs +++ b/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs @@ -1,100 +1,110 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using NUnit.Framework; - -delegate void Action(); - - -namespace Google.ProtocolBuffers.Collections { - [TestFixture] - public class PopsicleListTest { - - [Test] - public void MutatingOperationsOnFrozenList() { - PopsicleList<string> list = new PopsicleList<string>(); - list.MakeReadOnly(); - AssertNotSupported(() => list.Add("")); - AssertNotSupported(() => list.Clear()); - AssertNotSupported(() => list.Insert(0, "")); - AssertNotSupported(() => list.Remove("")); - AssertNotSupported(() => list.RemoveAt(0)); - AssertNotSupported(() => list.Add(new[] {"", ""})); - } - - [Test] - public void NonMutatingOperationsOnFrozenList() { - PopsicleList<string> list = new PopsicleList<string>(); - list.MakeReadOnly(); - Assert.IsFalse(list.Contains("")); - Assert.AreEqual(0, list.Count); - list.CopyTo(new string[5], 0); - list.GetEnumerator(); - Assert.AreEqual(-1, list.IndexOf("")); - Assert.IsTrue(list.IsReadOnly); - } - - [Test] - public void MutatingOperationsOnFluidList() { - PopsicleList<string> list = new PopsicleList<string>(); - list.Add(""); - list.Clear(); - list.Insert(0, ""); - list.Remove(""); - list.Add("x"); // Just to make the next call valid - list.RemoveAt(0); - } - - [Test] - public void NonMutatingOperationsOnFluidList() { - PopsicleList<string> list = new PopsicleList<string>(); - Assert.IsFalse(list.Contains("")); - Assert.AreEqual(0, list.Count); - list.CopyTo(new string[5], 0); - list.GetEnumerator(); - Assert.AreEqual(-1, list.IndexOf("")); - Assert.IsFalse(list.IsReadOnly); - } - - private static void AssertNotSupported(Action action) { - try { - action(); - Assert.Fail("Expected NotSupportedException"); - } catch (NotSupportedException) { - // Expected - } - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System;
+using NUnit.Framework;
+
+internal delegate void Action();
+
+namespace Google.ProtocolBuffers.Collections
+{
+ [TestFixture]
+ public class PopsicleListTest
+ {
+ [Test]
+ public void MutatingOperationsOnFrozenList()
+ {
+ PopsicleList<string> list = new PopsicleList<string>();
+ list.MakeReadOnly();
+ AssertNotSupported(() => list.Add(""));
+ AssertNotSupported(() => list.Clear());
+ AssertNotSupported(() => list.Insert(0, ""));
+ AssertNotSupported(() => list.Remove(""));
+ AssertNotSupported(() => list.RemoveAt(0));
+ AssertNotSupported(() => list.Add(new[] {"", ""}));
+ }
+
+ [Test]
+ public void NonMutatingOperationsOnFrozenList()
+ {
+ PopsicleList<string> list = new PopsicleList<string>();
+ list.MakeReadOnly();
+ Assert.IsFalse(list.Contains(""));
+ Assert.AreEqual(0, list.Count);
+ list.CopyTo(new string[5], 0);
+ list.GetEnumerator();
+ Assert.AreEqual(-1, list.IndexOf(""));
+ Assert.IsTrue(list.IsReadOnly);
+ }
+
+ [Test]
+ public void MutatingOperationsOnFluidList()
+ {
+ PopsicleList<string> list = new PopsicleList<string>();
+ list.Add("");
+ list.Clear();
+ list.Insert(0, "");
+ list.Remove("");
+ list.Add("x"); // Just to make the next call valid
+ list.RemoveAt(0);
+ }
+
+ [Test]
+ public void NonMutatingOperationsOnFluidList()
+ {
+ PopsicleList<string> list = new PopsicleList<string>();
+ Assert.IsFalse(list.Contains(""));
+ Assert.AreEqual(0, list.Count);
+ list.CopyTo(new string[5], 0);
+ list.GetEnumerator();
+ Assert.AreEqual(-1, list.IndexOf(""));
+ Assert.IsFalse(list.IsReadOnly);
+ }
+
+ private static void AssertNotSupported(Action action)
+ {
+ try
+ {
+ action();
+ Assert.Fail("Expected NotSupportedException");
+ }
+ catch (NotSupportedException)
+ {
+ // Expected
+ }
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/Descriptors/MessageDescriptorTest.cs b/src/ProtocolBuffers.Test/Descriptors/MessageDescriptorTest.cs index df3b236a..d536db2d 100644 --- a/src/ProtocolBuffers.Test/Descriptors/MessageDescriptorTest.cs +++ b/src/ProtocolBuffers.Test/Descriptors/MessageDescriptorTest.cs @@ -1,65 +1,72 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using NUnit.Framework; -using Google.ProtocolBuffers.TestProtos; - -namespace Google.ProtocolBuffers.Descriptors { - - [TestFixture] - public class MessageDescriptorTest { - [Test] - public void FindPropertyWithDefaultName() { - Assert.AreSame(OptionsMessage.Descriptor.FindFieldByNumber(OptionsMessage.NormalFieldNumber), - OptionsMessage.Descriptor.FindFieldByPropertyName("Normal")); - } - - [Test] - public void FindPropertyWithAutoModifiedName() { - Assert.AreSame(OptionsMessage.Descriptor.FindFieldByNumber(OptionsMessage.OptionsMessage_FieldNumber), - OptionsMessage.Descriptor.FindFieldByPropertyName("OptionsMessage_")); - } - - [Test] - public void FindPropertyWithCustomizedName() { - Assert.AreSame(OptionsMessage.Descriptor.FindFieldByNumber(OptionsMessage.CustomNameFieldNumber), - OptionsMessage.Descriptor.FindFieldByPropertyName("CustomName")); - } - - [Test] - public void FindPropertyWithInvalidName() { - Assert.IsNull(OptionsMessage.Descriptor.FindFieldByPropertyName("Bogus")); - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using NUnit.Framework;
+using Google.ProtocolBuffers.TestProtos;
+
+namespace Google.ProtocolBuffers.Descriptors
+{
+ [TestFixture]
+ public class MessageDescriptorTest
+ {
+ [Test]
+ public void FindPropertyWithDefaultName()
+ {
+ Assert.AreSame(OptionsMessage.Descriptor.FindFieldByNumber(OptionsMessage.NormalFieldNumber),
+ OptionsMessage.Descriptor.FindFieldByPropertyName("Normal"));
+ }
+
+ [Test]
+ public void FindPropertyWithAutoModifiedName()
+ {
+ Assert.AreSame(OptionsMessage.Descriptor.FindFieldByNumber(OptionsMessage.OptionsMessage_FieldNumber),
+ OptionsMessage.Descriptor.FindFieldByPropertyName("OptionsMessage_"));
+ }
+
+ [Test]
+ public void FindPropertyWithCustomizedName()
+ {
+ Assert.AreSame(OptionsMessage.Descriptor.FindFieldByNumber(OptionsMessage.CustomNameFieldNumber),
+ OptionsMessage.Descriptor.FindFieldByPropertyName("CustomName"));
+ }
+
+ [Test]
+ public void FindPropertyWithInvalidName()
+ {
+ Assert.IsNull(OptionsMessage.Descriptor.FindFieldByPropertyName("Bogus"));
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/DescriptorsTest.cs b/src/ProtocolBuffers.Test/DescriptorsTest.cs index f3c03cd6..671fb5a8 100644 --- a/src/ProtocolBuffers.Test/DescriptorsTest.cs +++ b/src/ProtocolBuffers.Test/DescriptorsTest.cs @@ -1,327 +1,352 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System.Text; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - /// <summary> - /// Tests for descriptors. (Not in its own namespace or broken up into individual classes as the - /// size doesn't warrant it. On the other hand, this makes me feel a bit dirty...) - /// </summary> - [TestFixture] - public class DescriptorsTest { - - [Test] - public void FileDescriptor() { - FileDescriptor file = UnitTestProtoFile.Descriptor; - - Assert.AreEqual("google/protobuf/unittest.proto", file.Name); - Assert.AreEqual("protobuf_unittest", file.Package); - - Assert.AreEqual("UnittestProto", file.Options.JavaOuterClassname); - Assert.AreEqual("google/protobuf/unittest.proto", file.Proto.Name); - -// TODO(jonskeet): Either change to expect 2 dependencies, or don't emit them. -// Assert.AreEqual(2, file.Dependencies.Count); - Assert.AreEqual(UnitTestImportProtoFile.Descriptor, file.Dependencies[1]); - - MessageDescriptor messageType = TestAllTypes.Descriptor; - Assert.AreEqual(messageType, file.MessageTypes[0]); - Assert.AreEqual(messageType, file.FindTypeByName<MessageDescriptor>("TestAllTypes")); - Assert.IsNull(file.FindTypeByName<MessageDescriptor>("NoSuchType")); - Assert.IsNull(file.FindTypeByName<MessageDescriptor>("protobuf_unittest.TestAllTypes")); - for (int i = 0; i < file.MessageTypes.Count; i++) { - Assert.AreEqual(i, file.MessageTypes[i].Index); - } - - Assert.AreEqual(file.EnumTypes[0], file.FindTypeByName<EnumDescriptor>("ForeignEnum")); - Assert.IsNull(file.FindTypeByName<EnumDescriptor>("NoSuchType")); - Assert.IsNull(file.FindTypeByName<EnumDescriptor>("protobuf_unittest.ForeignEnum")); - Assert.AreEqual(1, UnitTestImportProtoFile.Descriptor.EnumTypes.Count); - Assert.AreEqual("ImportEnum", UnitTestImportProtoFile.Descriptor.EnumTypes[0].Name); - for (int i = 0; i < file.EnumTypes.Count; i++) { - Assert.AreEqual(i, file.EnumTypes[i].Index); - }
-
- ServiceDescriptor service = TestGenericService.Descriptor; - Assert.AreEqual(service, UnitTestGenericServices.Descriptor.Services[0]);
- Assert.AreEqual(service, UnitTestGenericServices.Descriptor.FindTypeByName<ServiceDescriptor>("TestGenericService"));
- Assert.IsNull(UnitTestGenericServices.Descriptor.FindTypeByName<ServiceDescriptor>("NoSuchType"));
- Assert.IsNull(UnitTestGenericServices.Descriptor.FindTypeByName<ServiceDescriptor>("protobuf_unittest.TestGenericService")); - Assert.AreEqual(0, UnitTestImportProtoFile.Descriptor.Services.Count); - for (int i = 0; i < file.Services.Count; i++) { - Assert.AreEqual(i, file.Services[i].Index); - } - - FieldDescriptor extension = UnitTestProtoFile.OptionalInt32Extension.Descriptor; - Assert.AreEqual(extension, file.Extensions[0]); - Assert.AreEqual(extension, file.FindTypeByName<FieldDescriptor>("optional_int32_extension")); - Assert.IsNull(file.FindTypeByName<FieldDescriptor>("no_such_ext")); - Assert.IsNull(file.FindTypeByName<FieldDescriptor>("protobuf_unittest.optional_int32_extension")); - Assert.AreEqual(0, UnitTestImportProtoFile.Descriptor.Extensions.Count); - for (int i = 0; i < file.Extensions.Count; i++) { - Assert.AreEqual(i, file.Extensions[i].Index); - } - } - - [Test] - public void MessageDescriptor() { - MessageDescriptor messageType = TestAllTypes.Descriptor; - MessageDescriptor nestedType = TestAllTypes.Types.NestedMessage.Descriptor; - - Assert.AreEqual("TestAllTypes", messageType.Name); - Assert.AreEqual("protobuf_unittest.TestAllTypes", messageType.FullName); - Assert.AreEqual(UnitTestProtoFile.Descriptor, messageType.File); - Assert.IsNull(messageType.ContainingType); - Assert.AreEqual(DescriptorProtos.MessageOptions.DefaultInstance, messageType.Options); - Assert.AreEqual("TestAllTypes", messageType.Proto.Name); - - Assert.AreEqual("NestedMessage", nestedType.Name); - Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedMessage", nestedType.FullName); - Assert.AreEqual(UnitTestProtoFile.Descriptor, nestedType.File); - Assert.AreEqual(messageType, nestedType.ContainingType); - - FieldDescriptor field = messageType.Fields[0]; - Assert.AreEqual("optional_int32", field.Name); - Assert.AreEqual(field, messageType.FindDescriptor<FieldDescriptor>("optional_int32")); - Assert.IsNull(messageType.FindDescriptor<FieldDescriptor>("no_such_field")); - Assert.AreEqual(field, messageType.FindFieldByNumber(1)); - Assert.IsNull(messageType.FindFieldByNumber(571283)); - for (int i = 0; i < messageType.Fields.Count; i++) { - Assert.AreEqual(i, messageType.Fields[i].Index); - } - - Assert.AreEqual(nestedType, messageType.NestedTypes[0]); - Assert.AreEqual(nestedType, messageType.FindDescriptor<MessageDescriptor>("NestedMessage")); - Assert.IsNull(messageType.FindDescriptor<MessageDescriptor>("NoSuchType")); - for (int i = 0; i < messageType.NestedTypes.Count; i++) { - Assert.AreEqual(i, messageType.NestedTypes[i].Index); - } - - Assert.AreEqual(messageType.EnumTypes[0], messageType.FindDescriptor<EnumDescriptor>("NestedEnum")); - Assert.IsNull(messageType.FindDescriptor<EnumDescriptor>("NoSuchType")); - for (int i = 0; i < messageType.EnumTypes.Count; i++) { - Assert.AreEqual(i, messageType.EnumTypes[i].Index); - } - } - - [Test] - public void FieldDescriptor() { - MessageDescriptor messageType = TestAllTypes.Descriptor; - FieldDescriptor primitiveField = messageType.FindDescriptor<FieldDescriptor>("optional_int32"); - FieldDescriptor enumField = messageType.FindDescriptor<FieldDescriptor>("optional_nested_enum"); - FieldDescriptor messageField = messageType.FindDescriptor<FieldDescriptor>("optional_foreign_message"); - FieldDescriptor cordField = messageType.FindDescriptor<FieldDescriptor>("optional_cord"); - FieldDescriptor extension = UnitTestProtoFile.OptionalInt32Extension.Descriptor; - FieldDescriptor nestedExtension = TestRequired.Single.Descriptor; - - Assert.AreEqual("optional_int32", primitiveField.Name); - Assert.AreEqual("protobuf_unittest.TestAllTypes.optional_int32", - primitiveField.FullName); - Assert.AreEqual(1, primitiveField.FieldNumber); - Assert.AreEqual(messageType, primitiveField.ContainingType); - Assert.AreEqual(UnitTestProtoFile.Descriptor, primitiveField.File); - Assert.AreEqual(FieldType.Int32, primitiveField.FieldType); - Assert.AreEqual(MappedType.Int32, primitiveField.MappedType); - Assert.AreEqual(DescriptorProtos.FieldOptions.DefaultInstance, primitiveField.Options); - Assert.IsFalse(primitiveField.IsExtension); - Assert.AreEqual("optional_int32", primitiveField.Proto.Name); - - Assert.AreEqual("optional_nested_enum", enumField.Name); - Assert.AreEqual(FieldType.Enum, enumField.FieldType); - Assert.AreEqual(MappedType.Enum, enumField.MappedType); - // Assert.AreEqual(TestAllTypes.Types.NestedEnum.Descriptor, enumField.EnumType); - - Assert.AreEqual("optional_foreign_message", messageField.Name); - Assert.AreEqual(FieldType.Message, messageField.FieldType); - Assert.AreEqual(MappedType.Message, messageField.MappedType); - Assert.AreEqual(ForeignMessage.Descriptor, messageField.MessageType); - - Assert.AreEqual("optional_cord", cordField.Name); - Assert.AreEqual(FieldType.String, cordField.FieldType); - Assert.AreEqual(MappedType.String, cordField.MappedType); - Assert.AreEqual(DescriptorProtos.FieldOptions.Types.CType.CORD, cordField.Options.Ctype); - - Assert.AreEqual("optional_int32_extension", extension.Name); - Assert.AreEqual("protobuf_unittest.optional_int32_extension", extension.FullName); - Assert.AreEqual(1, extension.FieldNumber); - Assert.AreEqual(TestAllExtensions.Descriptor, extension.ContainingType); - Assert.AreEqual(UnitTestProtoFile.Descriptor, extension.File); - Assert.AreEqual(FieldType.Int32, extension.FieldType); - Assert.AreEqual(MappedType.Int32, extension.MappedType); - Assert.AreEqual(DescriptorProtos.FieldOptions.DefaultInstance, - extension.Options); - Assert.IsTrue(extension.IsExtension); - Assert.AreEqual(null, extension.ExtensionScope); - Assert.AreEqual("optional_int32_extension", extension.Proto.Name); - - Assert.AreEqual("single", nestedExtension.Name); - Assert.AreEqual("protobuf_unittest.TestRequired.single", - nestedExtension.FullName); - Assert.AreEqual(TestRequired.Descriptor, - nestedExtension.ExtensionScope); - } - - [Test] - public void FieldDescriptorLabel() { - FieldDescriptor requiredField = - TestRequired.Descriptor.FindDescriptor<FieldDescriptor>("a"); - FieldDescriptor optionalField = - TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("optional_int32"); - FieldDescriptor repeatedField = - TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_int32"); - - Assert.IsTrue(requiredField.IsRequired); - Assert.IsFalse(requiredField.IsRepeated); - Assert.IsFalse(optionalField.IsRequired); - Assert.IsFalse(optionalField.IsRepeated); - Assert.IsFalse(repeatedField.IsRequired); - Assert.IsTrue(repeatedField.IsRepeated); - } - - [Test] - public void FieldDescriptorDefault() { - MessageDescriptor d = TestAllTypes.Descriptor; - Assert.IsFalse(d.FindDescriptor<FieldDescriptor>("optional_int32").HasDefaultValue); - Assert.AreEqual(0, d.FindDescriptor<FieldDescriptor>("optional_int32").DefaultValue); - Assert.IsTrue(d.FindDescriptor<FieldDescriptor>("default_int32").HasDefaultValue); - Assert.AreEqual(41, d.FindDescriptor<FieldDescriptor>("default_int32").DefaultValue); - - d = TestExtremeDefaultValues.Descriptor; - Assert.AreEqual(ByteString.CopyFrom("\u0000\u0001\u0007\b\f\n\r\t\u000b\\\'\"\u00fe", Encoding.GetEncoding(28591)), - d.FindDescriptor<FieldDescriptor>("escaped_bytes").DefaultValue); - Assert.AreEqual(uint.MaxValue, d.FindDescriptor<FieldDescriptor>("large_uint32").DefaultValue); - Assert.AreEqual(ulong.MaxValue, d.FindDescriptor<FieldDescriptor>("large_uint64").DefaultValue); - } - - [Test] - public void EnumDescriptor() { - // Note: this test is a bit different to the Java version because there's no static way of getting to the descriptor - EnumDescriptor enumType = UnitTestProtoFile.Descriptor.FindTypeByName<EnumDescriptor>("ForeignEnum"); - EnumDescriptor nestedType = TestAllTypes.Descriptor.FindDescriptor<EnumDescriptor>("NestedEnum"); - - Assert.AreEqual("ForeignEnum", enumType.Name); - Assert.AreEqual("protobuf_unittest.ForeignEnum", enumType.FullName); - Assert.AreEqual(UnitTestProtoFile.Descriptor, enumType.File); - Assert.IsNull(enumType.ContainingType); - Assert.AreEqual(DescriptorProtos.EnumOptions.DefaultInstance, - enumType.Options); - - Assert.AreEqual("NestedEnum", nestedType.Name); - Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedEnum", - nestedType.FullName); - Assert.AreEqual(UnitTestProtoFile.Descriptor, nestedType.File); - Assert.AreEqual(TestAllTypes.Descriptor, nestedType.ContainingType); - - EnumValueDescriptor value = enumType.FindValueByName("FOREIGN_FOO"); - Assert.AreEqual(value, enumType.Values[0]); - Assert.AreEqual("FOREIGN_FOO", value.Name); - Assert.AreEqual(4, value.Number); - Assert.AreEqual((int) ForeignEnum.FOREIGN_FOO, value.Number); - Assert.AreEqual(value, enumType.FindValueByNumber(4)); - Assert.IsNull(enumType.FindValueByName("NO_SUCH_VALUE")); - for (int i = 0; i < enumType.Values.Count; i++) { - Assert.AreEqual(i, enumType.Values[i].Index); - } - } - - [Test] - public void ServiceDescriptor() { - ServiceDescriptor service = TestGenericService.Descriptor;
-
- Assert.AreEqual("TestGenericService", service.Name);
- Assert.AreEqual("protobuf_unittest.TestGenericService", service.FullName);
- Assert.AreEqual(UnitTestGenericServices.Descriptor, service.File); - - Assert.AreEqual(2, service.Methods.Count); - - MethodDescriptor fooMethod = service.Methods[0]; - Assert.AreEqual("Foo", fooMethod.Name); - Assert.AreEqual(FooRequest.Descriptor, fooMethod.InputType); - Assert.AreEqual(FooResponse.Descriptor, fooMethod.OutputType); - Assert.AreEqual(fooMethod, service.FindMethodByName("Foo")); - - MethodDescriptor barMethod = service.Methods[1]; - Assert.AreEqual("Bar", barMethod.Name); - Assert.AreEqual(BarRequest.Descriptor, barMethod.InputType); - Assert.AreEqual(BarResponse.Descriptor, barMethod.OutputType); - Assert.AreEqual(barMethod, service.FindMethodByName("Bar")); - - Assert.IsNull(service.FindMethodByName("NoSuchMethod")); - - for (int i = 0; i < service.Methods.Count; i++) { - Assert.AreEqual(i, service.Methods[i].Index); - } - } - - [Test] - public void CustomOptions() { - MessageDescriptor descriptor = TestMessageWithCustomOptions.Descriptor; - Assert.IsTrue(descriptor.Options.HasExtension(UnitTestCustomOptionsProtoFile.MessageOpt1)); - Assert.AreEqual(-56, descriptor.Options.GetExtension(UnitTestCustomOptionsProtoFile.MessageOpt1)); - - - FieldDescriptor field = descriptor.FindFieldByName("field1"); - Assert.IsNotNull(field); - - Assert.IsTrue(field.Options.HasExtension(UnitTestCustomOptionsProtoFile.FieldOpt1)); - Assert.AreEqual(8765432109L, field.Options.GetExtension(UnitTestCustomOptionsProtoFile.FieldOpt1)); - - // TODO: Write out enum descriptors - /* - EnumDescriptor enumType = TestMessageWithCustomOptions.Types. - UnittestCustomOptions.TestMessageWithCustomOptions.AnEnum.getDescriptor(); - - Assert.IsTrue( - enumType.getOptions().hasExtension(UnittestCustomOptions.enumOpt1)); - Assert.AreEqual(Integer.valueOf(-789), - enumType.getOptions().getExtension(UnittestCustomOptions.enumOpt1)); +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System.Text;
+using Google.ProtocolBuffers.Descriptors;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ /// <summary>
+ /// Tests for descriptors. (Not in its own namespace or broken up into individual classes as the
+ /// size doesn't warrant it. On the other hand, this makes me feel a bit dirty...)
+ /// </summary>
+ [TestFixture]
+ public class DescriptorsTest
+ {
+ [Test]
+ public void FileDescriptor()
+ {
+ FileDescriptor file = UnitTestProtoFile.Descriptor;
+
+ Assert.AreEqual("google/protobuf/unittest.proto", file.Name);
+ Assert.AreEqual("protobuf_unittest", file.Package);
+
+ Assert.AreEqual("UnittestProto", file.Options.JavaOuterClassname);
+ Assert.AreEqual("google/protobuf/unittest.proto", file.Proto.Name);
+
+// TODO(jonskeet): Either change to expect 2 dependencies, or don't emit them.
+// Assert.AreEqual(2, file.Dependencies.Count);
+ Assert.AreEqual(UnitTestImportProtoFile.Descriptor, file.Dependencies[1]);
+
+ MessageDescriptor messageType = TestAllTypes.Descriptor;
+ Assert.AreEqual(messageType, file.MessageTypes[0]);
+ Assert.AreEqual(messageType, file.FindTypeByName<MessageDescriptor>("TestAllTypes"));
+ Assert.IsNull(file.FindTypeByName<MessageDescriptor>("NoSuchType"));
+ Assert.IsNull(file.FindTypeByName<MessageDescriptor>("protobuf_unittest.TestAllTypes"));
+ for (int i = 0; i < file.MessageTypes.Count; i++)
+ {
+ Assert.AreEqual(i, file.MessageTypes[i].Index);
+ }
+
+ Assert.AreEqual(file.EnumTypes[0], file.FindTypeByName<EnumDescriptor>("ForeignEnum"));
+ Assert.IsNull(file.FindTypeByName<EnumDescriptor>("NoSuchType"));
+ Assert.IsNull(file.FindTypeByName<EnumDescriptor>("protobuf_unittest.ForeignEnum"));
+ Assert.AreEqual(1, UnitTestImportProtoFile.Descriptor.EnumTypes.Count);
+ Assert.AreEqual("ImportEnum", UnitTestImportProtoFile.Descriptor.EnumTypes[0].Name);
+ for (int i = 0; i < file.EnumTypes.Count; i++)
+ {
+ Assert.AreEqual(i, file.EnumTypes[i].Index);
+ }
+
+ ServiceDescriptor service = TestGenericService.Descriptor;
+ Assert.AreEqual(service, UnitTestGenericServices.Descriptor.Services[0]);
+ Assert.AreEqual(service,
+ UnitTestGenericServices.Descriptor.FindTypeByName<ServiceDescriptor>("TestGenericService"));
+ Assert.IsNull(UnitTestGenericServices.Descriptor.FindTypeByName<ServiceDescriptor>("NoSuchType"));
+ Assert.IsNull(
+ UnitTestGenericServices.Descriptor.FindTypeByName<ServiceDescriptor>(
+ "protobuf_unittest.TestGenericService"));
+ Assert.AreEqual(0, UnitTestImportProtoFile.Descriptor.Services.Count);
+ for (int i = 0; i < file.Services.Count; i++)
+ {
+ Assert.AreEqual(i, file.Services[i].Index);
+ }
+
+ FieldDescriptor extension = UnitTestProtoFile.OptionalInt32Extension.Descriptor;
+ Assert.AreEqual(extension, file.Extensions[0]);
+ Assert.AreEqual(extension, file.FindTypeByName<FieldDescriptor>("optional_int32_extension"));
+ Assert.IsNull(file.FindTypeByName<FieldDescriptor>("no_such_ext"));
+ Assert.IsNull(file.FindTypeByName<FieldDescriptor>("protobuf_unittest.optional_int32_extension"));
+ Assert.AreEqual(0, UnitTestImportProtoFile.Descriptor.Extensions.Count);
+ for (int i = 0; i < file.Extensions.Count; i++)
+ {
+ Assert.AreEqual(i, file.Extensions[i].Index);
+ }
+ }
+
+ [Test]
+ public void MessageDescriptor()
+ {
+ MessageDescriptor messageType = TestAllTypes.Descriptor;
+ MessageDescriptor nestedType = TestAllTypes.Types.NestedMessage.Descriptor;
+
+ Assert.AreEqual("TestAllTypes", messageType.Name);
+ Assert.AreEqual("protobuf_unittest.TestAllTypes", messageType.FullName);
+ Assert.AreEqual(UnitTestProtoFile.Descriptor, messageType.File);
+ Assert.IsNull(messageType.ContainingType);
+ Assert.AreEqual(DescriptorProtos.MessageOptions.DefaultInstance, messageType.Options);
+ Assert.AreEqual("TestAllTypes", messageType.Proto.Name);
+
+ Assert.AreEqual("NestedMessage", nestedType.Name);
+ Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedMessage", nestedType.FullName);
+ Assert.AreEqual(UnitTestProtoFile.Descriptor, nestedType.File);
+ Assert.AreEqual(messageType, nestedType.ContainingType);
+
+ FieldDescriptor field = messageType.Fields[0];
+ Assert.AreEqual("optional_int32", field.Name);
+ Assert.AreEqual(field, messageType.FindDescriptor<FieldDescriptor>("optional_int32"));
+ Assert.IsNull(messageType.FindDescriptor<FieldDescriptor>("no_such_field"));
+ Assert.AreEqual(field, messageType.FindFieldByNumber(1));
+ Assert.IsNull(messageType.FindFieldByNumber(571283));
+ for (int i = 0; i < messageType.Fields.Count; i++)
+ {
+ Assert.AreEqual(i, messageType.Fields[i].Index);
+ }
+
+ Assert.AreEqual(nestedType, messageType.NestedTypes[0]);
+ Assert.AreEqual(nestedType, messageType.FindDescriptor<MessageDescriptor>("NestedMessage"));
+ Assert.IsNull(messageType.FindDescriptor<MessageDescriptor>("NoSuchType"));
+ for (int i = 0; i < messageType.NestedTypes.Count; i++)
+ {
+ Assert.AreEqual(i, messageType.NestedTypes[i].Index);
+ }
+
+ Assert.AreEqual(messageType.EnumTypes[0], messageType.FindDescriptor<EnumDescriptor>("NestedEnum"));
+ Assert.IsNull(messageType.FindDescriptor<EnumDescriptor>("NoSuchType"));
+ for (int i = 0; i < messageType.EnumTypes.Count; i++)
+ {
+ Assert.AreEqual(i, messageType.EnumTypes[i].Index);
+ }
+ }
+
+ [Test]
+ public void FieldDescriptor()
+ {
+ MessageDescriptor messageType = TestAllTypes.Descriptor;
+ FieldDescriptor primitiveField = messageType.FindDescriptor<FieldDescriptor>("optional_int32");
+ FieldDescriptor enumField = messageType.FindDescriptor<FieldDescriptor>("optional_nested_enum");
+ FieldDescriptor messageField = messageType.FindDescriptor<FieldDescriptor>("optional_foreign_message");
+ FieldDescriptor cordField = messageType.FindDescriptor<FieldDescriptor>("optional_cord");
+ FieldDescriptor extension = UnitTestProtoFile.OptionalInt32Extension.Descriptor;
+ FieldDescriptor nestedExtension = TestRequired.Single.Descriptor;
+
+ Assert.AreEqual("optional_int32", primitiveField.Name);
+ Assert.AreEqual("protobuf_unittest.TestAllTypes.optional_int32",
+ primitiveField.FullName);
+ Assert.AreEqual(1, primitiveField.FieldNumber);
+ Assert.AreEqual(messageType, primitiveField.ContainingType);
+ Assert.AreEqual(UnitTestProtoFile.Descriptor, primitiveField.File);
+ Assert.AreEqual(FieldType.Int32, primitiveField.FieldType);
+ Assert.AreEqual(MappedType.Int32, primitiveField.MappedType);
+ Assert.AreEqual(DescriptorProtos.FieldOptions.DefaultInstance, primitiveField.Options);
+ Assert.IsFalse(primitiveField.IsExtension);
+ Assert.AreEqual("optional_int32", primitiveField.Proto.Name);
+
+ Assert.AreEqual("optional_nested_enum", enumField.Name);
+ Assert.AreEqual(FieldType.Enum, enumField.FieldType);
+ Assert.AreEqual(MappedType.Enum, enumField.MappedType);
+ // Assert.AreEqual(TestAllTypes.Types.NestedEnum.Descriptor, enumField.EnumType);
+
+ Assert.AreEqual("optional_foreign_message", messageField.Name);
+ Assert.AreEqual(FieldType.Message, messageField.FieldType);
+ Assert.AreEqual(MappedType.Message, messageField.MappedType);
+ Assert.AreEqual(ForeignMessage.Descriptor, messageField.MessageType);
+
+ Assert.AreEqual("optional_cord", cordField.Name);
+ Assert.AreEqual(FieldType.String, cordField.FieldType);
+ Assert.AreEqual(MappedType.String, cordField.MappedType);
+ Assert.AreEqual(DescriptorProtos.FieldOptions.Types.CType.CORD, cordField.Options.Ctype);
+
+ Assert.AreEqual("optional_int32_extension", extension.Name);
+ Assert.AreEqual("protobuf_unittest.optional_int32_extension", extension.FullName);
+ Assert.AreEqual(1, extension.FieldNumber);
+ Assert.AreEqual(TestAllExtensions.Descriptor, extension.ContainingType);
+ Assert.AreEqual(UnitTestProtoFile.Descriptor, extension.File);
+ Assert.AreEqual(FieldType.Int32, extension.FieldType);
+ Assert.AreEqual(MappedType.Int32, extension.MappedType);
+ Assert.AreEqual(DescriptorProtos.FieldOptions.DefaultInstance,
+ extension.Options);
+ Assert.IsTrue(extension.IsExtension);
+ Assert.AreEqual(null, extension.ExtensionScope);
+ Assert.AreEqual("optional_int32_extension", extension.Proto.Name);
+
+ Assert.AreEqual("single", nestedExtension.Name);
+ Assert.AreEqual("protobuf_unittest.TestRequired.single",
+ nestedExtension.FullName);
+ Assert.AreEqual(TestRequired.Descriptor,
+ nestedExtension.ExtensionScope);
+ }
+
+ [Test]
+ public void FieldDescriptorLabel()
+ {
+ FieldDescriptor requiredField =
+ TestRequired.Descriptor.FindDescriptor<FieldDescriptor>("a");
+ FieldDescriptor optionalField =
+ TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("optional_int32");
+ FieldDescriptor repeatedField =
+ TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_int32");
+
+ Assert.IsTrue(requiredField.IsRequired);
+ Assert.IsFalse(requiredField.IsRepeated);
+ Assert.IsFalse(optionalField.IsRequired);
+ Assert.IsFalse(optionalField.IsRepeated);
+ Assert.IsFalse(repeatedField.IsRequired);
+ Assert.IsTrue(repeatedField.IsRepeated);
+ }
+
+ [Test]
+ public void FieldDescriptorDefault()
+ {
+ MessageDescriptor d = TestAllTypes.Descriptor;
+ Assert.IsFalse(d.FindDescriptor<FieldDescriptor>("optional_int32").HasDefaultValue);
+ Assert.AreEqual(0, d.FindDescriptor<FieldDescriptor>("optional_int32").DefaultValue);
+ Assert.IsTrue(d.FindDescriptor<FieldDescriptor>("default_int32").HasDefaultValue);
+ Assert.AreEqual(41, d.FindDescriptor<FieldDescriptor>("default_int32").DefaultValue);
+
+ d = TestExtremeDefaultValues.Descriptor;
+ Assert.AreEqual(
+ ByteString.CopyFrom("\u0000\u0001\u0007\b\f\n\r\t\u000b\\\'\"\u00fe", Encoding.GetEncoding(28591)),
+ d.FindDescriptor<FieldDescriptor>("escaped_bytes").DefaultValue);
+ Assert.AreEqual(uint.MaxValue, d.FindDescriptor<FieldDescriptor>("large_uint32").DefaultValue);
+ Assert.AreEqual(ulong.MaxValue, d.FindDescriptor<FieldDescriptor>("large_uint64").DefaultValue);
+ }
+
+ [Test]
+ public void EnumDescriptor()
+ {
+ // Note: this test is a bit different to the Java version because there's no static way of getting to the descriptor
+ EnumDescriptor enumType = UnitTestProtoFile.Descriptor.FindTypeByName<EnumDescriptor>("ForeignEnum");
+ EnumDescriptor nestedType = TestAllTypes.Descriptor.FindDescriptor<EnumDescriptor>("NestedEnum");
+
+ Assert.AreEqual("ForeignEnum", enumType.Name);
+ Assert.AreEqual("protobuf_unittest.ForeignEnum", enumType.FullName);
+ Assert.AreEqual(UnitTestProtoFile.Descriptor, enumType.File);
+ Assert.IsNull(enumType.ContainingType);
+ Assert.AreEqual(DescriptorProtos.EnumOptions.DefaultInstance,
+ enumType.Options);
+
+ Assert.AreEqual("NestedEnum", nestedType.Name);
+ Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedEnum",
+ nestedType.FullName);
+ Assert.AreEqual(UnitTestProtoFile.Descriptor, nestedType.File);
+ Assert.AreEqual(TestAllTypes.Descriptor, nestedType.ContainingType);
+
+ EnumValueDescriptor value = enumType.FindValueByName("FOREIGN_FOO");
+ Assert.AreEqual(value, enumType.Values[0]);
+ Assert.AreEqual("FOREIGN_FOO", value.Name);
+ Assert.AreEqual(4, value.Number);
+ Assert.AreEqual((int) ForeignEnum.FOREIGN_FOO, value.Number);
+ Assert.AreEqual(value, enumType.FindValueByNumber(4));
+ Assert.IsNull(enumType.FindValueByName("NO_SUCH_VALUE"));
+ for (int i = 0; i < enumType.Values.Count; i++)
+ {
+ Assert.AreEqual(i, enumType.Values[i].Index);
+ }
+ }
+
+ [Test]
+ public void ServiceDescriptor()
+ {
+ ServiceDescriptor service = TestGenericService.Descriptor;
+
+ Assert.AreEqual("TestGenericService", service.Name);
+ Assert.AreEqual("protobuf_unittest.TestGenericService", service.FullName);
+ Assert.AreEqual(UnitTestGenericServices.Descriptor, service.File);
+
+ Assert.AreEqual(2, service.Methods.Count);
+
+ MethodDescriptor fooMethod = service.Methods[0];
+ Assert.AreEqual("Foo", fooMethod.Name);
+ Assert.AreEqual(FooRequest.Descriptor, fooMethod.InputType);
+ Assert.AreEqual(FooResponse.Descriptor, fooMethod.OutputType);
+ Assert.AreEqual(fooMethod, service.FindMethodByName("Foo"));
+
+ MethodDescriptor barMethod = service.Methods[1];
+ Assert.AreEqual("Bar", barMethod.Name);
+ Assert.AreEqual(BarRequest.Descriptor, barMethod.InputType);
+ Assert.AreEqual(BarResponse.Descriptor, barMethod.OutputType);
+ Assert.AreEqual(barMethod, service.FindMethodByName("Bar"));
+
+ Assert.IsNull(service.FindMethodByName("NoSuchMethod"));
+
+ for (int i = 0; i < service.Methods.Count; i++)
+ {
+ Assert.AreEqual(i, service.Methods[i].Index);
+ }
+ }
+
+ [Test]
+ public void CustomOptions()
+ {
+ MessageDescriptor descriptor = TestMessageWithCustomOptions.Descriptor;
+ Assert.IsTrue(descriptor.Options.HasExtension(UnitTestCustomOptionsProtoFile.MessageOpt1));
+ Assert.AreEqual(-56, descriptor.Options.GetExtension(UnitTestCustomOptionsProtoFile.MessageOpt1));
+
+
+ FieldDescriptor field = descriptor.FindFieldByName("field1");
+ Assert.IsNotNull(field);
+
+ Assert.IsTrue(field.Options.HasExtension(UnitTestCustomOptionsProtoFile.FieldOpt1));
+ Assert.AreEqual(8765432109L, field.Options.GetExtension(UnitTestCustomOptionsProtoFile.FieldOpt1));
+
+ // TODO: Write out enum descriptors
+ /*
+ EnumDescriptor enumType = TestMessageWithCustomOptions.Types.
+ UnittestCustomOptions.TestMessageWithCustomOptions.AnEnum.getDescriptor();
+
+ Assert.IsTrue(
+ enumType.getOptions().hasExtension(UnittestCustomOptions.enumOpt1));
+ Assert.AreEqual(Integer.valueOf(-789),
+ enumType.getOptions().getExtension(UnittestCustomOptions.enumOpt1));
*/
- ServiceDescriptor service = TestGenericServiceWithCustomOptions.Descriptor; - - Assert.IsTrue(service.Options.HasExtension(UnitTestCustomOptionsProtoFile.ServiceOpt1)); - Assert.AreEqual(-9876543210L, service.Options.GetExtension(UnitTestCustomOptionsProtoFile.ServiceOpt1)); - - MethodDescriptor method = service.FindMethodByName("Foo"); - Assert.IsNotNull(method); - - Assert.IsTrue(method.Options.HasExtension(UnitTestCustomOptionsProtoFile.MethodOpt1)); - Assert.AreEqual(MethodOpt1.METHODOPT1_VAL2, method.Options.GetExtension(UnitTestCustomOptionsProtoFile.MethodOpt1)); - } - } -} + ServiceDescriptor service = TestGenericServiceWithCustomOptions.Descriptor;
+
+ Assert.IsTrue(service.Options.HasExtension(UnitTestCustomOptionsProtoFile.ServiceOpt1));
+ Assert.AreEqual(-9876543210L, service.Options.GetExtension(UnitTestCustomOptionsProtoFile.ServiceOpt1));
+
+ MethodDescriptor method = service.FindMethodByName("Foo");
+ Assert.IsNotNull(method);
+
+ Assert.IsTrue(method.Options.HasExtension(UnitTestCustomOptionsProtoFile.MethodOpt1));
+ Assert.AreEqual(MethodOpt1.METHODOPT1_VAL2,
+ method.Options.GetExtension(UnitTestCustomOptionsProtoFile.MethodOpt1));
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/DynamicMessageTest.cs b/src/ProtocolBuffers.Test/DynamicMessageTest.cs index e2971692..b6c8178a 100644 --- a/src/ProtocolBuffers.Test/DynamicMessageTest.cs +++ b/src/ProtocolBuffers.Test/DynamicMessageTest.cs @@ -1,215 +1,237 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Collections.Generic; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class DynamicMessageTest { - - private ReflectionTester reflectionTester; - private ReflectionTester extensionsReflectionTester; - private ReflectionTester packedReflectionTester; - - [SetUp] - public void SetUp() { - reflectionTester = ReflectionTester.CreateTestAllTypesInstance(); - extensionsReflectionTester = ReflectionTester.CreateTestAllExtensionsInstance(); - packedReflectionTester = ReflectionTester.CreateTestPackedTypesInstance(); - } - - [Test] - public void DynamicMessageAccessors() { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - reflectionTester.AssertAllFieldsSetViaReflection(message); - } - - [Test] - public void DoubleBuildError() { - DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - builder.Build(); - try { - builder.Build(); - Assert.Fail("Should have thrown exception."); - } catch (InvalidOperationException) { - // Success. - } - } - - [Test] - public void DynamicMessageSettersRejectNull() { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.AssertReflectionSettersRejectNull(builder); - } - - [Test] - public void DynamicMessageExtensionAccessors() { - // We don't need to extensively test DynamicMessage's handling of - // extensions because, frankly, it doesn't do anything special with them. - // It treats them just like any other fields. - IBuilder builder = DynamicMessage.CreateBuilder(TestAllExtensions.Descriptor); - extensionsReflectionTester.SetAllFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - extensionsReflectionTester.AssertAllFieldsSetViaReflection(message); - } - - [Test] - public void DynamicMessageExtensionSettersRejectNull() { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllExtensions.Descriptor); - extensionsReflectionTester.AssertReflectionSettersRejectNull(builder); - } - - [Test] - public void DynamicMessageRepeatedSetters() { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(builder); - reflectionTester.ModifyRepeatedFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - reflectionTester.AssertRepeatedFieldsModifiedViaReflection(message); - } - - [Test] - public void DynamicMessageRepeatedSettersRejectNull() { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.AssertReflectionRepeatedSettersRejectNull(builder); - } - - [Test] - public void DynamicMessageDefaults() { - reflectionTester.AssertClearViaReflection(DynamicMessage.GetDefaultInstance(TestAllTypes.Descriptor)); - reflectionTester.AssertClearViaReflection(DynamicMessage.CreateBuilder(TestAllTypes.Descriptor).Build()); - } - - [Test] - public void DynamicMessageSerializedSize() { - TestAllTypes message = TestUtil.GetAllSet(); - - IBuilder dynamicBuilder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(dynamicBuilder); - IMessage dynamicMessage = dynamicBuilder.WeakBuild(); - - Assert.AreEqual(message.SerializedSize, dynamicMessage.SerializedSize); - } - - [Test] - public void DynamicMessageSerialization() { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - - ByteString rawBytes = message.ToByteString(); - TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes); - - TestUtil.AssertAllFieldsSet(message2); - - // In fact, the serialized forms should be exactly the same, byte-for-byte. - Assert.AreEqual(TestUtil.GetAllSet().ToByteString(), rawBytes); - } - - [Test] - public void DynamicMessageParsing() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - - ByteString rawBytes = message.ToByteString(); - - IMessage message2 = DynamicMessage.ParseFrom(TestAllTypes.Descriptor, rawBytes); - reflectionTester.AssertAllFieldsSetViaReflection(message2); - } - - [Test] - public void DynamicMessagePackedSerialization() { - IBuilder builder = DynamicMessage.CreateBuilder(TestPackedTypes.Descriptor); - packedReflectionTester.SetPackedFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - - ByteString rawBytes = message.ToByteString(); - TestPackedTypes message2 = TestPackedTypes.ParseFrom(rawBytes); - - TestUtil.AssertPackedFieldsSet(message2); - - // In fact, the serialized forms should be exactly the same, byte-for-byte. - Assert.AreEqual(TestUtil.GetPackedSet().ToByteString(), rawBytes); - } - - [Test] - public void testDynamicMessagePackedParsing() { - TestPackedTypes.Builder builder = TestPackedTypes.CreateBuilder(); - TestUtil.SetPackedFields(builder); - TestPackedTypes message = builder.Build(); - - ByteString rawBytes = message.ToByteString(); - - IMessage message2 = DynamicMessage.ParseFrom(TestPackedTypes.Descriptor, rawBytes); - packedReflectionTester.AssertPackedFieldsSetViaReflection(message2); - } - - [Test] - public void DynamicMessageCopy() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - - DynamicMessage copy = DynamicMessage.CreateBuilder(message).Build(); - reflectionTester.AssertAllFieldsSetViaReflection(copy); - } - - [Test] - public void ToBuilder() { - DynamicMessage.Builder builder = - DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(builder); - int unknownFieldNum = 9; - ulong unknownFieldVal = 90; - builder.SetUnknownFields(UnknownFieldSet.CreateBuilder() - .AddField(unknownFieldNum, - UnknownField.CreateBuilder().AddVarint(unknownFieldVal).Build()) - .Build()); - DynamicMessage message = builder.Build(); - - DynamicMessage derived = message.ToBuilder().Build(); - reflectionTester.AssertAllFieldsSetViaReflection(derived); - - IList<ulong> values = derived.UnknownFields.FieldDictionary[unknownFieldNum].VarintList; - Assert.AreEqual(1, values.Count); - Assert.AreEqual(unknownFieldVal, values[0]); - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System;
+using System.Collections.Generic;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class DynamicMessageTest
+ {
+ private ReflectionTester reflectionTester;
+ private ReflectionTester extensionsReflectionTester;
+ private ReflectionTester packedReflectionTester;
+
+ [SetUp]
+ public void SetUp()
+ {
+ reflectionTester = ReflectionTester.CreateTestAllTypesInstance();
+ extensionsReflectionTester = ReflectionTester.CreateTestAllExtensionsInstance();
+ packedReflectionTester = ReflectionTester.CreateTestPackedTypesInstance();
+ }
+
+ [Test]
+ public void DynamicMessageAccessors()
+ {
+ IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
+ reflectionTester.SetAllFieldsViaReflection(builder);
+ IMessage message = builder.WeakBuild();
+ reflectionTester.AssertAllFieldsSetViaReflection(message);
+ }
+
+ [Test]
+ public void DoubleBuildError()
+ {
+ DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
+ builder.Build();
+ try
+ {
+ builder.Build();
+ Assert.Fail("Should have thrown exception.");
+ }
+ catch (InvalidOperationException)
+ {
+ // Success.
+ }
+ }
+
+ [Test]
+ public void DynamicMessageSettersRejectNull()
+ {
+ IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
+ reflectionTester.AssertReflectionSettersRejectNull(builder);
+ }
+
+ [Test]
+ public void DynamicMessageExtensionAccessors()
+ {
+ // We don't need to extensively test DynamicMessage's handling of
+ // extensions because, frankly, it doesn't do anything special with them.
+ // It treats them just like any other fields.
+ IBuilder builder = DynamicMessage.CreateBuilder(TestAllExtensions.Descriptor);
+ extensionsReflectionTester.SetAllFieldsViaReflection(builder);
+ IMessage message = builder.WeakBuild();
+ extensionsReflectionTester.AssertAllFieldsSetViaReflection(message);
+ }
+
+ [Test]
+ public void DynamicMessageExtensionSettersRejectNull()
+ {
+ IBuilder builder = DynamicMessage.CreateBuilder(TestAllExtensions.Descriptor);
+ extensionsReflectionTester.AssertReflectionSettersRejectNull(builder);
+ }
+
+ [Test]
+ public void DynamicMessageRepeatedSetters()
+ {
+ IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
+ reflectionTester.SetAllFieldsViaReflection(builder);
+ reflectionTester.ModifyRepeatedFieldsViaReflection(builder);
+ IMessage message = builder.WeakBuild();
+ reflectionTester.AssertRepeatedFieldsModifiedViaReflection(message);
+ }
+
+ [Test]
+ public void DynamicMessageRepeatedSettersRejectNull()
+ {
+ IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
+ reflectionTester.AssertReflectionRepeatedSettersRejectNull(builder);
+ }
+
+ [Test]
+ public void DynamicMessageDefaults()
+ {
+ reflectionTester.AssertClearViaReflection(DynamicMessage.GetDefaultInstance(TestAllTypes.Descriptor));
+ reflectionTester.AssertClearViaReflection(DynamicMessage.CreateBuilder(TestAllTypes.Descriptor).Build());
+ }
+
+ [Test]
+ public void DynamicMessageSerializedSize()
+ {
+ TestAllTypes message = TestUtil.GetAllSet();
+
+ IBuilder dynamicBuilder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
+ reflectionTester.SetAllFieldsViaReflection(dynamicBuilder);
+ IMessage dynamicMessage = dynamicBuilder.WeakBuild();
+
+ Assert.AreEqual(message.SerializedSize, dynamicMessage.SerializedSize);
+ }
+
+ [Test]
+ public void DynamicMessageSerialization()
+ {
+ IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
+ reflectionTester.SetAllFieldsViaReflection(builder);
+ IMessage message = builder.WeakBuild();
+
+ ByteString rawBytes = message.ToByteString();
+ TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
+
+ TestUtil.AssertAllFieldsSet(message2);
+
+ // In fact, the serialized forms should be exactly the same, byte-for-byte.
+ Assert.AreEqual(TestUtil.GetAllSet().ToByteString(), rawBytes);
+ }
+
+ [Test]
+ public void DynamicMessageParsing()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TestUtil.SetAllFields(builder);
+ TestAllTypes message = builder.Build();
+
+ ByteString rawBytes = message.ToByteString();
+
+ IMessage message2 = DynamicMessage.ParseFrom(TestAllTypes.Descriptor, rawBytes);
+ reflectionTester.AssertAllFieldsSetViaReflection(message2);
+ }
+
+ [Test]
+ public void DynamicMessagePackedSerialization()
+ {
+ IBuilder builder = DynamicMessage.CreateBuilder(TestPackedTypes.Descriptor);
+ packedReflectionTester.SetPackedFieldsViaReflection(builder);
+ IMessage message = builder.WeakBuild();
+
+ ByteString rawBytes = message.ToByteString();
+ TestPackedTypes message2 = TestPackedTypes.ParseFrom(rawBytes);
+
+ TestUtil.AssertPackedFieldsSet(message2);
+
+ // In fact, the serialized forms should be exactly the same, byte-for-byte.
+ Assert.AreEqual(TestUtil.GetPackedSet().ToByteString(), rawBytes);
+ }
+
+ [Test]
+ public void testDynamicMessagePackedParsing()
+ {
+ TestPackedTypes.Builder builder = TestPackedTypes.CreateBuilder();
+ TestUtil.SetPackedFields(builder);
+ TestPackedTypes message = builder.Build();
+
+ ByteString rawBytes = message.ToByteString();
+
+ IMessage message2 = DynamicMessage.ParseFrom(TestPackedTypes.Descriptor, rawBytes);
+ packedReflectionTester.AssertPackedFieldsSetViaReflection(message2);
+ }
+
+ [Test]
+ public void DynamicMessageCopy()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TestUtil.SetAllFields(builder);
+ TestAllTypes message = builder.Build();
+
+ DynamicMessage copy = DynamicMessage.CreateBuilder(message).Build();
+ reflectionTester.AssertAllFieldsSetViaReflection(copy);
+ }
+
+ [Test]
+ public void ToBuilder()
+ {
+ DynamicMessage.Builder builder =
+ DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
+ reflectionTester.SetAllFieldsViaReflection(builder);
+ int unknownFieldNum = 9;
+ ulong unknownFieldVal = 90;
+ builder.SetUnknownFields(UnknownFieldSet.CreateBuilder()
+ .AddField(unknownFieldNum,
+ UnknownField.CreateBuilder().AddVarint(unknownFieldVal).Build())
+ .Build());
+ DynamicMessage message = builder.Build();
+
+ DynamicMessage derived = message.ToBuilder().Build();
+ reflectionTester.AssertAllFieldsSetViaReflection(derived);
+
+ IList<ulong> values = derived.UnknownFields.FieldDictionary[unknownFieldNum].VarintList;
+ Assert.AreEqual(1, values.Count);
+ Assert.AreEqual(unknownFieldVal, values[0]);
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/ExtendableMessageTest.cs b/src/ProtocolBuffers.Test/ExtendableMessageTest.cs index 6ec0cf16..29423ff2 100644 --- a/src/ProtocolBuffers.Test/ExtendableMessageTest.cs +++ b/src/ProtocolBuffers.Test/ExtendableMessageTest.cs @@ -1,192 +1,202 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Collections.Generic; -using Google.ProtocolBuffers; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class ExtendableMessageTest { - - [Test, ExpectedException(typeof(ArgumentException))] - public void ExtensionWriterInvalidExtension() { - TestPackedExtensions.CreateBuilder()[UnitTestProtoFile.OptionalForeignMessageExtension.Descriptor] = - ForeignMessage.DefaultInstance; - } - - [Test] - public void ExtensionWriterTest() { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder() - .SetExtension(UnitTestProtoFile.DefaultBoolExtension, true) - .SetExtension(UnitTestProtoFile.DefaultBytesExtension, ByteString.CopyFromUtf8("123")) - .SetExtension(UnitTestProtoFile.DefaultCordExtension, "123") - .SetExtension(UnitTestProtoFile.DefaultDoubleExtension, 123) - .SetExtension(UnitTestProtoFile.DefaultFixed32Extension, 123u) - .SetExtension(UnitTestProtoFile.DefaultFixed64Extension, 123u) - .SetExtension(UnitTestProtoFile.DefaultFloatExtension, 123) - .SetExtension(UnitTestProtoFile.DefaultForeignEnumExtension, ForeignEnum.FOREIGN_BAZ) - .SetExtension(UnitTestProtoFile.DefaultImportEnumExtension, ImportEnum.IMPORT_BAZ) - .SetExtension(UnitTestProtoFile.DefaultInt32Extension, 123) - .SetExtension(UnitTestProtoFile.DefaultInt64Extension, 123) - .SetExtension(UnitTestProtoFile.DefaultNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO) - .SetExtension(UnitTestProtoFile.DefaultSfixed32Extension, 123) - .SetExtension(UnitTestProtoFile.DefaultSfixed64Extension, 123) - .SetExtension(UnitTestProtoFile.DefaultSint32Extension, 123) - .SetExtension(UnitTestProtoFile.DefaultSint64Extension, 123) - .SetExtension(UnitTestProtoFile.DefaultStringExtension, "123") - .SetExtension(UnitTestProtoFile.DefaultStringPieceExtension, "123") - .SetExtension(UnitTestProtoFile.DefaultUint32Extension, 123u) - .SetExtension(UnitTestProtoFile.DefaultUint64Extension, 123u) - //Optional - .SetExtension(UnitTestProtoFile.OptionalBoolExtension, true) - .SetExtension(UnitTestProtoFile.OptionalBytesExtension, ByteString.CopyFromUtf8("123")) - .SetExtension(UnitTestProtoFile.OptionalCordExtension, "123") - .SetExtension(UnitTestProtoFile.OptionalDoubleExtension, 123) - .SetExtension(UnitTestProtoFile.OptionalFixed32Extension, 123u) - .SetExtension(UnitTestProtoFile.OptionalFixed64Extension, 123u) - .SetExtension(UnitTestProtoFile.OptionalFloatExtension, 123) - .SetExtension(UnitTestProtoFile.OptionalForeignEnumExtension, ForeignEnum.FOREIGN_BAZ) - .SetExtension(UnitTestProtoFile.OptionalImportEnumExtension, ImportEnum.IMPORT_BAZ) - .SetExtension(UnitTestProtoFile.OptionalInt32Extension, 123) - .SetExtension(UnitTestProtoFile.OptionalInt64Extension, 123) - .SetExtension(UnitTestProtoFile.OptionalNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO) - .SetExtension(UnitTestProtoFile.OptionalSfixed32Extension, 123) - .SetExtension(UnitTestProtoFile.OptionalSfixed64Extension, 123) - .SetExtension(UnitTestProtoFile.OptionalSint32Extension, 123) - .SetExtension(UnitTestProtoFile.OptionalSint64Extension, 123) - .SetExtension(UnitTestProtoFile.OptionalStringExtension, "123") - .SetExtension(UnitTestProtoFile.OptionalStringPieceExtension, "123") - .SetExtension(UnitTestProtoFile.OptionalUint32Extension, 123u) - .SetExtension(UnitTestProtoFile.OptionalUint64Extension, 123u) - //Repeated - .AddExtension(UnitTestProtoFile.RepeatedBoolExtension, true) - .AddExtension(UnitTestProtoFile.RepeatedBytesExtension, ByteString.CopyFromUtf8("123")) - .AddExtension(UnitTestProtoFile.RepeatedCordExtension, "123") - .AddExtension(UnitTestProtoFile.RepeatedDoubleExtension, 123) - .AddExtension(UnitTestProtoFile.RepeatedFixed32Extension, 123u) - .AddExtension(UnitTestProtoFile.RepeatedFixed64Extension, 123u) - .AddExtension(UnitTestProtoFile.RepeatedFloatExtension, 123) - .AddExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAZ) - .AddExtension(UnitTestProtoFile.RepeatedImportEnumExtension, ImportEnum.IMPORT_BAZ) - .AddExtension(UnitTestProtoFile.RepeatedInt32Extension, 123) - .AddExtension(UnitTestProtoFile.RepeatedInt64Extension, 123) - .AddExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO) - .AddExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 123) - .AddExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 123) - .AddExtension(UnitTestProtoFile.RepeatedSint32Extension, 123) - .AddExtension(UnitTestProtoFile.RepeatedSint64Extension, 123) - .AddExtension(UnitTestProtoFile.RepeatedStringExtension, "123") - .AddExtension(UnitTestProtoFile.RepeatedStringPieceExtension, "123") - .AddExtension(UnitTestProtoFile.RepeatedUint32Extension, 123u) - .AddExtension(UnitTestProtoFile.RepeatedUint64Extension, 123u) - ; - TestAllExtensions msg = builder.Build(); - - ExtensionRegistry registry = ExtensionRegistry.CreateInstance(); - UnitTestProtoFile.RegisterAllExtensions(registry); - - TestAllExtensions.Builder copyBuilder = TestAllExtensions.CreateBuilder().MergeFrom(msg.ToByteArray(), registry); - TestAllExtensions copy = copyBuilder.Build(); - - Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray()); - - Assert.AreEqual(true, copy.GetExtension(UnitTestProtoFile.DefaultBoolExtension)); - Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(UnitTestProtoFile.DefaultBytesExtension)); - Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.DefaultCordExtension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultDoubleExtension)); - Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.DefaultFixed32Extension)); - Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.DefaultFixed64Extension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultFloatExtension)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, copy.GetExtension(UnitTestProtoFile.DefaultForeignEnumExtension)); - Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(UnitTestProtoFile.DefaultImportEnumExtension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultInt32Extension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultInt64Extension)); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, copy.GetExtension(UnitTestProtoFile.DefaultNestedEnumExtension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultSfixed32Extension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultSfixed64Extension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultSint32Extension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultSint64Extension)); - Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.DefaultStringExtension)); - Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.DefaultStringPieceExtension)); - Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.DefaultUint32Extension)); - Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.DefaultUint64Extension)); - - Assert.AreEqual(true, copy.GetExtension(UnitTestProtoFile.OptionalBoolExtension)); - Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(UnitTestProtoFile.OptionalBytesExtension)); - Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.OptionalCordExtension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalDoubleExtension)); - Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.OptionalFixed32Extension)); - Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.OptionalFixed64Extension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalFloatExtension)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, copy.GetExtension(UnitTestProtoFile.OptionalForeignEnumExtension)); - Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(UnitTestProtoFile.OptionalImportEnumExtension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalInt32Extension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalInt64Extension)); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, copy.GetExtension(UnitTestProtoFile.OptionalNestedEnumExtension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalSfixed32Extension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalSfixed64Extension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalSint32Extension)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalSint64Extension)); - Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.OptionalStringExtension)); - Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.OptionalStringPieceExtension)); - Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.OptionalUint32Extension)); - Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.OptionalUint64Extension)); - - Assert.AreEqual(true, copy.GetExtension(UnitTestProtoFile.RepeatedBoolExtension, 0)); - Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(UnitTestProtoFile.RepeatedBytesExtension, 0)); - Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.RepeatedCordExtension, 0)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedDoubleExtension, 0)); - Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.RepeatedFixed32Extension, 0)); - Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.RepeatedFixed64Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedFloatExtension, 0)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, copy.GetExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, 0)); - Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(UnitTestProtoFile.RepeatedImportEnumExtension, 0)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedInt32Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedInt64Extension, 0)); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, copy.GetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, 0)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedSint32Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedSint64Extension, 0)); - Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.RepeatedStringExtension, 0)); - Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.RepeatedStringPieceExtension, 0)); - Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.RepeatedUint32Extension, 0)); - Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.RepeatedUint64Extension, 0)); - } - - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System;
+using System.Collections.Generic;
+using Google.ProtocolBuffers;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class ExtendableMessageTest
+ {
+ [Test, ExpectedException(typeof (ArgumentException))]
+ public void ExtensionWriterInvalidExtension()
+ {
+ TestPackedExtensions.CreateBuilder()[UnitTestProtoFile.OptionalForeignMessageExtension.Descriptor] =
+ ForeignMessage.DefaultInstance;
+ }
+
+ [Test]
+ public void ExtensionWriterTest()
+ {
+ TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder()
+ .SetExtension(UnitTestProtoFile.DefaultBoolExtension, true)
+ .SetExtension(UnitTestProtoFile.DefaultBytesExtension, ByteString.CopyFromUtf8("123"))
+ .SetExtension(UnitTestProtoFile.DefaultCordExtension, "123")
+ .SetExtension(UnitTestProtoFile.DefaultDoubleExtension, 123)
+ .SetExtension(UnitTestProtoFile.DefaultFixed32Extension, 123u)
+ .SetExtension(UnitTestProtoFile.DefaultFixed64Extension, 123u)
+ .SetExtension(UnitTestProtoFile.DefaultFloatExtension, 123)
+ .SetExtension(UnitTestProtoFile.DefaultForeignEnumExtension, ForeignEnum.FOREIGN_BAZ)
+ .SetExtension(UnitTestProtoFile.DefaultImportEnumExtension, ImportEnum.IMPORT_BAZ)
+ .SetExtension(UnitTestProtoFile.DefaultInt32Extension, 123)
+ .SetExtension(UnitTestProtoFile.DefaultInt64Extension, 123)
+ .SetExtension(UnitTestProtoFile.DefaultNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO)
+ .SetExtension(UnitTestProtoFile.DefaultSfixed32Extension, 123)
+ .SetExtension(UnitTestProtoFile.DefaultSfixed64Extension, 123)
+ .SetExtension(UnitTestProtoFile.DefaultSint32Extension, 123)
+ .SetExtension(UnitTestProtoFile.DefaultSint64Extension, 123)
+ .SetExtension(UnitTestProtoFile.DefaultStringExtension, "123")
+ .SetExtension(UnitTestProtoFile.DefaultStringPieceExtension, "123")
+ .SetExtension(UnitTestProtoFile.DefaultUint32Extension, 123u)
+ .SetExtension(UnitTestProtoFile.DefaultUint64Extension, 123u)
+ //Optional
+ .SetExtension(UnitTestProtoFile.OptionalBoolExtension, true)
+ .SetExtension(UnitTestProtoFile.OptionalBytesExtension, ByteString.CopyFromUtf8("123"))
+ .SetExtension(UnitTestProtoFile.OptionalCordExtension, "123")
+ .SetExtension(UnitTestProtoFile.OptionalDoubleExtension, 123)
+ .SetExtension(UnitTestProtoFile.OptionalFixed32Extension, 123u)
+ .SetExtension(UnitTestProtoFile.OptionalFixed64Extension, 123u)
+ .SetExtension(UnitTestProtoFile.OptionalFloatExtension, 123)
+ .SetExtension(UnitTestProtoFile.OptionalForeignEnumExtension, ForeignEnum.FOREIGN_BAZ)
+ .SetExtension(UnitTestProtoFile.OptionalImportEnumExtension, ImportEnum.IMPORT_BAZ)
+ .SetExtension(UnitTestProtoFile.OptionalInt32Extension, 123)
+ .SetExtension(UnitTestProtoFile.OptionalInt64Extension, 123)
+ .SetExtension(UnitTestProtoFile.OptionalNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO)
+ .SetExtension(UnitTestProtoFile.OptionalSfixed32Extension, 123)
+ .SetExtension(UnitTestProtoFile.OptionalSfixed64Extension, 123)
+ .SetExtension(UnitTestProtoFile.OptionalSint32Extension, 123)
+ .SetExtension(UnitTestProtoFile.OptionalSint64Extension, 123)
+ .SetExtension(UnitTestProtoFile.OptionalStringExtension, "123")
+ .SetExtension(UnitTestProtoFile.OptionalStringPieceExtension, "123")
+ .SetExtension(UnitTestProtoFile.OptionalUint32Extension, 123u)
+ .SetExtension(UnitTestProtoFile.OptionalUint64Extension, 123u)
+ //Repeated
+ .AddExtension(UnitTestProtoFile.RepeatedBoolExtension, true)
+ .AddExtension(UnitTestProtoFile.RepeatedBytesExtension, ByteString.CopyFromUtf8("123"))
+ .AddExtension(UnitTestProtoFile.RepeatedCordExtension, "123")
+ .AddExtension(UnitTestProtoFile.RepeatedDoubleExtension, 123)
+ .AddExtension(UnitTestProtoFile.RepeatedFixed32Extension, 123u)
+ .AddExtension(UnitTestProtoFile.RepeatedFixed64Extension, 123u)
+ .AddExtension(UnitTestProtoFile.RepeatedFloatExtension, 123)
+ .AddExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAZ)
+ .AddExtension(UnitTestProtoFile.RepeatedImportEnumExtension, ImportEnum.IMPORT_BAZ)
+ .AddExtension(UnitTestProtoFile.RepeatedInt32Extension, 123)
+ .AddExtension(UnitTestProtoFile.RepeatedInt64Extension, 123)
+ .AddExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO)
+ .AddExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 123)
+ .AddExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 123)
+ .AddExtension(UnitTestProtoFile.RepeatedSint32Extension, 123)
+ .AddExtension(UnitTestProtoFile.RepeatedSint64Extension, 123)
+ .AddExtension(UnitTestProtoFile.RepeatedStringExtension, "123")
+ .AddExtension(UnitTestProtoFile.RepeatedStringPieceExtension, "123")
+ .AddExtension(UnitTestProtoFile.RepeatedUint32Extension, 123u)
+ .AddExtension(UnitTestProtoFile.RepeatedUint64Extension, 123u)
+ ;
+ TestAllExtensions msg = builder.Build();
+
+ ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
+ UnitTestProtoFile.RegisterAllExtensions(registry);
+
+ TestAllExtensions.Builder copyBuilder = TestAllExtensions.CreateBuilder().MergeFrom(msg.ToByteArray(),
+ registry);
+ TestAllExtensions copy = copyBuilder.Build();
+
+ Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
+
+ Assert.AreEqual(true, copy.GetExtension(UnitTestProtoFile.DefaultBoolExtension));
+ Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(UnitTestProtoFile.DefaultBytesExtension));
+ Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.DefaultCordExtension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultDoubleExtension));
+ Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.DefaultFixed32Extension));
+ Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.DefaultFixed64Extension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultFloatExtension));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, copy.GetExtension(UnitTestProtoFile.DefaultForeignEnumExtension));
+ Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(UnitTestProtoFile.DefaultImportEnumExtension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultInt32Extension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultInt64Extension));
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO,
+ copy.GetExtension(UnitTestProtoFile.DefaultNestedEnumExtension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultSfixed32Extension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultSfixed64Extension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultSint32Extension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.DefaultSint64Extension));
+ Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.DefaultStringExtension));
+ Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.DefaultStringPieceExtension));
+ Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.DefaultUint32Extension));
+ Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.DefaultUint64Extension));
+
+ Assert.AreEqual(true, copy.GetExtension(UnitTestProtoFile.OptionalBoolExtension));
+ Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(UnitTestProtoFile.OptionalBytesExtension));
+ Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.OptionalCordExtension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalDoubleExtension));
+ Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.OptionalFixed32Extension));
+ Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.OptionalFixed64Extension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalFloatExtension));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, copy.GetExtension(UnitTestProtoFile.OptionalForeignEnumExtension));
+ Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(UnitTestProtoFile.OptionalImportEnumExtension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalInt32Extension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalInt64Extension));
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO,
+ copy.GetExtension(UnitTestProtoFile.OptionalNestedEnumExtension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalSfixed32Extension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalSfixed64Extension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalSint32Extension));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.OptionalSint64Extension));
+ Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.OptionalStringExtension));
+ Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.OptionalStringPieceExtension));
+ Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.OptionalUint32Extension));
+ Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.OptionalUint64Extension));
+
+ Assert.AreEqual(true, copy.GetExtension(UnitTestProtoFile.RepeatedBoolExtension, 0));
+ Assert.AreEqual(ByteString.CopyFromUtf8("123"),
+ copy.GetExtension(UnitTestProtoFile.RepeatedBytesExtension, 0));
+ Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.RepeatedCordExtension, 0));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedDoubleExtension, 0));
+ Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.RepeatedFixed32Extension, 0));
+ Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.RepeatedFixed64Extension, 0));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedFloatExtension, 0));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAZ,
+ copy.GetExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, 0));
+ Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(UnitTestProtoFile.RepeatedImportEnumExtension, 0));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedInt32Extension, 0));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedInt64Extension, 0));
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO,
+ copy.GetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, 0));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 0));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 0));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedSint32Extension, 0));
+ Assert.AreEqual(123, copy.GetExtension(UnitTestProtoFile.RepeatedSint64Extension, 0));
+ Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.RepeatedStringExtension, 0));
+ Assert.AreEqual("123", copy.GetExtension(UnitTestProtoFile.RepeatedStringPieceExtension, 0));
+ Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.RepeatedUint32Extension, 0));
+ Assert.AreEqual(123u, copy.GetExtension(UnitTestProtoFile.RepeatedUint64Extension, 0));
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/GeneratedMessageTest.cs b/src/ProtocolBuffers.Test/GeneratedMessageTest.cs index b87794a5..410452d3 100644 --- a/src/ProtocolBuffers.Test/GeneratedMessageTest.cs +++ b/src/ProtocolBuffers.Test/GeneratedMessageTest.cs @@ -1,465 +1,538 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Collections.Generic; -using Google.ProtocolBuffers.Collections; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class GeneratedMessageTest { - ReflectionTester reflectionTester; - ReflectionTester extensionsReflectionTester; - - [SetUp] - public void SetUp() { - reflectionTester = ReflectionTester.CreateTestAllTypesInstance(); - extensionsReflectionTester = ReflectionTester.CreateTestAllExtensionsInstance(); - } - - [Test] - public void RepeatedAddPrimitiveBeforeBuild() { - TestAllTypes message = new TestAllTypes.Builder { RepeatedInt32List = { 1, 2, 3 } }.Build(); - TestUtil.AssertEqual(new int[]{1, 2, 3}, message.RepeatedInt32List); - } - - [Test] - public void AddPrimitiveFailsAfterBuild() { - TestAllTypes.Builder builder = new TestAllTypes.Builder(); - IList<int> list = builder.RepeatedInt32List; - list.Add(1); // Fine - builder.Build(); - - try { - list.Add(2); - Assert.Fail("List should be frozen"); - } catch (NotSupportedException) { - // Expected - } - } - - [Test] - public void RepeatedAddMessageBeforeBuild() { - TestAllTypes message = new TestAllTypes.Builder { - RepeatedNestedMessageList = { new TestAllTypes.Types.NestedMessage.Builder { Bb = 10 }.Build() } }.Build(); - Assert.AreEqual(1, message.RepeatedNestedMessageCount); - Assert.AreEqual(10, message.RepeatedNestedMessageList[0].Bb); - } - - [Test] - public void AddMessageFailsAfterBuild() { - TestAllTypes.Builder builder = new TestAllTypes.Builder(); - IList<TestAllTypes.Types.NestedMessage> list = builder.RepeatedNestedMessageList; - builder.Build(); - - try { - list.Add(new TestAllTypes.Types.NestedMessage.Builder { Bb = 10 }.Build()); - Assert.Fail("List should be frozen"); - } catch (NotSupportedException) { - // Expected - } - } - - [Test] - public void DoubleBuildError() { - TestAllTypes.Builder builder = new TestAllTypes.Builder(); - builder.Build(); - try { - builder.Build(); - Assert.Fail("Should have thrown exception."); - } catch (InvalidOperationException) { - // Success. - } - } - - [Test] - public void DefaultInstance() { - Assert.AreSame(TestAllTypes.DefaultInstance, TestAllTypes.DefaultInstance.DefaultInstanceForType); - Assert.AreSame(TestAllTypes.DefaultInstance, TestAllTypes.CreateBuilder().DefaultInstanceForType); - } - - [Test] - public void Accessors() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertAllFieldsSet(message); - } - - [Test] - public void SettersRejectNull() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.AssertArgumentNullException(() => builder.SetOptionalString(null)); - TestUtil.AssertArgumentNullException(() => builder.SetOptionalBytes(null)); - TestUtil.AssertArgumentNullException(() => builder.SetOptionalNestedMessage((TestAllTypes.Types.NestedMessage)null)); - TestUtil.AssertArgumentNullException(() => builder.SetOptionalNestedMessage((TestAllTypes.Types.NestedMessage.Builder)null)); - TestUtil.AssertArgumentNullException(() => builder.AddRepeatedString(null)); - TestUtil.AssertArgumentNullException(() => builder.AddRepeatedBytes(null)); - TestUtil.AssertArgumentNullException(() => builder.AddRepeatedNestedMessage((TestAllTypes.Types.NestedMessage)null)); - TestUtil.AssertArgumentNullException(() => builder.AddRepeatedNestedMessage((TestAllTypes.Types.NestedMessage.Builder)null)); - } - - [Test] - public void RepeatedSetters() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestUtil.ModifyRepeatedFields(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertRepeatedFieldsModified(message); - } - - [Test] - public void RepeatedAppend() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - - builder.AddRangeRepeatedInt32(new int[]{1, 2, 3, 4}); - builder.AddRangeRepeatedForeignEnum((new ForeignEnum[] { ForeignEnum.FOREIGN_BAZ })); - - ForeignMessage foreignMessage = ForeignMessage.CreateBuilder().SetC(12).Build(); - builder.AddRangeRepeatedForeignMessage(new ForeignMessage[] {foreignMessage}); - - TestAllTypes message = builder.Build(); - TestUtil.AssertEqual(message.RepeatedInt32List, new int[]{1, 2, 3, 4}); - TestUtil.AssertEqual(message.RepeatedForeignEnumList, new ForeignEnum[] {ForeignEnum.FOREIGN_BAZ}); - Assert.AreEqual(1, message.RepeatedForeignMessageCount); - Assert.AreEqual(12, message.GetRepeatedForeignMessage(0).C); - } - - [Test] - public void RepeatedAppendRejectsNull() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - - ForeignMessage foreignMessage = ForeignMessage.CreateBuilder().SetC(12).Build(); - TestUtil.AssertArgumentNullException(() => builder.AddRangeRepeatedForeignMessage(new[] { foreignMessage, null })); - TestUtil.AssertArgumentNullException(() => builder.AddRangeRepeatedForeignMessage(null)); - TestUtil.AssertArgumentNullException(() => builder.AddRangeRepeatedForeignEnum(null)); - TestUtil.AssertArgumentNullException(() => builder.AddRangeRepeatedString(new[] { "one", null })); - TestUtil.AssertArgumentNullException(() => builder.AddRangeRepeatedBytes(new[] { TestUtil.ToBytes("one"), null })); - } - - [Test] - public void SettingForeignMessageUsingBuilder() { - TestAllTypes message = TestAllTypes.CreateBuilder() - // Pass builder for foreign message instance. - .SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(123)) - .Build(); - TestAllTypes expectedMessage = TestAllTypes.CreateBuilder() - // Create expected version passing foreign message instance explicitly. - .SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(123).Build()) - .Build(); - Assert.AreEqual(expectedMessage, message); - } - - [Test] - public void SettingRepeatedForeignMessageUsingBuilder() { - TestAllTypes message = TestAllTypes.CreateBuilder() - // Pass builder for foreign message instance. - .AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(456)) - .Build(); - TestAllTypes expectedMessage = TestAllTypes.CreateBuilder() - // Create expected version passing foreign message instance explicitly. - .AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(456).Build()) - .Build(); - Assert.AreEqual(expectedMessage, message); - } - - [Test] - public void SettingRepeatedValuesUsingRangeInCollectionInitializer() { - int[] values = { 1, 2, 3 }; - TestAllTypes message = new TestAllTypes.Builder { - RepeatedSint32List = { values } - }.Build(); - Assert.IsTrue(Lists.Equals(values, message.RepeatedSint32List)); - } - - [Test] - public void SettingRepeatedValuesUsingIndividualValuesInCollectionInitializer() { - TestAllTypes message = new TestAllTypes.Builder { - RepeatedSint32List = { 6, 7 } - }.Build(); - Assert.IsTrue(Lists.Equals(new int[] { 6, 7 }, message.RepeatedSint32List)); - } - - [Test] - public void Defaults() { - TestUtil.AssertClear(TestAllTypes.DefaultInstance); - TestUtil.AssertClear(TestAllTypes.CreateBuilder().Build()); - - Assert.AreEqual("\u1234", TestExtremeDefaultValues.DefaultInstance.Utf8String); - } - - [Test] - public void ReflectionGetters() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - reflectionTester.AssertAllFieldsSetViaReflection(message); - } - - [Test] - public void ReflectionSetters() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.SetAllFieldsViaReflection(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertAllFieldsSet(message); - } - - [Test] - public void ReflectionSettersRejectNull() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.AssertReflectionSettersRejectNull(builder); - } - [Test] - public void ReflectionRepeatedSetters() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.SetAllFieldsViaReflection(builder); - reflectionTester.ModifyRepeatedFieldsViaReflection(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertRepeatedFieldsModified(message); - } - - [Test] - public void TestReflectionRepeatedSettersRejectNull() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.AssertReflectionRepeatedSettersRejectNull(builder); - } - - [Test] - public void ReflectionDefaults() { - TestUtil.TestInMultipleCultures(() => { - reflectionTester.AssertClearViaReflection(TestAllTypes.DefaultInstance); - reflectionTester.AssertClearViaReflection(TestAllTypes.CreateBuilder().Build()); - }); - } - // ================================================================= - // Extensions. - - [Test] - public void ExtensionAccessors() { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - TestUtil.SetAllExtensions(builder); - TestAllExtensions message = builder.Build(); - TestUtil.AssertAllExtensionsSet(message); - } - - [Test] - public void ExtensionRepeatedSetters() { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - TestUtil.SetAllExtensions(builder); - TestUtil.ModifyRepeatedExtensions(builder); - TestAllExtensions message = builder.Build(); - TestUtil.AssertRepeatedExtensionsModified(message); - } - - [Test] - public void ExtensionDefaults() { - TestUtil.AssertExtensionsClear(TestAllExtensions.DefaultInstance); - TestUtil.AssertExtensionsClear(TestAllExtensions.CreateBuilder().Build()); - } - - [Test] - public void ExtensionReflectionGetters() { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - TestUtil.SetAllExtensions(builder); - TestAllExtensions message = builder.Build(); - extensionsReflectionTester.AssertAllFieldsSetViaReflection(message); - } - - [Test] - public void ExtensionReflectionSetters() { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - extensionsReflectionTester.SetAllFieldsViaReflection(builder); - TestAllExtensions message = builder.Build(); - TestUtil.AssertAllExtensionsSet(message); - } - - [Test] - public void ExtensionReflectionSettersRejectNull() { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - extensionsReflectionTester.AssertReflectionSettersRejectNull(builder); - } - - [Test] - public void ExtensionReflectionRepeatedSetters() { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - extensionsReflectionTester.SetAllFieldsViaReflection(builder); - extensionsReflectionTester.ModifyRepeatedFieldsViaReflection(builder); - TestAllExtensions message = builder.Build(); - TestUtil.AssertRepeatedExtensionsModified(message); - } - - [Test] - public void ExtensionReflectionRepeatedSettersRejectNull() { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - extensionsReflectionTester.AssertReflectionRepeatedSettersRejectNull(builder); - } - - [Test] - public void ExtensionReflectionDefaults() { - TestUtil.TestInMultipleCultures(() => { - extensionsReflectionTester.AssertClearViaReflection(TestAllExtensions.DefaultInstance); - extensionsReflectionTester.AssertClearViaReflection(TestAllExtensions.CreateBuilder().Build()); - }); - } - - [Test] - public void ClearExtension() { - // ClearExtension() is not actually used in TestUtil, so try it manually. - Assert.IsFalse(TestAllExtensions.CreateBuilder() - .SetExtension(UnitTestProtoFile.OptionalInt32Extension, 1) - .ClearExtension(UnitTestProtoFile.OptionalInt32Extension) - .HasExtension(UnitTestProtoFile.OptionalInt32Extension)); - Assert.AreEqual(0, TestAllExtensions.CreateBuilder() - .AddExtension(UnitTestProtoFile.RepeatedInt32Extension, 1) - .ClearExtension(UnitTestProtoFile.RepeatedInt32Extension) - .GetExtensionCount(UnitTestProtoFile.RepeatedInt32Extension)); - } - - [Test] - public void ExtensionMergeFrom() { - TestAllExtensions original = TestAllExtensions.CreateBuilder() - .SetExtension(UnitTestProtoFile.OptionalInt32Extension, 1).Build(); - TestAllExtensions merged = - TestAllExtensions.CreateBuilder().MergeFrom(original).Build(); - Assert.IsTrue((merged.HasExtension(UnitTestProtoFile.OptionalInt32Extension))); - Assert.AreEqual(1, (int)merged.GetExtension(UnitTestProtoFile.OptionalInt32Extension)); - } - - /* Removed multiple files option for the moment - [Test] - public void MultipleFilesOption() { - // We mostly just want to check that things compile. - MessageWithNoOuter message = MessageWithNoOuter.CreateBuilder() - .SetNested(MessageWithNoOuter.Types.NestedMessage.CreateBuilder().SetI(1)) - .AddForeign(TestAllTypes.CreateBuilder().SetOptionalInt32(1)) - .SetNestedEnum(MessageWithNoOuter.Types.NestedEnum.BAZ) - .SetForeignEnum(EnumWithNoOuter.BAR) - .Build(); - Assert.AreEqual(message, MessageWithNoOuter.ParseFrom(message.ToByteString())); - - Assert.AreEqual(MultiFileProto.Descriptor, MessageWithNoOuter.Descriptor.File); - - FieldDescriptor field = MessageWithNoOuter.Descriptor.FindDescriptor<FieldDescriptor>("foreign_enum"); - Assert.AreEqual(MultiFileProto.Descriptor.FindTypeByName<EnumDescriptor>("EnumWithNoOuter") - .FindValueByNumber((int)EnumWithNoOuter.BAR), message[field]); - - Assert.AreEqual(MultiFileProto.Descriptor, ServiceWithNoOuter.Descriptor.File); - - Assert.IsFalse(TestAllExtensions.DefaultInstance.HasExtension(MultiFileProto.ExtensionWithOuter)); - }*/ - - [Test] - public void OptionalFieldWithRequiredSubfieldsOptimizedForSize() { - TestOptionalOptimizedForSize message = TestOptionalOptimizedForSize.DefaultInstance; - Assert.IsTrue(message.IsInitialized); - - message = TestOptionalOptimizedForSize.CreateBuilder().SetO( - TestRequiredOptimizedForSize.CreateBuilder().BuildPartial() - ).BuildPartial(); - Assert.IsFalse(message.IsInitialized); - - message = TestOptionalOptimizedForSize.CreateBuilder().SetO( - TestRequiredOptimizedForSize.CreateBuilder().SetX(5).BuildPartial() - ).BuildPartial(); - Assert.IsTrue(message.IsInitialized); - } - - [Test] - public void OptimizedForSizeMergeUsesAllFieldsFromTarget() { - TestOptimizedForSize withFieldSet = new TestOptimizedForSize.Builder { I = 10 }.Build(); - TestOptimizedForSize.Builder builder = new TestOptimizedForSize.Builder(); - builder.MergeFrom(withFieldSet); - TestOptimizedForSize built = builder.Build(); - Assert.AreEqual(10, built.I); - } - - [Test] - public void UninitializedExtensionInOptimizedForSizeMakesMessageUninitialized() { - TestOptimizedForSize.Builder builder = new TestOptimizedForSize.Builder(); - builder.SetExtension(TestOptimizedForSize.TestExtension2, - new TestRequiredOptimizedForSize.Builder().BuildPartial()); - Assert.IsFalse(builder.IsInitialized); - Assert.IsFalse(builder.BuildPartial().IsInitialized); - - builder = new TestOptimizedForSize.Builder(); - builder.SetExtension(TestOptimizedForSize.TestExtension2, - new TestRequiredOptimizedForSize.Builder { X = 10 }.BuildPartial()); - Assert.IsTrue(builder.IsInitialized); - Assert.IsTrue(builder.BuildPartial().IsInitialized); - } - - [Test] - public void ToBuilder() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertAllFieldsSet(message.ToBuilder().Build()); - } - - [Test] - public void FieldConstantValues() { - Assert.AreEqual(TestAllTypes.Types.NestedMessage.BbFieldNumber, 1); - Assert.AreEqual(TestAllTypes.OptionalInt32FieldNumber, 1); - Assert.AreEqual(TestAllTypes.OptionalGroupFieldNumber, 16); - Assert.AreEqual(TestAllTypes.OptionalNestedMessageFieldNumber, 18); - Assert.AreEqual(TestAllTypes.OptionalNestedEnumFieldNumber, 21); - Assert.AreEqual(TestAllTypes.RepeatedInt32FieldNumber, 31); - Assert.AreEqual(TestAllTypes.RepeatedGroupFieldNumber, 46); - Assert.AreEqual(TestAllTypes.RepeatedNestedMessageFieldNumber, 48); - Assert.AreEqual(TestAllTypes.RepeatedNestedEnumFieldNumber, 51); - } - - [Test] - public void ExtensionConstantValues() { - Assert.AreEqual(TestRequired.SingleFieldNumber, 1000); - Assert.AreEqual(TestRequired.MultiFieldNumber, 1001); - Assert.AreEqual(UnitTestProtoFile.OptionalInt32ExtensionFieldNumber, 1); - Assert.AreEqual(UnitTestProtoFile.OptionalGroupExtensionFieldNumber, 16); - Assert.AreEqual(UnitTestProtoFile.OptionalNestedMessageExtensionFieldNumber, 18); - Assert.AreEqual(UnitTestProtoFile.OptionalNestedEnumExtensionFieldNumber, 21); - Assert.AreEqual(UnitTestProtoFile.RepeatedInt32ExtensionFieldNumber, 31); - Assert.AreEqual(UnitTestProtoFile.RepeatedGroupExtensionFieldNumber, 46); - Assert.AreEqual(UnitTestProtoFile.RepeatedNestedMessageExtensionFieldNumber, 48); - Assert.AreEqual(UnitTestProtoFile.RepeatedNestedEnumExtensionFieldNumber, 51); - } - - [Test] - public void EmptyPackedValue() { - TestPackedTypes empty = new TestPackedTypes.Builder().Build(); - Assert.AreEqual(0, empty.SerializedSize); - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System;
+using System.Collections.Generic;
+using Google.ProtocolBuffers.Collections;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class GeneratedMessageTest
+ {
+ private ReflectionTester reflectionTester;
+ private ReflectionTester extensionsReflectionTester;
+
+ [SetUp]
+ public void SetUp()
+ {
+ reflectionTester = ReflectionTester.CreateTestAllTypesInstance();
+ extensionsReflectionTester = ReflectionTester.CreateTestAllExtensionsInstance();
+ }
+
+ [Test]
+ public void RepeatedAddPrimitiveBeforeBuild()
+ {
+ TestAllTypes message = new TestAllTypes.Builder {RepeatedInt32List = {1, 2, 3}}.Build();
+ TestUtil.AssertEqual(new int[] {1, 2, 3}, message.RepeatedInt32List);
+ }
+
+ [Test]
+ public void AddPrimitiveFailsAfterBuild()
+ {
+ TestAllTypes.Builder builder = new TestAllTypes.Builder();
+ IList<int> list = builder.RepeatedInt32List;
+ list.Add(1); // Fine
+ builder.Build();
+
+ try
+ {
+ list.Add(2);
+ Assert.Fail("List should be frozen");
+ }
+ catch (NotSupportedException)
+ {
+ // Expected
+ }
+ }
+
+ [Test]
+ public void RepeatedAddMessageBeforeBuild()
+ {
+ TestAllTypes message = new TestAllTypes.Builder
+ {
+ RepeatedNestedMessageList =
+ {new TestAllTypes.Types.NestedMessage.Builder {Bb = 10}.Build()}
+ }.Build();
+ Assert.AreEqual(1, message.RepeatedNestedMessageCount);
+ Assert.AreEqual(10, message.RepeatedNestedMessageList[0].Bb);
+ }
+
+ [Test]
+ public void AddMessageFailsAfterBuild()
+ {
+ TestAllTypes.Builder builder = new TestAllTypes.Builder();
+ IList<TestAllTypes.Types.NestedMessage> list = builder.RepeatedNestedMessageList;
+ builder.Build();
+
+ try
+ {
+ list.Add(new TestAllTypes.Types.NestedMessage.Builder {Bb = 10}.Build());
+ Assert.Fail("List should be frozen");
+ }
+ catch (NotSupportedException)
+ {
+ // Expected
+ }
+ }
+
+ [Test]
+ public void DoubleBuildError()
+ {
+ TestAllTypes.Builder builder = new TestAllTypes.Builder();
+ builder.Build();
+ try
+ {
+ builder.Build();
+ Assert.Fail("Should have thrown exception.");
+ }
+ catch (InvalidOperationException)
+ {
+ // Success.
+ }
+ }
+
+ [Test]
+ public void DefaultInstance()
+ {
+ Assert.AreSame(TestAllTypes.DefaultInstance, TestAllTypes.DefaultInstance.DefaultInstanceForType);
+ Assert.AreSame(TestAllTypes.DefaultInstance, TestAllTypes.CreateBuilder().DefaultInstanceForType);
+ }
+
+ [Test]
+ public void Accessors()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TestUtil.SetAllFields(builder);
+ TestAllTypes message = builder.Build();
+ TestUtil.AssertAllFieldsSet(message);
+ }
+
+ [Test]
+ public void SettersRejectNull()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TestUtil.AssertArgumentNullException(() => builder.SetOptionalString(null));
+ TestUtil.AssertArgumentNullException(() => builder.SetOptionalBytes(null));
+ TestUtil.AssertArgumentNullException(
+ () => builder.SetOptionalNestedMessage((TestAllTypes.Types.NestedMessage) null));
+ TestUtil.AssertArgumentNullException(
+ () => builder.SetOptionalNestedMessage((TestAllTypes.Types.NestedMessage.Builder) null));
+ TestUtil.AssertArgumentNullException(() => builder.AddRepeatedString(null));
+ TestUtil.AssertArgumentNullException(() => builder.AddRepeatedBytes(null));
+ TestUtil.AssertArgumentNullException(
+ () => builder.AddRepeatedNestedMessage((TestAllTypes.Types.NestedMessage) null));
+ TestUtil.AssertArgumentNullException(
+ () => builder.AddRepeatedNestedMessage((TestAllTypes.Types.NestedMessage.Builder) null));
+ }
+
+ [Test]
+ public void RepeatedSetters()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TestUtil.SetAllFields(builder);
+ TestUtil.ModifyRepeatedFields(builder);
+ TestAllTypes message = builder.Build();
+ TestUtil.AssertRepeatedFieldsModified(message);
+ }
+
+ [Test]
+ public void RepeatedAppend()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+
+ builder.AddRangeRepeatedInt32(new int[] {1, 2, 3, 4});
+ builder.AddRangeRepeatedForeignEnum((new ForeignEnum[] {ForeignEnum.FOREIGN_BAZ}));
+
+ ForeignMessage foreignMessage = ForeignMessage.CreateBuilder().SetC(12).Build();
+ builder.AddRangeRepeatedForeignMessage(new ForeignMessage[] {foreignMessage});
+
+ TestAllTypes message = builder.Build();
+ TestUtil.AssertEqual(message.RepeatedInt32List, new int[] {1, 2, 3, 4});
+ TestUtil.AssertEqual(message.RepeatedForeignEnumList, new ForeignEnum[] {ForeignEnum.FOREIGN_BAZ});
+ Assert.AreEqual(1, message.RepeatedForeignMessageCount);
+ Assert.AreEqual(12, message.GetRepeatedForeignMessage(0).C);
+ }
+
+ [Test]
+ public void RepeatedAppendRejectsNull()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+
+ ForeignMessage foreignMessage = ForeignMessage.CreateBuilder().SetC(12).Build();
+ TestUtil.AssertArgumentNullException(
+ () => builder.AddRangeRepeatedForeignMessage(new[] {foreignMessage, null}));
+ TestUtil.AssertArgumentNullException(() => builder.AddRangeRepeatedForeignMessage(null));
+ TestUtil.AssertArgumentNullException(() => builder.AddRangeRepeatedForeignEnum(null));
+ TestUtil.AssertArgumentNullException(() => builder.AddRangeRepeatedString(new[] {"one", null}));
+ TestUtil.AssertArgumentNullException(
+ () => builder.AddRangeRepeatedBytes(new[] {TestUtil.ToBytes("one"), null}));
+ }
+
+ [Test]
+ public void SettingForeignMessageUsingBuilder()
+ {
+ TestAllTypes message = TestAllTypes.CreateBuilder()
+ // Pass builder for foreign message instance.
+ .SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(123))
+ .Build();
+ TestAllTypes expectedMessage = TestAllTypes.CreateBuilder()
+ // Create expected version passing foreign message instance explicitly.
+ .SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(123).Build())
+ .Build();
+ Assert.AreEqual(expectedMessage, message);
+ }
+
+ [Test]
+ public void SettingRepeatedForeignMessageUsingBuilder()
+ {
+ TestAllTypes message = TestAllTypes.CreateBuilder()
+ // Pass builder for foreign message instance.
+ .AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(456))
+ .Build();
+ TestAllTypes expectedMessage = TestAllTypes.CreateBuilder()
+ // Create expected version passing foreign message instance explicitly.
+ .AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(456).Build())
+ .Build();
+ Assert.AreEqual(expectedMessage, message);
+ }
+
+ [Test]
+ public void SettingRepeatedValuesUsingRangeInCollectionInitializer()
+ {
+ int[] values = {1, 2, 3};
+ TestAllTypes message = new TestAllTypes.Builder
+ {
+ RepeatedSint32List = {values}
+ }.Build();
+ Assert.IsTrue(Lists.Equals(values, message.RepeatedSint32List));
+ }
+
+ [Test]
+ public void SettingRepeatedValuesUsingIndividualValuesInCollectionInitializer()
+ {
+ TestAllTypes message = new TestAllTypes.Builder
+ {
+ RepeatedSint32List = {6, 7}
+ }.Build();
+ Assert.IsTrue(Lists.Equals(new int[] {6, 7}, message.RepeatedSint32List));
+ }
+
+ [Test]
+ public void Defaults()
+ {
+ TestUtil.AssertClear(TestAllTypes.DefaultInstance);
+ TestUtil.AssertClear(TestAllTypes.CreateBuilder().Build());
+
+ Assert.AreEqual("\u1234", TestExtremeDefaultValues.DefaultInstance.Utf8String);
+ }
+
+ [Test]
+ public void ReflectionGetters()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TestUtil.SetAllFields(builder);
+ TestAllTypes message = builder.Build();
+ reflectionTester.AssertAllFieldsSetViaReflection(message);
+ }
+
+ [Test]
+ public void ReflectionSetters()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ reflectionTester.SetAllFieldsViaReflection(builder);
+ TestAllTypes message = builder.Build();
+ TestUtil.AssertAllFieldsSet(message);
+ }
+
+ [Test]
+ public void ReflectionSettersRejectNull()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ reflectionTester.AssertReflectionSettersRejectNull(builder);
+ }
+
+ [Test]
+ public void ReflectionRepeatedSetters()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ reflectionTester.SetAllFieldsViaReflection(builder);
+ reflectionTester.ModifyRepeatedFieldsViaReflection(builder);
+ TestAllTypes message = builder.Build();
+ TestUtil.AssertRepeatedFieldsModified(message);
+ }
+
+ [Test]
+ public void TestReflectionRepeatedSettersRejectNull()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ reflectionTester.AssertReflectionRepeatedSettersRejectNull(builder);
+ }
+
+ [Test]
+ public void ReflectionDefaults()
+ {
+ TestUtil.TestInMultipleCultures(() =>
+ {
+ reflectionTester.AssertClearViaReflection(
+ TestAllTypes.DefaultInstance);
+ reflectionTester.AssertClearViaReflection(
+ TestAllTypes.CreateBuilder().Build());
+ });
+ }
+
+ // =================================================================
+ // Extensions.
+
+ [Test]
+ public void ExtensionAccessors()
+ {
+ TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
+ TestUtil.SetAllExtensions(builder);
+ TestAllExtensions message = builder.Build();
+ TestUtil.AssertAllExtensionsSet(message);
+ }
+
+ [Test]
+ public void ExtensionRepeatedSetters()
+ {
+ TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
+ TestUtil.SetAllExtensions(builder);
+ TestUtil.ModifyRepeatedExtensions(builder);
+ TestAllExtensions message = builder.Build();
+ TestUtil.AssertRepeatedExtensionsModified(message);
+ }
+
+ [Test]
+ public void ExtensionDefaults()
+ {
+ TestUtil.AssertExtensionsClear(TestAllExtensions.DefaultInstance);
+ TestUtil.AssertExtensionsClear(TestAllExtensions.CreateBuilder().Build());
+ }
+
+ [Test]
+ public void ExtensionReflectionGetters()
+ {
+ TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
+ TestUtil.SetAllExtensions(builder);
+ TestAllExtensions message = builder.Build();
+ extensionsReflectionTester.AssertAllFieldsSetViaReflection(message);
+ }
+
+ [Test]
+ public void ExtensionReflectionSetters()
+ {
+ TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
+ extensionsReflectionTester.SetAllFieldsViaReflection(builder);
+ TestAllExtensions message = builder.Build();
+ TestUtil.AssertAllExtensionsSet(message);
+ }
+
+ [Test]
+ public void ExtensionReflectionSettersRejectNull()
+ {
+ TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
+ extensionsReflectionTester.AssertReflectionSettersRejectNull(builder);
+ }
+
+ [Test]
+ public void ExtensionReflectionRepeatedSetters()
+ {
+ TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
+ extensionsReflectionTester.SetAllFieldsViaReflection(builder);
+ extensionsReflectionTester.ModifyRepeatedFieldsViaReflection(builder);
+ TestAllExtensions message = builder.Build();
+ TestUtil.AssertRepeatedExtensionsModified(message);
+ }
+
+ [Test]
+ public void ExtensionReflectionRepeatedSettersRejectNull()
+ {
+ TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
+ extensionsReflectionTester.AssertReflectionRepeatedSettersRejectNull(builder);
+ }
+
+ [Test]
+ public void ExtensionReflectionDefaults()
+ {
+ TestUtil.TestInMultipleCultures(() =>
+ {
+ extensionsReflectionTester.AssertClearViaReflection(
+ TestAllExtensions.DefaultInstance);
+ extensionsReflectionTester.AssertClearViaReflection(
+ TestAllExtensions.CreateBuilder().Build());
+ });
+ }
+
+ [Test]
+ public void ClearExtension()
+ {
+ // ClearExtension() is not actually used in TestUtil, so try it manually.
+ Assert.IsFalse(TestAllExtensions.CreateBuilder()
+ .SetExtension(UnitTestProtoFile.OptionalInt32Extension, 1)
+ .ClearExtension(UnitTestProtoFile.OptionalInt32Extension)
+ .HasExtension(UnitTestProtoFile.OptionalInt32Extension));
+ Assert.AreEqual(0, TestAllExtensions.CreateBuilder()
+ .AddExtension(UnitTestProtoFile.RepeatedInt32Extension, 1)
+ .ClearExtension(UnitTestProtoFile.RepeatedInt32Extension)
+ .GetExtensionCount(UnitTestProtoFile.RepeatedInt32Extension));
+ }
+
+ [Test]
+ public void ExtensionMergeFrom()
+ {
+ TestAllExtensions original = TestAllExtensions.CreateBuilder()
+ .SetExtension(UnitTestProtoFile.OptionalInt32Extension, 1).Build();
+ TestAllExtensions merged =
+ TestAllExtensions.CreateBuilder().MergeFrom(original).Build();
+ Assert.IsTrue((merged.HasExtension(UnitTestProtoFile.OptionalInt32Extension)));
+ Assert.AreEqual(1, (int) merged.GetExtension(UnitTestProtoFile.OptionalInt32Extension));
+ }
+
+ /* Removed multiple files option for the moment
+ [Test]
+ public void MultipleFilesOption() {
+ // We mostly just want to check that things compile.
+ MessageWithNoOuter message = MessageWithNoOuter.CreateBuilder()
+ .SetNested(MessageWithNoOuter.Types.NestedMessage.CreateBuilder().SetI(1))
+ .AddForeign(TestAllTypes.CreateBuilder().SetOptionalInt32(1))
+ .SetNestedEnum(MessageWithNoOuter.Types.NestedEnum.BAZ)
+ .SetForeignEnum(EnumWithNoOuter.BAR)
+ .Build();
+ Assert.AreEqual(message, MessageWithNoOuter.ParseFrom(message.ToByteString()));
+
+ Assert.AreEqual(MultiFileProto.Descriptor, MessageWithNoOuter.Descriptor.File);
+
+ FieldDescriptor field = MessageWithNoOuter.Descriptor.FindDescriptor<FieldDescriptor>("foreign_enum");
+ Assert.AreEqual(MultiFileProto.Descriptor.FindTypeByName<EnumDescriptor>("EnumWithNoOuter")
+ .FindValueByNumber((int)EnumWithNoOuter.BAR), message[field]);
+
+ Assert.AreEqual(MultiFileProto.Descriptor, ServiceWithNoOuter.Descriptor.File);
+
+ Assert.IsFalse(TestAllExtensions.DefaultInstance.HasExtension(MultiFileProto.ExtensionWithOuter));
+ }*/
+
+ [Test]
+ public void OptionalFieldWithRequiredSubfieldsOptimizedForSize()
+ {
+ TestOptionalOptimizedForSize message = TestOptionalOptimizedForSize.DefaultInstance;
+ Assert.IsTrue(message.IsInitialized);
+
+ message = TestOptionalOptimizedForSize.CreateBuilder().SetO(
+ TestRequiredOptimizedForSize.CreateBuilder().BuildPartial()
+ ).BuildPartial();
+ Assert.IsFalse(message.IsInitialized);
+
+ message = TestOptionalOptimizedForSize.CreateBuilder().SetO(
+ TestRequiredOptimizedForSize.CreateBuilder().SetX(5).BuildPartial()
+ ).BuildPartial();
+ Assert.IsTrue(message.IsInitialized);
+ }
+
+ [Test]
+ public void OptimizedForSizeMergeUsesAllFieldsFromTarget()
+ {
+ TestOptimizedForSize withFieldSet = new TestOptimizedForSize.Builder {I = 10}.Build();
+ TestOptimizedForSize.Builder builder = new TestOptimizedForSize.Builder();
+ builder.MergeFrom(withFieldSet);
+ TestOptimizedForSize built = builder.Build();
+ Assert.AreEqual(10, built.I);
+ }
+
+ [Test]
+ public void UninitializedExtensionInOptimizedForSizeMakesMessageUninitialized()
+ {
+ TestOptimizedForSize.Builder builder = new TestOptimizedForSize.Builder();
+ builder.SetExtension(TestOptimizedForSize.TestExtension2,
+ new TestRequiredOptimizedForSize.Builder().BuildPartial());
+ Assert.IsFalse(builder.IsInitialized);
+ Assert.IsFalse(builder.BuildPartial().IsInitialized);
+
+ builder = new TestOptimizedForSize.Builder();
+ builder.SetExtension(TestOptimizedForSize.TestExtension2,
+ new TestRequiredOptimizedForSize.Builder {X = 10}.BuildPartial());
+ Assert.IsTrue(builder.IsInitialized);
+ Assert.IsTrue(builder.BuildPartial().IsInitialized);
+ }
+
+ [Test]
+ public void ToBuilder()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TestUtil.SetAllFields(builder);
+ TestAllTypes message = builder.Build();
+ TestUtil.AssertAllFieldsSet(message.ToBuilder().Build());
+ }
+
+ [Test]
+ public void FieldConstantValues()
+ {
+ Assert.AreEqual(TestAllTypes.Types.NestedMessage.BbFieldNumber, 1);
+ Assert.AreEqual(TestAllTypes.OptionalInt32FieldNumber, 1);
+ Assert.AreEqual(TestAllTypes.OptionalGroupFieldNumber, 16);
+ Assert.AreEqual(TestAllTypes.OptionalNestedMessageFieldNumber, 18);
+ Assert.AreEqual(TestAllTypes.OptionalNestedEnumFieldNumber, 21);
+ Assert.AreEqual(TestAllTypes.RepeatedInt32FieldNumber, 31);
+ Assert.AreEqual(TestAllTypes.RepeatedGroupFieldNumber, 46);
+ Assert.AreEqual(TestAllTypes.RepeatedNestedMessageFieldNumber, 48);
+ Assert.AreEqual(TestAllTypes.RepeatedNestedEnumFieldNumber, 51);
+ }
+
+ [Test]
+ public void ExtensionConstantValues()
+ {
+ Assert.AreEqual(TestRequired.SingleFieldNumber, 1000);
+ Assert.AreEqual(TestRequired.MultiFieldNumber, 1001);
+ Assert.AreEqual(UnitTestProtoFile.OptionalInt32ExtensionFieldNumber, 1);
+ Assert.AreEqual(UnitTestProtoFile.OptionalGroupExtensionFieldNumber, 16);
+ Assert.AreEqual(UnitTestProtoFile.OptionalNestedMessageExtensionFieldNumber, 18);
+ Assert.AreEqual(UnitTestProtoFile.OptionalNestedEnumExtensionFieldNumber, 21);
+ Assert.AreEqual(UnitTestProtoFile.RepeatedInt32ExtensionFieldNumber, 31);
+ Assert.AreEqual(UnitTestProtoFile.RepeatedGroupExtensionFieldNumber, 46);
+ Assert.AreEqual(UnitTestProtoFile.RepeatedNestedMessageExtensionFieldNumber, 48);
+ Assert.AreEqual(UnitTestProtoFile.RepeatedNestedEnumExtensionFieldNumber, 51);
+ }
+
+ [Test]
+ public void EmptyPackedValue()
+ {
+ TestPackedTypes empty = new TestPackedTypes.Builder().Build();
+ Assert.AreEqual(0, empty.SerializedSize);
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs b/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs index 38125de5..3e4eafe7 100644 --- a/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs +++ b/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs @@ -1,83 +1,91 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System.Collections.Generic; -using System.IO; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; -using NestedMessage = Google.ProtocolBuffers.TestProtos.TestAllTypes.Types.NestedMessage; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class MessageStreamIteratorTest { - - [Test] - public void ThreeMessagesInMemory() { - MemoryStream stream = new MemoryStream(MessageStreamWriterTest.ThreeMessageData); - IEnumerable<NestedMessage> iterator = MessageStreamIterator<NestedMessage>.FromStreamProvider(() => stream); - List<NestedMessage> messages = new List<NestedMessage>(iterator); - - Assert.AreEqual(3, messages.Count); - Assert.AreEqual(5, messages[0].Bb); - Assert.AreEqual(1500, messages[1].Bb); - Assert.IsFalse(messages[2].HasBb); - } - - [Test] - public void ManyMessagesShouldNotTriggerSizeAlert() { - int messageSize = TestUtil.GetAllSet().SerializedSize; - // Enough messages to trigger the alert unless we've reset the size - // Note that currently we need to make this big enough to copy two whole buffers, - // as otherwise when we refill the buffer the second type, the alert triggers instantly. - int correctCount = (CodedInputStream.BufferSize * 2) / messageSize + 1; - using (MemoryStream stream = new MemoryStream()) { - MessageStreamWriter<TestAllTypes> writer = new MessageStreamWriter<TestAllTypes>(stream); - for (int i = 0; i < correctCount; i++) { - writer.Write(TestUtil.GetAllSet()); - } - writer.Flush(); - - stream.Position = 0; - - int count = 0; - foreach (var message in MessageStreamIterator<TestAllTypes>.FromStreamProvider(() => stream) - .WithSizeLimit(CodedInputStream.BufferSize * 2)) { - count++; - TestUtil.AssertAllFieldsSet(message); - } - Assert.AreEqual(correctCount, count); - } - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System.Collections.Generic;
+using System.IO;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+using NestedMessage = Google.ProtocolBuffers.TestProtos.TestAllTypes.Types.NestedMessage;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class MessageStreamIteratorTest
+ {
+ [Test]
+ public void ThreeMessagesInMemory()
+ {
+ MemoryStream stream = new MemoryStream(MessageStreamWriterTest.ThreeMessageData);
+ IEnumerable<NestedMessage> iterator = MessageStreamIterator<NestedMessage>.FromStreamProvider(() => stream);
+ List<NestedMessage> messages = new List<NestedMessage>(iterator);
+
+ Assert.AreEqual(3, messages.Count);
+ Assert.AreEqual(5, messages[0].Bb);
+ Assert.AreEqual(1500, messages[1].Bb);
+ Assert.IsFalse(messages[2].HasBb);
+ }
+
+ [Test]
+ public void ManyMessagesShouldNotTriggerSizeAlert()
+ {
+ int messageSize = TestUtil.GetAllSet().SerializedSize;
+ // Enough messages to trigger the alert unless we've reset the size
+ // Note that currently we need to make this big enough to copy two whole buffers,
+ // as otherwise when we refill the buffer the second type, the alert triggers instantly.
+ int correctCount = (CodedInputStream.BufferSize*2)/messageSize + 1;
+ using (MemoryStream stream = new MemoryStream())
+ {
+ MessageStreamWriter<TestAllTypes> writer = new MessageStreamWriter<TestAllTypes>(stream);
+ for (int i = 0; i < correctCount; i++)
+ {
+ writer.Write(TestUtil.GetAllSet());
+ }
+ writer.Flush();
+
+ stream.Position = 0;
+
+ int count = 0;
+ foreach (var message in MessageStreamIterator<TestAllTypes>.FromStreamProvider(() => stream)
+ .WithSizeLimit(CodedInputStream.BufferSize*2))
+ {
+ count++;
+ TestUtil.AssertAllFieldsSet(message);
+ }
+ Assert.AreEqual(correctCount, count);
+ }
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs b/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs index 3be830a7..e2737914 100644 --- a/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs +++ b/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs @@ -1,70 +1,79 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System.IO; -using NUnit.Framework; -using NestedMessage = Google.ProtocolBuffers.TestProtos.TestAllTypes.Types.NestedMessage; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class MessageStreamWriterTest { - - internal static readonly byte[] ThreeMessageData = new byte[] { - (1 << 3) | 2, 2, // Field 1, 2 bytes long (first message) - (1 << 3) | 0, 5, // Field 1, value 5 - (1 << 3) | 2, 3, // Field 1, 3 bytes long (second message) - (1 << 3) | 0, (1500 & 0x7f) | 0x80, 1500 >> 7, // Field 1, value 1500 - (1 << 3) | 2, 0, // Field 1, no data (third message) - }; - - [Test] - public void ThreeMessages() { - NestedMessage message1 = new NestedMessage.Builder { Bb = 5 }.Build(); - NestedMessage message2 = new NestedMessage.Builder { Bb = 1500 }.Build(); - NestedMessage message3 = new NestedMessage.Builder().Build(); - - byte[] data; - using (MemoryStream stream = new MemoryStream()) { - MessageStreamWriter<NestedMessage> writer = new MessageStreamWriter<NestedMessage>(stream); - writer.Write(message1); - writer.Write(message2); - writer.Write(message3); - writer.Flush(); - data = stream.ToArray(); - } - - TestUtil.AssertEqualBytes(ThreeMessageData, data); - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System.IO;
+using NUnit.Framework;
+using NestedMessage = Google.ProtocolBuffers.TestProtos.TestAllTypes.Types.NestedMessage;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class MessageStreamWriterTest
+ {
+ internal static readonly byte[] ThreeMessageData = new byte[]
+ {
+ (1 << 3) | 2, 2,
+ // Field 1, 2 bytes long (first message)
+ (1 << 3) | 0, 5, // Field 1, value 5
+ (1 << 3) | 2, 3,
+ // Field 1, 3 bytes long (second message)
+ (1 << 3) | 0, (1500 & 0x7f) | 0x80, 1500 >> 7,
+ // Field 1, value 1500
+ (1 << 3) | 2, 0, // Field 1, no data (third message)
+ };
+
+ [Test]
+ public void ThreeMessages()
+ {
+ NestedMessage message1 = new NestedMessage.Builder {Bb = 5}.Build();
+ NestedMessage message2 = new NestedMessage.Builder {Bb = 1500}.Build();
+ NestedMessage message3 = new NestedMessage.Builder().Build();
+
+ byte[] data;
+ using (MemoryStream stream = new MemoryStream())
+ {
+ MessageStreamWriter<NestedMessage> writer = new MessageStreamWriter<NestedMessage>(stream);
+ writer.Write(message1);
+ writer.Write(message2);
+ writer.Write(message3);
+ writer.Flush();
+ data = stream.ToArray();
+ }
+
+ TestUtil.AssertEqualBytes(ThreeMessageData, data);
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/MessageTest.cs b/src/ProtocolBuffers.Test/MessageTest.cs index e06254d7..0f2d1c9a 100644 --- a/src/ProtocolBuffers.Test/MessageTest.cs +++ b/src/ProtocolBuffers.Test/MessageTest.cs @@ -1,329 +1,380 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System.IO; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - /// <summary> - /// Miscellaneous tests for message operations that apply to both - /// generated and dynamic messages. - /// </summary> - [TestFixture] - public class MessageTest { - // ================================================================= - // Message-merging tests. - - private static readonly TestAllTypes MergeSource = new TestAllTypes.Builder { - OptionalInt32 = 1, - OptionalString = "foo", - OptionalForeignMessage = ForeignMessage.DefaultInstance, - }.AddRepeatedString("bar").Build(); - - private static readonly TestAllTypes MergeDest = new TestAllTypes.Builder { - OptionalInt64 = 2, - OptionalString = "baz", - OptionalForeignMessage = new ForeignMessage.Builder { C=3 }.Build(), - }.AddRepeatedString("qux").Build(); - - private const string MergeResultText = - "optional_int32: 1\n" + - "optional_int64: 2\n" + - "optional_string: \"foo\"\n" + - "optional_foreign_message {\n" + - " c: 3\n" + - "}\n" + - "repeated_string: \"qux\"\n" + - "repeated_string: \"bar\"\n"; - - [Test] - public void MergeFrom() { - TestAllTypes result = TestAllTypes.CreateBuilder(MergeDest).MergeFrom(MergeSource).Build(); - - Assert.AreEqual(MergeResultText, result.ToString()); - } - - /// <summary> - /// Test merging a DynamicMessage into a GeneratedMessage. - /// As long as they have the same descriptor, this should work, but it is an - /// entirely different code path. - /// </summary> - [Test] - public void MergeFromDynamic() { - TestAllTypes result = (TestAllTypes) TestAllTypes.CreateBuilder(MergeDest) - .MergeFrom(DynamicMessage.CreateBuilder(MergeSource).Build()) - .Build(); - - Assert.AreEqual(MergeResultText, result.ToString()); - } - - /// <summary> - /// Test merging two DynamicMessages. - /// </summary> - [Test] - public void DynamicMergeFrom() { - DynamicMessage result = (DynamicMessage) DynamicMessage.CreateBuilder(MergeDest) - .MergeFrom((DynamicMessage) DynamicMessage.CreateBuilder(MergeSource).Build()) - .Build(); - - Assert.AreEqual(MergeResultText, result.ToString()); - } - - // ================================================================= - // Required-field-related tests. - - private static readonly TestRequired TestRequiredUninitialized = TestRequired.DefaultInstance; - private static readonly TestRequired TestRequiredInitialized = new TestRequired.Builder { - A = 1, B = 2, C = 3 - }.Build(); - - [Test] - public void Initialization() { - TestRequired.Builder builder = TestRequired.CreateBuilder(); - - Assert.IsFalse(builder.IsInitialized); - builder.A = 1; - Assert.IsFalse(builder.IsInitialized); - builder.B = 1; - Assert.IsFalse(builder.IsInitialized); - builder.C = 1; - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void RequiredForeign() { - TestRequiredForeign.Builder builder = TestRequiredForeign.CreateBuilder(); - - Assert.IsTrue(builder.IsInitialized); - - builder.SetOptionalMessage(TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetOptionalMessage(TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - - builder.AddRepeatedMessage(TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetRepeatedMessage(0, TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void RequiredExtension() { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - - Assert.IsTrue(builder.IsInitialized); - - builder.SetExtension(TestRequired.Single, TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetExtension(TestRequired.Single, TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - - builder.AddExtension(TestRequired.Multi, TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetExtension(TestRequired.Multi, 0, TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void RequiredDynamic() { - MessageDescriptor descriptor = TestRequired.Descriptor; - DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(descriptor); - - Assert.IsFalse(builder.IsInitialized); - builder[descriptor.FindDescriptor<FieldDescriptor>("a")] = 1; - Assert.IsFalse(builder.IsInitialized); - builder[descriptor.FindDescriptor<FieldDescriptor>("b")] = 1; - Assert.IsFalse(builder.IsInitialized); - builder[descriptor.FindDescriptor<FieldDescriptor>("c")] = 1; - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void RequiredDynamicForeign() { - MessageDescriptor descriptor = TestRequiredForeign.Descriptor; - DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(descriptor); - - Assert.IsTrue(builder.IsInitialized); - - builder[descriptor.FindDescriptor<FieldDescriptor>("optional_message")] = TestRequiredUninitialized; - Assert.IsFalse(builder.IsInitialized); - - builder[descriptor.FindDescriptor<FieldDescriptor>("optional_message")] = TestRequiredInitialized; - Assert.IsTrue(builder.IsInitialized); - - builder.AddRepeatedField(descriptor.FindDescriptor<FieldDescriptor>("repeated_message"), TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetRepeatedField(descriptor.FindDescriptor<FieldDescriptor>("repeated_message"), 0, TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void UninitializedException() { - try { - TestRequired.CreateBuilder().Build(); - Assert.Fail("Should have thrown an exception."); - } catch (UninitializedMessageException e) { - Assert.AreEqual("Message missing required fields: a, b, c", e.Message); - } - } - - [Test] - public void BuildPartial() { - // We're mostly testing that no exception is thrown. - TestRequired message = TestRequired.CreateBuilder().BuildPartial(); - Assert.IsFalse(message.IsInitialized); - } - - [Test] - public void NestedUninitializedException() { - try { - TestRequiredForeign.CreateBuilder() - .SetOptionalMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .Build(); - Assert.Fail("Should have thrown an exception."); - } catch (UninitializedMessageException e) { - Assert.AreEqual( - "Message missing required fields: " + - "optional_message.a, " + - "optional_message.b, " + - "optional_message.c, " + - "repeated_message[0].a, " + - "repeated_message[0].b, " + - "repeated_message[0].c, " + - "repeated_message[1].a, " + - "repeated_message[1].b, " + - "repeated_message[1].c", - e.Message); - } - } - - [Test] - public void BuildNestedPartial() { - // We're mostly testing that no exception is thrown. - TestRequiredForeign message = - TestRequiredForeign.CreateBuilder() - .SetOptionalMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .BuildPartial(); - Assert.IsFalse(message.IsInitialized); - } - - [Test] - public void ParseUnititialized() { - try { - TestRequired.ParseFrom(ByteString.Empty); - Assert.Fail("Should have thrown an exception."); - } catch (InvalidProtocolBufferException e) { - Assert.AreEqual("Message missing required fields: a, b, c", e.Message); - } - } - - [Test] - public void ParseNestedUnititialized() { - ByteString data = - TestRequiredForeign.CreateBuilder() - .SetOptionalMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .BuildPartial().ToByteString(); - - try { - TestRequiredForeign.ParseFrom(data); - Assert.Fail("Should have thrown an exception."); - } catch (InvalidProtocolBufferException e) { - Assert.AreEqual( - "Message missing required fields: " + - "optional_message.a, " + - "optional_message.b, " + - "optional_message.c, " + - "repeated_message[0].a, " + - "repeated_message[0].b, " + - "repeated_message[0].c, " + - "repeated_message[1].a, " + - "repeated_message[1].b, " + - "repeated_message[1].c", - e.Message); - } - } - - [Test] - public void DynamicUninitializedException() { - try { - DynamicMessage.CreateBuilder(TestRequired.Descriptor).Build(); - Assert.Fail("Should have thrown an exception."); - } catch (UninitializedMessageException e) { - Assert.AreEqual("Message missing required fields: a, b, c", e.Message); - } - } - - [Test] - public void DynamicBuildPartial() { - // We're mostly testing that no exception is thrown. - DynamicMessage message = DynamicMessage.CreateBuilder(TestRequired.Descriptor).BuildPartial(); - Assert.IsFalse(message.Initialized); - } - - [Test] - public void DynamicParseUnititialized() { - try { - MessageDescriptor descriptor = TestRequired.Descriptor; - DynamicMessage.ParseFrom(descriptor, ByteString.Empty); - Assert.Fail("Should have thrown an exception."); - } catch (InvalidProtocolBufferException e) { - Assert.AreEqual("Message missing required fields: a, b, c", e.Message); - } - } - - [Test] - public void PackedTypesWrittenDirectlyToStream() { - TestPackedTypes message = new TestPackedTypes.Builder {PackedInt32List = {0, 1, 2}}.Build(); - MemoryStream stream = new MemoryStream(); - message.WriteTo(stream); - stream.Position = 0; - TestPackedTypes readMessage = TestPackedTypes.ParseFrom(stream); - Assert.AreEqual(message, readMessage); - } - } - -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System.IO;
+using Google.ProtocolBuffers.Descriptors;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ /// <summary>
+ /// Miscellaneous tests for message operations that apply to both
+ /// generated and dynamic messages.
+ /// </summary>
+ [TestFixture]
+ public class MessageTest
+ {
+ // =================================================================
+ // Message-merging tests.
+
+ private static readonly TestAllTypes MergeSource = new TestAllTypes.Builder
+ {
+ OptionalInt32 = 1,
+ OptionalString = "foo",
+ OptionalForeignMessage =
+ ForeignMessage.DefaultInstance,
+ }.AddRepeatedString("bar").Build();
+
+ private static readonly TestAllTypes MergeDest = new TestAllTypes.Builder
+ {
+ OptionalInt64 = 2,
+ OptionalString = "baz",
+ OptionalForeignMessage =
+ new ForeignMessage.Builder {C = 3}.Build(),
+ }.AddRepeatedString("qux").Build();
+
+ private const string MergeResultText =
+ "optional_int32: 1\n" +
+ "optional_int64: 2\n" +
+ "optional_string: \"foo\"\n" +
+ "optional_foreign_message {\n" +
+ " c: 3\n" +
+ "}\n" +
+ "repeated_string: \"qux\"\n" +
+ "repeated_string: \"bar\"\n";
+
+ [Test]
+ public void MergeFrom()
+ {
+ TestAllTypes result = TestAllTypes.CreateBuilder(MergeDest).MergeFrom(MergeSource).Build();
+
+ Assert.AreEqual(MergeResultText, result.ToString());
+ }
+
+ /// <summary>
+ /// Test merging a DynamicMessage into a GeneratedMessage.
+ /// As long as they have the same descriptor, this should work, but it is an
+ /// entirely different code path.
+ /// </summary>
+ [Test]
+ public void MergeFromDynamic()
+ {
+ TestAllTypes result = (TestAllTypes) TestAllTypes.CreateBuilder(MergeDest)
+ .MergeFrom(DynamicMessage.CreateBuilder(MergeSource).Build())
+ .Build();
+
+ Assert.AreEqual(MergeResultText, result.ToString());
+ }
+
+ /// <summary>
+ /// Test merging two DynamicMessages.
+ /// </summary>
+ [Test]
+ public void DynamicMergeFrom()
+ {
+ DynamicMessage result = (DynamicMessage) DynamicMessage.CreateBuilder(MergeDest)
+ .MergeFrom(
+ (DynamicMessage)
+ DynamicMessage.CreateBuilder(MergeSource).Build())
+ .Build();
+
+ Assert.AreEqual(MergeResultText, result.ToString());
+ }
+
+ // =================================================================
+ // Required-field-related tests.
+
+ private static readonly TestRequired TestRequiredUninitialized = TestRequired.DefaultInstance;
+
+ private static readonly TestRequired TestRequiredInitialized = new TestRequired.Builder
+ {
+ A = 1,
+ B = 2,
+ C = 3
+ }.Build();
+
+ [Test]
+ public void Initialization()
+ {
+ TestRequired.Builder builder = TestRequired.CreateBuilder();
+
+ Assert.IsFalse(builder.IsInitialized);
+ builder.A = 1;
+ Assert.IsFalse(builder.IsInitialized);
+ builder.B = 1;
+ Assert.IsFalse(builder.IsInitialized);
+ builder.C = 1;
+ Assert.IsTrue(builder.IsInitialized);
+ }
+
+ [Test]
+ public void RequiredForeign()
+ {
+ TestRequiredForeign.Builder builder = TestRequiredForeign.CreateBuilder();
+
+ Assert.IsTrue(builder.IsInitialized);
+
+ builder.SetOptionalMessage(TestRequiredUninitialized);
+ Assert.IsFalse(builder.IsInitialized);
+
+ builder.SetOptionalMessage(TestRequiredInitialized);
+ Assert.IsTrue(builder.IsInitialized);
+
+ builder.AddRepeatedMessage(TestRequiredUninitialized);
+ Assert.IsFalse(builder.IsInitialized);
+
+ builder.SetRepeatedMessage(0, TestRequiredInitialized);
+ Assert.IsTrue(builder.IsInitialized);
+ }
+
+ [Test]
+ public void RequiredExtension()
+ {
+ TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
+
+ Assert.IsTrue(builder.IsInitialized);
+
+ builder.SetExtension(TestRequired.Single, TestRequiredUninitialized);
+ Assert.IsFalse(builder.IsInitialized);
+
+ builder.SetExtension(TestRequired.Single, TestRequiredInitialized);
+ Assert.IsTrue(builder.IsInitialized);
+
+ builder.AddExtension(TestRequired.Multi, TestRequiredUninitialized);
+ Assert.IsFalse(builder.IsInitialized);
+
+ builder.SetExtension(TestRequired.Multi, 0, TestRequiredInitialized);
+ Assert.IsTrue(builder.IsInitialized);
+ }
+
+ [Test]
+ public void RequiredDynamic()
+ {
+ MessageDescriptor descriptor = TestRequired.Descriptor;
+ DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(descriptor);
+
+ Assert.IsFalse(builder.IsInitialized);
+ builder[descriptor.FindDescriptor<FieldDescriptor>("a")] = 1;
+ Assert.IsFalse(builder.IsInitialized);
+ builder[descriptor.FindDescriptor<FieldDescriptor>("b")] = 1;
+ Assert.IsFalse(builder.IsInitialized);
+ builder[descriptor.FindDescriptor<FieldDescriptor>("c")] = 1;
+ Assert.IsTrue(builder.IsInitialized);
+ }
+
+ [Test]
+ public void RequiredDynamicForeign()
+ {
+ MessageDescriptor descriptor = TestRequiredForeign.Descriptor;
+ DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(descriptor);
+
+ Assert.IsTrue(builder.IsInitialized);
+
+ builder[descriptor.FindDescriptor<FieldDescriptor>("optional_message")] = TestRequiredUninitialized;
+ Assert.IsFalse(builder.IsInitialized);
+
+ builder[descriptor.FindDescriptor<FieldDescriptor>("optional_message")] = TestRequiredInitialized;
+ Assert.IsTrue(builder.IsInitialized);
+
+ builder.AddRepeatedField(descriptor.FindDescriptor<FieldDescriptor>("repeated_message"),
+ TestRequiredUninitialized);
+ Assert.IsFalse(builder.IsInitialized);
+
+ builder.SetRepeatedField(descriptor.FindDescriptor<FieldDescriptor>("repeated_message"), 0,
+ TestRequiredInitialized);
+ Assert.IsTrue(builder.IsInitialized);
+ }
+
+ [Test]
+ public void UninitializedException()
+ {
+ try
+ {
+ TestRequired.CreateBuilder().Build();
+ Assert.Fail("Should have thrown an exception.");
+ }
+ catch (UninitializedMessageException e)
+ {
+ Assert.AreEqual("Message missing required fields: a, b, c", e.Message);
+ }
+ }
+
+ [Test]
+ public void BuildPartial()
+ {
+ // We're mostly testing that no exception is thrown.
+ TestRequired message = TestRequired.CreateBuilder().BuildPartial();
+ Assert.IsFalse(message.IsInitialized);
+ }
+
+ [Test]
+ public void NestedUninitializedException()
+ {
+ try
+ {
+ TestRequiredForeign.CreateBuilder()
+ .SetOptionalMessage(TestRequiredUninitialized)
+ .AddRepeatedMessage(TestRequiredUninitialized)
+ .AddRepeatedMessage(TestRequiredUninitialized)
+ .Build();
+ Assert.Fail("Should have thrown an exception.");
+ }
+ catch (UninitializedMessageException e)
+ {
+ Assert.AreEqual(
+ "Message missing required fields: " +
+ "optional_message.a, " +
+ "optional_message.b, " +
+ "optional_message.c, " +
+ "repeated_message[0].a, " +
+ "repeated_message[0].b, " +
+ "repeated_message[0].c, " +
+ "repeated_message[1].a, " +
+ "repeated_message[1].b, " +
+ "repeated_message[1].c",
+ e.Message);
+ }
+ }
+
+ [Test]
+ public void BuildNestedPartial()
+ {
+ // We're mostly testing that no exception is thrown.
+ TestRequiredForeign message =
+ TestRequiredForeign.CreateBuilder()
+ .SetOptionalMessage(TestRequiredUninitialized)
+ .AddRepeatedMessage(TestRequiredUninitialized)
+ .AddRepeatedMessage(TestRequiredUninitialized)
+ .BuildPartial();
+ Assert.IsFalse(message.IsInitialized);
+ }
+
+ [Test]
+ public void ParseUnititialized()
+ {
+ try
+ {
+ TestRequired.ParseFrom(ByteString.Empty);
+ Assert.Fail("Should have thrown an exception.");
+ }
+ catch (InvalidProtocolBufferException e)
+ {
+ Assert.AreEqual("Message missing required fields: a, b, c", e.Message);
+ }
+ }
+
+ [Test]
+ public void ParseNestedUnititialized()
+ {
+ ByteString data =
+ TestRequiredForeign.CreateBuilder()
+ .SetOptionalMessage(TestRequiredUninitialized)
+ .AddRepeatedMessage(TestRequiredUninitialized)
+ .AddRepeatedMessage(TestRequiredUninitialized)
+ .BuildPartial().ToByteString();
+
+ try
+ {
+ TestRequiredForeign.ParseFrom(data);
+ Assert.Fail("Should have thrown an exception.");
+ }
+ catch (InvalidProtocolBufferException e)
+ {
+ Assert.AreEqual(
+ "Message missing required fields: " +
+ "optional_message.a, " +
+ "optional_message.b, " +
+ "optional_message.c, " +
+ "repeated_message[0].a, " +
+ "repeated_message[0].b, " +
+ "repeated_message[0].c, " +
+ "repeated_message[1].a, " +
+ "repeated_message[1].b, " +
+ "repeated_message[1].c",
+ e.Message);
+ }
+ }
+
+ [Test]
+ public void DynamicUninitializedException()
+ {
+ try
+ {
+ DynamicMessage.CreateBuilder(TestRequired.Descriptor).Build();
+ Assert.Fail("Should have thrown an exception.");
+ }
+ catch (UninitializedMessageException e)
+ {
+ Assert.AreEqual("Message missing required fields: a, b, c", e.Message);
+ }
+ }
+
+ [Test]
+ public void DynamicBuildPartial()
+ {
+ // We're mostly testing that no exception is thrown.
+ DynamicMessage message = DynamicMessage.CreateBuilder(TestRequired.Descriptor).BuildPartial();
+ Assert.IsFalse(message.Initialized);
+ }
+
+ [Test]
+ public void DynamicParseUnititialized()
+ {
+ try
+ {
+ MessageDescriptor descriptor = TestRequired.Descriptor;
+ DynamicMessage.ParseFrom(descriptor, ByteString.Empty);
+ Assert.Fail("Should have thrown an exception.");
+ }
+ catch (InvalidProtocolBufferException e)
+ {
+ Assert.AreEqual("Message missing required fields: a, b, c", e.Message);
+ }
+ }
+
+ [Test]
+ public void PackedTypesWrittenDirectlyToStream()
+ {
+ TestPackedTypes message = new TestPackedTypes.Builder {PackedInt32List = {0, 1, 2}}.Build();
+ MemoryStream stream = new MemoryStream();
+ message.WriteTo(stream);
+ stream.Position = 0;
+ TestPackedTypes readMessage = TestPackedTypes.ParseFrom(stream);
+ Assert.AreEqual(message, readMessage);
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/MessageUtilTest.cs b/src/ProtocolBuffers.Test/MessageUtilTest.cs index 4054d5f8..c7e08fe8 100644 --- a/src/ProtocolBuffers.Test/MessageUtilTest.cs +++ b/src/ProtocolBuffers.Test/MessageUtilTest.cs @@ -1,77 +1,87 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class MessageUtilTest { - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void NullTypeName() { - MessageUtil.GetDefaultMessage((string)null); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void InvalidTypeName() { - MessageUtil.GetDefaultMessage("invalidtypename"); - } - - [Test] - public void ValidTypeName() { - Assert.AreSame(TestAllTypes.DefaultInstance, MessageUtil.GetDefaultMessage(typeof(TestAllTypes).AssemblyQualifiedName)); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void NullType() { - MessageUtil.GetDefaultMessage((Type)null); - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void NonMessageType() { - MessageUtil.GetDefaultMessage(typeof(string)); - } - - [Test] - public void ValidType() { - Assert.AreSame(TestAllTypes.DefaultInstance, MessageUtil.GetDefaultMessage(typeof(TestAllTypes))); - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class MessageUtilTest
+ {
+ [Test]
+ [ExpectedException(typeof (ArgumentNullException))]
+ public void NullTypeName()
+ {
+ MessageUtil.GetDefaultMessage((string) null);
+ }
+
+ [Test]
+ [ExpectedException(typeof (ArgumentException))]
+ public void InvalidTypeName()
+ {
+ MessageUtil.GetDefaultMessage("invalidtypename");
+ }
+
+ [Test]
+ public void ValidTypeName()
+ {
+ Assert.AreSame(TestAllTypes.DefaultInstance,
+ MessageUtil.GetDefaultMessage(typeof (TestAllTypes).AssemblyQualifiedName));
+ }
+
+ [Test]
+ [ExpectedException(typeof (ArgumentNullException))]
+ public void NullType()
+ {
+ MessageUtil.GetDefaultMessage((Type) null);
+ }
+
+ [Test]
+ [ExpectedException(typeof (ArgumentException))]
+ public void NonMessageType()
+ {
+ MessageUtil.GetDefaultMessage(typeof (string));
+ }
+
+ [Test]
+ public void ValidType()
+ {
+ Assert.AreSame(TestAllTypes.DefaultInstance, MessageUtil.GetDefaultMessage(typeof (TestAllTypes)));
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/NameHelpersTest.cs b/src/ProtocolBuffers.Test/NameHelpersTest.cs index 61270116..b14b0fcf 100644 --- a/src/ProtocolBuffers.Test/NameHelpersTest.cs +++ b/src/ProtocolBuffers.Test/NameHelpersTest.cs @@ -1,66 +1,72 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class NameHelpersTest { - - [Test] - public void UnderscoresToPascalCase() { - Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("Foo_bar")); - Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("foo_bar")); - Assert.AreEqual("Foo0Bar", NameHelpers.UnderscoresToPascalCase("Foo0bar")); - Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("Foo_+_Bar")); - } - - [Test] - public void UnderscoresToCamelCase() { - Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("Foo_bar")); - Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("foo_bar")); - Assert.AreEqual("foo0Bar", NameHelpers.UnderscoresToCamelCase("Foo0bar")); - Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("Foo_+_Bar")); - } - - [Test] - public void StripSuffix() { - string text = "FooBar"; - Assert.IsFalse(NameHelpers.StripSuffix(ref text, "Foo")); - Assert.AreEqual("FooBar", text); - Assert.IsTrue(NameHelpers.StripSuffix(ref text, "Bar")); - Assert.AreEqual("Foo", text); - } - } +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class NameHelpersTest
+ {
+ [Test]
+ public void UnderscoresToPascalCase()
+ {
+ Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("Foo_bar"));
+ Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("foo_bar"));
+ Assert.AreEqual("Foo0Bar", NameHelpers.UnderscoresToPascalCase("Foo0bar"));
+ Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("Foo_+_Bar"));
+ }
+
+ [Test]
+ public void UnderscoresToCamelCase()
+ {
+ Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("Foo_bar"));
+ Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("foo_bar"));
+ Assert.AreEqual("foo0Bar", NameHelpers.UnderscoresToCamelCase("Foo0bar"));
+ Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("Foo_+_Bar"));
+ }
+
+ [Test]
+ public void StripSuffix()
+ {
+ string text = "FooBar";
+ Assert.IsFalse(NameHelpers.StripSuffix(ref text, "Foo"));
+ Assert.AreEqual("FooBar", text);
+ Assert.IsTrue(NameHelpers.StripSuffix(ref text, "Bar"));
+ Assert.AreEqual("Foo", text);
+ }
+ }
}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/Properties/AssemblyInfo.cs b/src/ProtocolBuffers.Test/Properties/AssemblyInfo.cs index d182bdbd..9c51aca6 100644 --- a/src/ProtocolBuffers.Test/Properties/AssemblyInfo.cs +++ b/src/ProtocolBuffers.Test/Properties/AssemblyInfo.cs @@ -1,40 +1,45 @@ -using System; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ProtocolBuffers.Test")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ProtocolBuffers.Test")] -[assembly: AssemblyCopyright("Copyright © 2008")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("54e627c3-daaa-4850-82cf-f25b7f097e78")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("2.3.0.277")] -[assembly: AssemblyVersion("2.3.0.277")] -[assembly: AssemblyFileVersion("2.3.0.277")] -// We don't really need CLSCompliance, but if the assembly builds with no warnings, -// that means the generator is okay. -[assembly: CLSCompliant(true)] +using System;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+
+[assembly: AssemblyTitle("ProtocolBuffers.Test")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("ProtocolBuffers.Test")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+
+[assembly: Guid("54e627c3-daaa-4850-82cf-f25b7f097e78")]
+
+// Version information for an assembly consists of the following four values:
+//
+// Major Version
+// Minor Version
+// Build Number
+// Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("2.3.0.277")]
+
+[assembly: AssemblyVersion("2.3.0.277")]
+[assembly: AssemblyFileVersion("2.3.0.277")]
+// We don't really need CLSCompliance, but if the assembly builds with no warnings,
+// that means the generator is okay.
+
+[assembly: CLSCompliant(true)]
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/ReflectionTester.cs b/src/ProtocolBuffers.Test/ReflectionTester.cs index 3e7ed390..5f323228 100644 --- a/src/ProtocolBuffers.Test/ReflectionTester.cs +++ b/src/ProtocolBuffers.Test/ReflectionTester.cs @@ -1,936 +1,990 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - /// <summary> - /// Performs the same things that the methods of TestUtil do, but - /// via the reflection interface. This is its own class because it needs - /// to know what descriptor to use. - /// </summary> - internal class ReflectionTester { - private readonly MessageDescriptor baseDescriptor; - private readonly ExtensionRegistry extensionRegistry; - - private readonly FileDescriptor file; - private readonly FileDescriptor importFile; - - private readonly MessageDescriptor optionalGroup; - private readonly MessageDescriptor repeatedGroup; - private readonly MessageDescriptor nestedMessage; - private readonly MessageDescriptor foreignMessage; - private readonly MessageDescriptor importMessage; - - private readonly FieldDescriptor groupA; - private readonly FieldDescriptor repeatedGroupA; - private readonly FieldDescriptor nestedB; - private readonly FieldDescriptor foreignC; - private readonly FieldDescriptor importD; - - private readonly EnumDescriptor nestedEnum; - private readonly EnumDescriptor foreignEnum; - private readonly EnumDescriptor importEnum; - - private readonly EnumValueDescriptor nestedFoo; - private readonly EnumValueDescriptor nestedBar; - private readonly EnumValueDescriptor nestedBaz; - private readonly EnumValueDescriptor foreignFoo; - private readonly EnumValueDescriptor foreignBar; - private readonly EnumValueDescriptor foreignBaz; - private readonly EnumValueDescriptor importFoo; - private readonly EnumValueDescriptor importBar; - private readonly EnumValueDescriptor importBaz; - - /// <summary> - /// Constructs an instance that will expect messages using the given - /// descriptor. Normally <paramref name="baseDescriptor"/> should be - /// a descriptor for TestAllTypes. However, if extensionRegistry is non-null, - /// then baseDescriptor should be for TestAllExtensions instead, and instead of - /// reading and writing normal fields, the tester will read and write extensions. - /// All of the TestAllExtensions extensions must be registered in the registry. - /// </summary> - private ReflectionTester(MessageDescriptor baseDescriptor, - ExtensionRegistry extensionRegistry) { - this.baseDescriptor = baseDescriptor; - this.extensionRegistry = extensionRegistry; - - this.file = baseDescriptor.File; - // TODO(jonskeet): We've got 2 dependencies, not 1 - because of the C# options. Hmm. - // Assert.AreEqual(1, file.Dependencies.Count); - // TODO(jonskeet): Find dependency by name instead of number? - this.importFile = file.Dependencies[1]; - - MessageDescriptor testAllTypes; - if (baseDescriptor.Name == "TestAllTypes") { - testAllTypes = baseDescriptor; - } else { - testAllTypes = file.FindTypeByName<MessageDescriptor>("TestAllTypes"); - Assert.IsNotNull(testAllTypes); - } - - if (extensionRegistry == null) { - // Use testAllTypes, rather than baseDescriptor, to allow - // initialization using TestPackedTypes descriptors. These objects - // won't be used by the methods for packed fields. - this.optionalGroup = - testAllTypes.FindDescriptor<MessageDescriptor>("OptionalGroup"); - this.repeatedGroup = - testAllTypes.FindDescriptor<MessageDescriptor>("RepeatedGroup"); - } else { - this.optionalGroup = - file.FindTypeByName<MessageDescriptor>("OptionalGroup_extension"); - this.repeatedGroup = - file.FindTypeByName<MessageDescriptor>("RepeatedGroup_extension"); - } - this.nestedMessage = testAllTypes.FindDescriptor<MessageDescriptor>("NestedMessage"); - this.foreignMessage = file.FindTypeByName<MessageDescriptor>("ForeignMessage"); - this.importMessage = importFile.FindTypeByName<MessageDescriptor>("ImportMessage"); - - this.nestedEnum = testAllTypes.FindDescriptor<EnumDescriptor>("NestedEnum"); - this.foreignEnum = file.FindTypeByName<EnumDescriptor>("ForeignEnum"); - this.importEnum = importFile.FindTypeByName<EnumDescriptor>("ImportEnum"); - - Assert.IsNotNull(optionalGroup); - Assert.IsNotNull(repeatedGroup); - Assert.IsNotNull(nestedMessage); - Assert.IsNotNull(foreignMessage); - Assert.IsNotNull(importMessage); - Assert.IsNotNull(nestedEnum); - Assert.IsNotNull(foreignEnum); - Assert.IsNotNull(importEnum); - - this.nestedB = nestedMessage.FindDescriptor<FieldDescriptor>("bb"); - this.foreignC = foreignMessage.FindDescriptor<FieldDescriptor>("c"); - this.importD = importMessage.FindDescriptor<FieldDescriptor>("d"); - this.nestedFoo = nestedEnum.FindValueByName("FOO"); - this.nestedBar = nestedEnum.FindValueByName("BAR"); - this.nestedBaz = nestedEnum.FindValueByName("BAZ"); - this.foreignFoo = foreignEnum.FindValueByName("FOREIGN_FOO"); - this.foreignBar = foreignEnum.FindValueByName("FOREIGN_BAR"); - this.foreignBaz = foreignEnum.FindValueByName("FOREIGN_BAZ"); - this.importFoo = importEnum.FindValueByName("IMPORT_FOO"); - this.importBar = importEnum.FindValueByName("IMPORT_BAR"); - this.importBaz = importEnum.FindValueByName("IMPORT_BAZ"); - - this.groupA = optionalGroup.FindDescriptor<FieldDescriptor>("a"); - this.repeatedGroupA = repeatedGroup.FindDescriptor<FieldDescriptor>("a"); - - Assert.IsNotNull(groupA); - Assert.IsNotNull(repeatedGroupA); - Assert.IsNotNull(nestedB); - Assert.IsNotNull(foreignC); - Assert.IsNotNull(importD); - Assert.IsNotNull(nestedFoo); - Assert.IsNotNull(nestedBar); - Assert.IsNotNull(nestedBaz); - Assert.IsNotNull(foreignFoo); - Assert.IsNotNull(foreignBar); - Assert.IsNotNull(foreignBaz); - Assert.IsNotNull(importFoo); - Assert.IsNotNull(importBar); - Assert.IsNotNull(importBaz); - } - - /// <summary> - /// Creates an instance for the TestAllTypes message, with no extension registry. - /// </summary> - public static ReflectionTester CreateTestAllTypesInstance() { - return new ReflectionTester(TestAllTypes.Descriptor, null); - } - - /// <summary> - /// Creates an instance for the TestAllExtensions message, with an - /// extension registry from TestUtil.CreateExtensionRegistry. - /// </summary> - public static ReflectionTester CreateTestAllExtensionsInstance() { - return new ReflectionTester(TestAllExtensions.Descriptor, TestUtil.CreateExtensionRegistry()); - } - - /// <summary> - /// Creates an instance for the TestPackedTypes message, with no extensions. - /// </summary> - public static ReflectionTester CreateTestPackedTypesInstance() { - return new ReflectionTester(TestPackedTypes.Descriptor, null); - } - - /// <summary> - /// Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes. - /// </summary> - private FieldDescriptor f(String name) { - FieldDescriptor result; - if (extensionRegistry == null) { - result = baseDescriptor.FindDescriptor<FieldDescriptor>(name); - } else { - result = file.FindTypeByName<FieldDescriptor>(name + "_extension"); - } - Assert.IsNotNull(result); - return result; - } - - /// <summary> - /// Calls parent.CreateBuilderForField() or uses the extension registry - /// to find an appropriate builder, depending on what type is being tested. - /// </summary> - private IBuilder CreateBuilderForField(IBuilder parent, FieldDescriptor field) { - if (extensionRegistry == null) { - return parent.CreateBuilderForField(field); - } else { - ExtensionInfo extension = extensionRegistry[field.ContainingType, field.FieldNumber]; - Assert.IsNotNull(extension); - Assert.IsNotNull(extension.DefaultInstance); - return (IBuilder)extension.DefaultInstance.WeakCreateBuilderForType(); - } - } - - /// <summary> - /// Sets every field of the message to the values expected by - /// AssertAllFieldsSet, using the reflection interface. - /// </summary> - /// <param name="message"></param> - internal void SetAllFieldsViaReflection(IBuilder message) { - message[f("optional_int32")] = 101; - message[f("optional_int64")] = 102L; - message[f("optional_uint32")] = 103U; - message[f("optional_uint64")] = 104UL; - message[f("optional_sint32")] = 105; - message[f("optional_sint64")] = 106L; - message[f("optional_fixed32")] = 107U; - message[f("optional_fixed64")] = 108UL; - message[f("optional_sfixed32")] = 109; - message[f("optional_sfixed64")] = 110L; - message[f("optional_float")] = 111F; - message[f("optional_double")] = 112D; - message[f("optional_bool")] = true; - message[f("optional_string")] = "115"; - message[f("optional_bytes")] = TestUtil.ToBytes("116"); - - message[f("optionalgroup")] = CreateBuilderForField(message, f("optionalgroup")).SetField(groupA, 117).WeakBuild(); - message[f("optional_nested_message")] = CreateBuilderForField(message, f("optional_nested_message")).SetField(nestedB, 118).WeakBuild(); - message[f("optional_foreign_message")] = CreateBuilderForField(message, f("optional_foreign_message")).SetField(foreignC, 119).WeakBuild(); - message[f("optional_import_message")] = CreateBuilderForField(message, f("optional_import_message")).SetField(importD, 120).WeakBuild(); - - message[f("optional_nested_enum")] = nestedBaz; - message[f("optional_foreign_enum")] = foreignBaz; - message[f("optional_import_enum")] = importBaz; - - message[f("optional_string_piece")] = "124"; - message[f("optional_cord")] = "125"; - - // ----------------------------------------------------------------- - - message.WeakAddRepeatedField(f("repeated_int32"), 201); - message.WeakAddRepeatedField(f("repeated_int64"), 202L); - message.WeakAddRepeatedField(f("repeated_uint32"), 203U); - message.WeakAddRepeatedField(f("repeated_uint64"), 204UL); - message.WeakAddRepeatedField(f("repeated_sint32"), 205); - message.WeakAddRepeatedField(f("repeated_sint64"), 206L); - message.WeakAddRepeatedField(f("repeated_fixed32"), 207U); - message.WeakAddRepeatedField(f("repeated_fixed64"), 208UL); - message.WeakAddRepeatedField(f("repeated_sfixed32"), 209); - message.WeakAddRepeatedField(f("repeated_sfixed64"), 210L); - message.WeakAddRepeatedField(f("repeated_float"), 211F); - message.WeakAddRepeatedField(f("repeated_double"), 212D); - message.WeakAddRepeatedField(f("repeated_bool"), true); - message.WeakAddRepeatedField(f("repeated_string"), "215"); - message.WeakAddRepeatedField(f("repeated_bytes"), TestUtil.ToBytes("216")); - - - message.WeakAddRepeatedField(f("repeatedgroup"), CreateBuilderForField(message, f("repeatedgroup")).SetField(repeatedGroupA, 217).WeakBuild()); - message.WeakAddRepeatedField(f("repeated_nested_message"), CreateBuilderForField(message, f("repeated_nested_message")).SetField(nestedB, 218).WeakBuild()); - message.WeakAddRepeatedField(f("repeated_foreign_message"), CreateBuilderForField(message, f("repeated_foreign_message")).SetField(foreignC, 219).WeakBuild()); - message.WeakAddRepeatedField(f("repeated_import_message"), CreateBuilderForField(message, f("repeated_import_message")).SetField(importD, 220).WeakBuild()); - - message.WeakAddRepeatedField(f("repeated_nested_enum"), nestedBar); - message.WeakAddRepeatedField(f("repeated_foreign_enum"), foreignBar); - message.WeakAddRepeatedField(f("repeated_import_enum"), importBar); - - message.WeakAddRepeatedField(f("repeated_string_piece"), "224"); - message.WeakAddRepeatedField(f("repeated_cord"), "225"); - - // Add a second one of each field. - message.WeakAddRepeatedField(f("repeated_int32"), 301); - message.WeakAddRepeatedField(f("repeated_int64"), 302L); - message.WeakAddRepeatedField(f("repeated_uint32"), 303U); - message.WeakAddRepeatedField(f("repeated_uint64"), 304UL); - message.WeakAddRepeatedField(f("repeated_sint32"), 305); - message.WeakAddRepeatedField(f("repeated_sint64"), 306L); - message.WeakAddRepeatedField(f("repeated_fixed32"), 307U); - message.WeakAddRepeatedField(f("repeated_fixed64"), 308UL); - message.WeakAddRepeatedField(f("repeated_sfixed32"), 309); - message.WeakAddRepeatedField(f("repeated_sfixed64"), 310L); - message.WeakAddRepeatedField(f("repeated_float"), 311F); - message.WeakAddRepeatedField(f("repeated_double"), 312D); - message.WeakAddRepeatedField(f("repeated_bool"), false); - message.WeakAddRepeatedField(f("repeated_string"), "315"); - message.WeakAddRepeatedField(f("repeated_bytes"), TestUtil.ToBytes("316")); - - message.WeakAddRepeatedField(f("repeatedgroup"), - CreateBuilderForField(message, f("repeatedgroup")) - .SetField(repeatedGroupA, 317).WeakBuild()); - message.WeakAddRepeatedField(f("repeated_nested_message"), - CreateBuilderForField(message, f("repeated_nested_message")) - .SetField(nestedB, 318).WeakBuild()); - message.WeakAddRepeatedField(f("repeated_foreign_message"), - CreateBuilderForField(message, f("repeated_foreign_message")) - .SetField(foreignC, 319).WeakBuild()); - message.WeakAddRepeatedField(f("repeated_import_message"), - CreateBuilderForField(message, f("repeated_import_message")) - .SetField(importD, 320).WeakBuild()); - - message.WeakAddRepeatedField(f("repeated_nested_enum"), nestedBaz); - message.WeakAddRepeatedField(f("repeated_foreign_enum"), foreignBaz); - message.WeakAddRepeatedField(f("repeated_import_enum"), importBaz); - - message.WeakAddRepeatedField(f("repeated_string_piece"), "324"); - message.WeakAddRepeatedField(f("repeated_cord"), "325"); - - // ----------------------------------------------------------------- - - message[f("default_int32")] = 401; - message[f("default_int64")] = 402L; - message[f("default_uint32")] = 403U; - message[f("default_uint64")] = 404UL; - message[f("default_sint32")] = 405; - message[f("default_sint64")] = 406L; - message[f("default_fixed32")] = 407U; - message[f("default_fixed64")] = 408UL; - message[f("default_sfixed32")] = 409; - message[f("default_sfixed64")] = 410L; - message[f("default_float")] = 411F; - message[f("default_double")] = 412D; - message[f("default_bool")] = false; - message[f("default_string")] = "415"; - message[f("default_bytes")] = TestUtil.ToBytes("416"); - - message[f("default_nested_enum")] = nestedFoo; - message[f("default_foreign_enum")] = foreignFoo; - message[f("default_import_enum")] = importFoo; - - message[f("default_string_piece")] = "424"; - message[f("default_cord")] = "425"; - } - - // ------------------------------------------------------------------- - - /// <summary> - /// Modify the repeated fields of the specified message to contain the - /// values expected by AssertRepeatedFieldsModified, using the IBuilder - /// reflection interface. - /// </summary> - internal void ModifyRepeatedFieldsViaReflection(IBuilder message) { - message[f("repeated_int32"), 1] = 501; - message[f("repeated_int64"), 1] = 502L; - message[f("repeated_uint32"), 1] = 503U; - message[f("repeated_uint64"), 1] = 504UL; - message[f("repeated_sint32"), 1] = 505; - message[f("repeated_sint64"), 1] = 506L; - message[f("repeated_fixed32"), 1] = 507U; - message[f("repeated_fixed64"), 1] = 508UL; - message[f("repeated_sfixed32"), 1] = 509; - message[f("repeated_sfixed64"), 1] = 510L; - message[f("repeated_float"), 1] = 511F; - message[f("repeated_double"), 1] = 512D; - message[f("repeated_bool"), 1] = true; - message[f("repeated_string"), 1] = "515"; - message.SetRepeatedField(f("repeated_bytes"), 1, TestUtil.ToBytes("516")); - - message.SetRepeatedField(f("repeatedgroup"), 1, CreateBuilderForField(message, f("repeatedgroup")).SetField(repeatedGroupA, 517).WeakBuild()); - message.SetRepeatedField(f("repeated_nested_message"), 1, CreateBuilderForField(message, f("repeated_nested_message")).SetField(nestedB, 518).WeakBuild()); - message.SetRepeatedField(f("repeated_foreign_message"), 1, CreateBuilderForField(message, f("repeated_foreign_message")).SetField(foreignC, 519).WeakBuild()); - message.SetRepeatedField(f("repeated_import_message"), 1, CreateBuilderForField(message, f("repeated_import_message")).SetField(importD, 520).WeakBuild()); - - message[f("repeated_nested_enum"), 1] = nestedFoo; - message[f("repeated_foreign_enum"), 1] = foreignFoo; - message[f("repeated_import_enum"), 1] = importFoo; - - message[f("repeated_string_piece"), 1] = "524"; - message[f("repeated_cord"), 1] = "525"; - } - - // ------------------------------------------------------------------- - - /// <summary> - /// Asserts that all fields of the specified message are set to the values - /// assigned by SetAllFields, using the IMessage reflection interface. - /// </summary> - public void AssertAllFieldsSetViaReflection(IMessage message) { - Assert.IsTrue(message.HasField(f("optional_int32"))); - Assert.IsTrue(message.HasField(f("optional_int64"))); - Assert.IsTrue(message.HasField(f("optional_uint32"))); - Assert.IsTrue(message.HasField(f("optional_uint64"))); - Assert.IsTrue(message.HasField(f("optional_sint32"))); - Assert.IsTrue(message.HasField(f("optional_sint64"))); - Assert.IsTrue(message.HasField(f("optional_fixed32"))); - Assert.IsTrue(message.HasField(f("optional_fixed64"))); - Assert.IsTrue(message.HasField(f("optional_sfixed32"))); - Assert.IsTrue(message.HasField(f("optional_sfixed64"))); - Assert.IsTrue(message.HasField(f("optional_float"))); - Assert.IsTrue(message.HasField(f("optional_double"))); - Assert.IsTrue(message.HasField(f("optional_bool"))); - Assert.IsTrue(message.HasField(f("optional_string"))); - Assert.IsTrue(message.HasField(f("optional_bytes"))); - - Assert.IsTrue(message.HasField(f("optionalgroup"))); - Assert.IsTrue(message.HasField(f("optional_nested_message"))); - Assert.IsTrue(message.HasField(f("optional_foreign_message"))); - Assert.IsTrue(message.HasField(f("optional_import_message"))); - - Assert.IsTrue(((IMessage)message[f("optionalgroup")]).HasField(groupA)); - Assert.IsTrue(((IMessage)message[f("optional_nested_message")]).HasField(nestedB)); - Assert.IsTrue(((IMessage)message[f("optional_foreign_message")]).HasField(foreignC)); - Assert.IsTrue(((IMessage)message[f("optional_import_message")]).HasField(importD)); - - Assert.IsTrue(message.HasField(f("optional_nested_enum"))); - Assert.IsTrue(message.HasField(f("optional_foreign_enum"))); - Assert.IsTrue(message.HasField(f("optional_import_enum"))); - - Assert.IsTrue(message.HasField(f("optional_string_piece"))); - Assert.IsTrue(message.HasField(f("optional_cord"))); - - Assert.AreEqual(101, message[f("optional_int32")]); - Assert.AreEqual(102L, message[f("optional_int64")]); - Assert.AreEqual(103U, message[f("optional_uint32")]); - Assert.AreEqual(104UL, message[f("optional_uint64")]); - Assert.AreEqual(105, message[f("optional_sint32")]); - Assert.AreEqual(106L, message[f("optional_sint64")]); - Assert.AreEqual(107U, message[f("optional_fixed32")]); - Assert.AreEqual(108UL, message[f("optional_fixed64")]); - Assert.AreEqual(109, message[f("optional_sfixed32")]); - Assert.AreEqual(110L, message[f("optional_sfixed64")]); - Assert.AreEqual(111F, message[f("optional_float")]); - Assert.AreEqual(112D, message[f("optional_double")]); - Assert.AreEqual(true, message[f("optional_bool")]); - Assert.AreEqual("115", message[f("optional_string")]); - Assert.AreEqual(TestUtil.ToBytes("116"), message[f("optional_bytes")]); - - Assert.AreEqual(117, ((IMessage)message[f("optionalgroup")])[groupA]); - Assert.AreEqual(118, ((IMessage)message[f("optional_nested_message")])[nestedB]); - Assert.AreEqual(119, ((IMessage)message[f("optional_foreign_message")])[foreignC]); - Assert.AreEqual(120, ((IMessage)message[f("optional_import_message")])[importD]); - - Assert.AreEqual(nestedBaz, message[f("optional_nested_enum")]); - Assert.AreEqual(foreignBaz, message[f("optional_foreign_enum")]); - Assert.AreEqual(importBaz, message[f("optional_import_enum")]); - - Assert.AreEqual("124", message[f("optional_string_piece")]); - Assert.AreEqual("125", message[f("optional_cord")]); - - // ----------------------------------------------------------------- - - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_int32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_int64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_uint32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_uint64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sint32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sint64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_fixed32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_fixed64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sfixed32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sfixed64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_float"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_double"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_bool"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_string"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_bytes"))); - - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeatedgroup"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_nested_message"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_foreign_message"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_import_message"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_nested_enum"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_foreign_enum"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_import_enum"))); - - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_string_piece"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_cord"))); - - Assert.AreEqual(201, message[f("repeated_int32"), 0]); - Assert.AreEqual(202L, message[f("repeated_int64"), 0]); - Assert.AreEqual(203U, message[f("repeated_uint32"), 0]); - Assert.AreEqual(204UL, message[f("repeated_uint64"), 0]); - Assert.AreEqual(205, message[f("repeated_sint32"), 0]); - Assert.AreEqual(206L, message[f("repeated_sint64"), 0]); - Assert.AreEqual(207U, message[f("repeated_fixed32"), 0]); - Assert.AreEqual(208UL, message[f("repeated_fixed64"), 0]); - Assert.AreEqual(209, message[f("repeated_sfixed32"), 0]); - Assert.AreEqual(210L, message[f("repeated_sfixed64"), 0]); - Assert.AreEqual(211F, message[f("repeated_float"), 0]); - Assert.AreEqual(212D, message[f("repeated_double"), 0]); - Assert.AreEqual(true, message[f("repeated_bool"), 0]); - Assert.AreEqual("215", message[f("repeated_string"), 0]); - Assert.AreEqual(TestUtil.ToBytes("216"), message[f("repeated_bytes"), 0]); - - Assert.AreEqual(217, ((IMessage)message[f("repeatedgroup"), 0])[repeatedGroupA]); - Assert.AreEqual(218, ((IMessage)message[f("repeated_nested_message"), 0])[nestedB]); - Assert.AreEqual(219, ((IMessage)message[f("repeated_foreign_message"), 0])[foreignC]); - Assert.AreEqual(220, ((IMessage)message[f("repeated_import_message"), 0])[importD]); - - Assert.AreEqual(nestedBar, message[f("repeated_nested_enum"), 0]); - Assert.AreEqual(foreignBar, message[f("repeated_foreign_enum"), 0]); - Assert.AreEqual(importBar, message[f("repeated_import_enum"), 0]); - - Assert.AreEqual("224", message[f("repeated_string_piece"), 0]); - Assert.AreEqual("225", message[f("repeated_cord"), 0]); - - Assert.AreEqual(301, message[f("repeated_int32"), 1]); - Assert.AreEqual(302L, message[f("repeated_int64"), 1]); - Assert.AreEqual(303U, message[f("repeated_uint32"), 1]); - Assert.AreEqual(304UL, message[f("repeated_uint64"), 1]); - Assert.AreEqual(305, message[f("repeated_sint32"), 1]); - Assert.AreEqual(306L, message[f("repeated_sint64"), 1]); - Assert.AreEqual(307U, message[f("repeated_fixed32"), 1]); - Assert.AreEqual(308UL, message[f("repeated_fixed64"), 1]); - Assert.AreEqual(309, message[f("repeated_sfixed32"), 1]); - Assert.AreEqual(310L, message[f("repeated_sfixed64"), 1]); - Assert.AreEqual(311F, message[f("repeated_float"), 1]); - Assert.AreEqual(312D, message[f("repeated_double"), 1]); - Assert.AreEqual(false, message[f("repeated_bool"), 1]); - Assert.AreEqual("315", message[f("repeated_string"), 1]); - Assert.AreEqual(TestUtil.ToBytes("316"), message[f("repeated_bytes"), 1]); - - Assert.AreEqual(317, ((IMessage)message[f("repeatedgroup"), 1])[repeatedGroupA]); - Assert.AreEqual(318, ((IMessage)message[f("repeated_nested_message"), 1])[nestedB]); - Assert.AreEqual(319, ((IMessage)message[f("repeated_foreign_message"), 1])[foreignC]); - Assert.AreEqual(320, ((IMessage)message[f("repeated_import_message"), 1])[importD]); - - Assert.AreEqual(nestedBaz, message[f("repeated_nested_enum"), 1]); - Assert.AreEqual(foreignBaz, message[f("repeated_foreign_enum"), 1]); - Assert.AreEqual(importBaz, message[f("repeated_import_enum"), 1]); - - Assert.AreEqual("324", message[f("repeated_string_piece"), 1]); - Assert.AreEqual("325", message[f("repeated_cord"), 1]); - - // ----------------------------------------------------------------- - - Assert.IsTrue(message.HasField(f("default_int32"))); - Assert.IsTrue(message.HasField(f("default_int64"))); - Assert.IsTrue(message.HasField(f("default_uint32"))); - Assert.IsTrue(message.HasField(f("default_uint64"))); - Assert.IsTrue(message.HasField(f("default_sint32"))); - Assert.IsTrue(message.HasField(f("default_sint64"))); - Assert.IsTrue(message.HasField(f("default_fixed32"))); - Assert.IsTrue(message.HasField(f("default_fixed64"))); - Assert.IsTrue(message.HasField(f("default_sfixed32"))); - Assert.IsTrue(message.HasField(f("default_sfixed64"))); - Assert.IsTrue(message.HasField(f("default_float"))); - Assert.IsTrue(message.HasField(f("default_double"))); - Assert.IsTrue(message.HasField(f("default_bool"))); - Assert.IsTrue(message.HasField(f("default_string"))); - Assert.IsTrue(message.HasField(f("default_bytes"))); - - Assert.IsTrue(message.HasField(f("default_nested_enum"))); - Assert.IsTrue(message.HasField(f("default_foreign_enum"))); - Assert.IsTrue(message.HasField(f("default_import_enum"))); - - Assert.IsTrue(message.HasField(f("default_string_piece"))); - Assert.IsTrue(message.HasField(f("default_cord"))); - - Assert.AreEqual(401, message[f("default_int32")]); - Assert.AreEqual(402L, message[f("default_int64")]); - Assert.AreEqual(403U, message[f("default_uint32")]); - Assert.AreEqual(404UL, message[f("default_uint64")]); - Assert.AreEqual(405, message[f("default_sint32")]); - Assert.AreEqual(406L, message[f("default_sint64")]); - Assert.AreEqual(407U, message[f("default_fixed32")]); - Assert.AreEqual(408UL, message[f("default_fixed64")]); - Assert.AreEqual(409, message[f("default_sfixed32")]); - Assert.AreEqual(410L, message[f("default_sfixed64")]); - Assert.AreEqual(411F, message[f("default_float")]); - Assert.AreEqual(412D, message[f("default_double")]); - Assert.AreEqual(false, message[f("default_bool")]); - Assert.AreEqual("415", message[f("default_string")]); - Assert.AreEqual(TestUtil.ToBytes("416"), message[f("default_bytes")]); - - Assert.AreEqual(nestedFoo, message[f("default_nested_enum")]); - Assert.AreEqual(foreignFoo, message[f("default_foreign_enum")]); - Assert.AreEqual(importFoo, message[f("default_import_enum")]); - - Assert.AreEqual("424", message[f("default_string_piece")]); - Assert.AreEqual("425", message[f("default_cord")]); - } - - /// <summary> - /// Assert that all fields of the message are cleared, and that - /// getting the fields returns their default values, using the reflection interface. - /// </summary> - public void AssertClearViaReflection(IMessage message) { - // has_blah() should initially be false for all optional fields. - Assert.IsFalse(message.HasField(f("optional_int32"))); - Assert.IsFalse(message.HasField(f("optional_int64"))); - Assert.IsFalse(message.HasField(f("optional_uint32"))); - Assert.IsFalse(message.HasField(f("optional_uint64"))); - Assert.IsFalse(message.HasField(f("optional_sint32"))); - Assert.IsFalse(message.HasField(f("optional_sint64"))); - Assert.IsFalse(message.HasField(f("optional_fixed32"))); - Assert.IsFalse(message.HasField(f("optional_fixed64"))); - Assert.IsFalse(message.HasField(f("optional_sfixed32"))); - Assert.IsFalse(message.HasField(f("optional_sfixed64"))); - Assert.IsFalse(message.HasField(f("optional_float"))); - Assert.IsFalse(message.HasField(f("optional_double"))); - Assert.IsFalse(message.HasField(f("optional_bool"))); - Assert.IsFalse(message.HasField(f("optional_string"))); - Assert.IsFalse(message.HasField(f("optional_bytes"))); - - Assert.IsFalse(message.HasField(f("optionalgroup"))); - Assert.IsFalse(message.HasField(f("optional_nested_message"))); - Assert.IsFalse(message.HasField(f("optional_foreign_message"))); - Assert.IsFalse(message.HasField(f("optional_import_message"))); - - Assert.IsFalse(message.HasField(f("optional_nested_enum"))); - Assert.IsFalse(message.HasField(f("optional_foreign_enum"))); - Assert.IsFalse(message.HasField(f("optional_import_enum"))); - - Assert.IsFalse(message.HasField(f("optional_string_piece"))); - Assert.IsFalse(message.HasField(f("optional_cord"))); - - // Optional fields without defaults are set to zero or something like it. - Assert.AreEqual(0, message[f("optional_int32")]); - Assert.AreEqual(0L, message[f("optional_int64")]); - Assert.AreEqual(0U, message[f("optional_uint32")]); - Assert.AreEqual(0UL, message[f("optional_uint64")]); - Assert.AreEqual(0, message[f("optional_sint32")]); - Assert.AreEqual(0L, message[f("optional_sint64")]); - Assert.AreEqual(0U, message[f("optional_fixed32")]); - Assert.AreEqual(0UL, message[f("optional_fixed64")]); - Assert.AreEqual(0, message[f("optional_sfixed32")]); - Assert.AreEqual(0L, message[f("optional_sfixed64")]); - Assert.AreEqual(0F, message[f("optional_float")]); - Assert.AreEqual(0D, message[f("optional_double")]); - Assert.AreEqual(false, message[f("optional_bool")]); - Assert.AreEqual("", message[f("optional_string")]); - Assert.AreEqual(ByteString.Empty, message[f("optional_bytes")]); - - // Embedded messages should also be clear. - Assert.IsFalse(((IMessage)message[f("optionalgroup")]).HasField(groupA)); - Assert.IsFalse(((IMessage)message[f("optional_nested_message")]) - .HasField(nestedB)); - Assert.IsFalse(((IMessage)message[f("optional_foreign_message")]) - .HasField(foreignC)); - Assert.IsFalse(((IMessage)message[f("optional_import_message")]) - .HasField(importD)); - - Assert.AreEqual(0, ((IMessage)message[f("optionalgroup")])[groupA]); - Assert.AreEqual(0, ((IMessage)message[f("optional_nested_message")])[nestedB]); - Assert.AreEqual(0, ((IMessage)message[f("optional_foreign_message")])[foreignC]); - Assert.AreEqual(0, ((IMessage)message[f("optional_import_message")])[importD]); - - // Enums without defaults are set to the first value in the enum. - Assert.AreEqual(nestedFoo, message[f("optional_nested_enum")]); - Assert.AreEqual(foreignFoo, message[f("optional_foreign_enum")]); - Assert.AreEqual(importFoo, message[f("optional_import_enum")]); - - Assert.AreEqual("", message[f("optional_string_piece")]); - Assert.AreEqual("", message[f("optional_cord")]); - - // Repeated fields are empty. - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_int32"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_int64"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_uint32"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_uint64"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_sint32"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_sint64"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_fixed32"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_fixed64"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_sfixed32"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_sfixed64"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_float"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_double"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_bool"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_string"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_bytes"))); - - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeatedgroup"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_nested_message"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_foreign_message"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_import_message"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_nested_enum"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_foreign_enum"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_import_enum"))); - - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_string_piece"))); - Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_cord"))); - - // has_blah() should also be false for all default fields. - Assert.IsFalse(message.HasField(f("default_int32"))); - Assert.IsFalse(message.HasField(f("default_int64"))); - Assert.IsFalse(message.HasField(f("default_uint32"))); - Assert.IsFalse(message.HasField(f("default_uint64"))); - Assert.IsFalse(message.HasField(f("default_sint32"))); - Assert.IsFalse(message.HasField(f("default_sint64"))); - Assert.IsFalse(message.HasField(f("default_fixed32"))); - Assert.IsFalse(message.HasField(f("default_fixed64"))); - Assert.IsFalse(message.HasField(f("default_sfixed32"))); - Assert.IsFalse(message.HasField(f("default_sfixed64"))); - Assert.IsFalse(message.HasField(f("default_float"))); - Assert.IsFalse(message.HasField(f("default_double"))); - Assert.IsFalse(message.HasField(f("default_bool"))); - Assert.IsFalse(message.HasField(f("default_string"))); - Assert.IsFalse(message.HasField(f("default_bytes"))); - - Assert.IsFalse(message.HasField(f("default_nested_enum"))); - Assert.IsFalse(message.HasField(f("default_foreign_enum"))); - Assert.IsFalse(message.HasField(f("default_import_enum"))); - - Assert.IsFalse(message.HasField(f("default_string_piece"))); - Assert.IsFalse(message.HasField(f("default_cord"))); - - // Fields with defaults have their default values (duh). - Assert.AreEqual(41, message[f("default_int32")]); - Assert.AreEqual(42L, message[f("default_int64")]); - Assert.AreEqual(43U, message[f("default_uint32")]); - Assert.AreEqual(44UL, message[f("default_uint64")]); - Assert.AreEqual(-45, message[f("default_sint32")]); - Assert.AreEqual(46L, message[f("default_sint64")]); - Assert.AreEqual(47U, message[f("default_fixed32")]); - Assert.AreEqual(48UL, message[f("default_fixed64")]); - Assert.AreEqual(49, message[f("default_sfixed32")]); - Assert.AreEqual(-50L, message[f("default_sfixed64")]); - Assert.AreEqual(51.5F, message[f("default_float")]); - Assert.AreEqual(52e3D, message[f("default_double")]); - Assert.AreEqual(true, message[f("default_bool")]); - Assert.AreEqual("hello", message[f("default_string")]); - Assert.AreEqual(TestUtil.ToBytes("world"), message[f("default_bytes")]); - - Assert.AreEqual(nestedBar, message[f("default_nested_enum")]); - Assert.AreEqual(foreignBar, message[f("default_foreign_enum")]); - Assert.AreEqual(importBar, message[f("default_import_enum")]); - - Assert.AreEqual("abc", message[f("default_string_piece")]); - Assert.AreEqual("123", message[f("default_cord")]); - } - - // --------------------------------------------------------------- - - internal void AssertRepeatedFieldsModifiedViaReflection(IMessage message) { - // ModifyRepeatedFields only sets the second repeated element of each - // field. In addition to verifying this, we also verify that the first - // element and size were *not* modified. - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_int32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_int64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_uint32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_uint64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sint32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sint64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_fixed32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_fixed64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sfixed32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sfixed64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_float"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_double"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_bool"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_string"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_bytes"))); - - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeatedgroup"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_nested_message"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_foreign_message"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_import_message"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_nested_enum"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_foreign_enum"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_import_enum"))); - - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_string_piece"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_cord"))); - - Assert.AreEqual(201, message[f("repeated_int32"), 0]); - Assert.AreEqual(202L, message[f("repeated_int64"), 0]); - Assert.AreEqual(203U, message[f("repeated_uint32"), 0]); - Assert.AreEqual(204UL, message[f("repeated_uint64"), 0]); - Assert.AreEqual(205, message[f("repeated_sint32"), 0]); - Assert.AreEqual(206L, message[f("repeated_sint64"), 0]); - Assert.AreEqual(207U, message[f("repeated_fixed32"), 0]); - Assert.AreEqual(208UL, message[f("repeated_fixed64"), 0]); - Assert.AreEqual(209, message[f("repeated_sfixed32"), 0]); - Assert.AreEqual(210L, message[f("repeated_sfixed64"), 0]); - Assert.AreEqual(211F, message[f("repeated_float"), 0]); - Assert.AreEqual(212D, message[f("repeated_double"), 0]); - Assert.AreEqual(true, message[f("repeated_bool"), 0]); - Assert.AreEqual("215", message[f("repeated_string"), 0]); - Assert.AreEqual(TestUtil.ToBytes("216"), message[f("repeated_bytes"), 0]); - - Assert.AreEqual(217, ((IMessage)message[f("repeatedgroup"), 0])[repeatedGroupA]); - Assert.AreEqual(218, ((IMessage)message[f("repeated_nested_message"), 0])[nestedB]); - Assert.AreEqual(219, ((IMessage)message[f("repeated_foreign_message"), 0])[foreignC]); - Assert.AreEqual(220, ((IMessage)message[f("repeated_import_message"), 0])[importD]); - - Assert.AreEqual(nestedBar, message[f("repeated_nested_enum"), 0]); - Assert.AreEqual(foreignBar, message[f("repeated_foreign_enum"), 0]); - Assert.AreEqual(importBar, message[f("repeated_import_enum"), 0]); - - Assert.AreEqual("224", message[f("repeated_string_piece"), 0]); - Assert.AreEqual("225", message[f("repeated_cord"), 0]); - - Assert.AreEqual(501, message[f("repeated_int32"), 1]); - Assert.AreEqual(502L, message[f("repeated_int64"), 1]); - Assert.AreEqual(503U, message[f("repeated_uint32"), 1]); - Assert.AreEqual(504UL, message[f("repeated_uint64"), 1]); - Assert.AreEqual(505, message[f("repeated_sint32"), 1]); - Assert.AreEqual(506L, message[f("repeated_sint64"), 1]); - Assert.AreEqual(507U, message[f("repeated_fixed32"), 1]); - Assert.AreEqual(508UL, message[f("repeated_fixed64"), 1]); - Assert.AreEqual(509, message[f("repeated_sfixed32"), 1]); - Assert.AreEqual(510L, message[f("repeated_sfixed64"), 1]); - Assert.AreEqual(511F, message[f("repeated_float"), 1]); - Assert.AreEqual(512D, message[f("repeated_double"), 1]); - Assert.AreEqual(true, message[f("repeated_bool"), 1]); - Assert.AreEqual("515", message[f("repeated_string"), 1]); - Assert.AreEqual(TestUtil.ToBytes("516"), message[f("repeated_bytes"), 1]); - - Assert.AreEqual(517, ((IMessage)message[f("repeatedgroup"), 1])[repeatedGroupA]); - Assert.AreEqual(518, ((IMessage)message[f("repeated_nested_message"), 1])[nestedB]); - Assert.AreEqual(519, ((IMessage)message[f("repeated_foreign_message"), 1])[foreignC]); - Assert.AreEqual(520, ((IMessage)message[f("repeated_import_message"), 1])[importD]); - - Assert.AreEqual(nestedFoo, message[f("repeated_nested_enum"), 1]); - Assert.AreEqual(foreignFoo, message[f("repeated_foreign_enum"), 1]); - Assert.AreEqual(importFoo, message[f("repeated_import_enum"), 1]); - - Assert.AreEqual("524", message[f("repeated_string_piece"), 1]); - Assert.AreEqual("525", message[f("repeated_cord"), 1]); - } - - /// <summary> - /// Verifies that the reflection setters for the given Builder object throw an - /// ArgumentNullException if they are passed a null value. - /// </summary> - public void AssertReflectionSettersRejectNull(IBuilder builder) { - TestUtil.AssertArgumentNullException(() => builder[f("optional_string")] = null); - TestUtil.AssertArgumentNullException(() => builder[f("optional_bytes")] = null); - TestUtil.AssertArgumentNullException(() => builder[f("optional_nested_enum")] = null); - TestUtil.AssertArgumentNullException(() => builder[f("optional_nested_message")] = null); - TestUtil.AssertArgumentNullException(() => builder[f("optional_nested_message")] = null); - TestUtil.AssertArgumentNullException(() => builder.WeakAddRepeatedField(f("repeated_string"), null)); - TestUtil.AssertArgumentNullException(() => builder.WeakAddRepeatedField(f("repeated_bytes"), null)); - TestUtil.AssertArgumentNullException(() => builder.WeakAddRepeatedField(f("repeated_nested_enum"), null)); - TestUtil.AssertArgumentNullException(() => builder.WeakAddRepeatedField(f("repeated_nested_message"), null)); - } - - /// <summary> - /// Verifies that the reflection repeated setters for the given Builder object throw an - /// ArgumentNullException if they are passed a null value. - /// </summary> - public void AssertReflectionRepeatedSettersRejectNull(IBuilder builder) { - builder.WeakAddRepeatedField(f("repeated_string"), "one"); - TestUtil.AssertArgumentNullException(() => builder.SetRepeatedField(f("repeated_string"), 0, null)); - builder.WeakAddRepeatedField(f("repeated_bytes"), TestUtil.ToBytes("one")); - TestUtil.AssertArgumentNullException(() => builder.SetRepeatedField(f("repeated_bytes"), 0, null)); - builder.WeakAddRepeatedField(f("repeated_nested_enum"), nestedBaz); - TestUtil.AssertArgumentNullException(() => builder.SetRepeatedField(f("repeated_nested_enum"), 0, null)); - builder.WeakAddRepeatedField(f("repeated_nested_message"), - new TestAllTypes.Types.NestedMessage.Builder { Bb = 218 }.Build()); - TestUtil.AssertArgumentNullException(() => builder.SetRepeatedField(f("repeated_nested_message"), 0, null)); - } - - public void SetPackedFieldsViaReflection(IBuilder message) { - message.WeakAddRepeatedField(f("packed_int32"), 601); - message.WeakAddRepeatedField(f("packed_int64"), 602L); - message.WeakAddRepeatedField(f("packed_uint32"), 603U); - message.WeakAddRepeatedField(f("packed_uint64"), 604UL); - message.WeakAddRepeatedField(f("packed_sint32"), 605); - message.WeakAddRepeatedField(f("packed_sint64"), 606L); - message.WeakAddRepeatedField(f("packed_fixed32"), 607U); - message.WeakAddRepeatedField(f("packed_fixed64"), 608UL); - message.WeakAddRepeatedField(f("packed_sfixed32"), 609); - message.WeakAddRepeatedField(f("packed_sfixed64"), 610L); - message.WeakAddRepeatedField(f("packed_float"), 611F); - message.WeakAddRepeatedField(f("packed_double"), 612D); - message.WeakAddRepeatedField(f("packed_bool"), true); - message.WeakAddRepeatedField(f("packed_enum"), foreignBar); - // Add a second one of each field. - message.WeakAddRepeatedField(f("packed_int32"), 701); - message.WeakAddRepeatedField(f("packed_int64"), 702L); - message.WeakAddRepeatedField(f("packed_uint32"), 703U); - message.WeakAddRepeatedField(f("packed_uint64"), 704UL); - message.WeakAddRepeatedField(f("packed_sint32"), 705); - message.WeakAddRepeatedField(f("packed_sint64"), 706L); - message.WeakAddRepeatedField(f("packed_fixed32"), 707U); - message.WeakAddRepeatedField(f("packed_fixed64"), 708UL); - message.WeakAddRepeatedField(f("packed_sfixed32"), 709); - message.WeakAddRepeatedField(f("packed_sfixed64"), 710L); - message.WeakAddRepeatedField(f("packed_float"), 711F); - message.WeakAddRepeatedField(f("packed_double"), 712D); - message.WeakAddRepeatedField(f("packed_bool"), false); - message.WeakAddRepeatedField(f("packed_enum"), foreignBaz); - } - - public void AssertPackedFieldsSetViaReflection(IMessage message) { - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_int32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_int64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_uint32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_uint64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_sint32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_sint64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_fixed32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_fixed64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_sfixed32"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_sfixed64"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_float"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_double"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_bool"))); - Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_enum"))); - Assert.AreEqual(601, message[f("packed_int32"), 0]); - Assert.AreEqual(602L, message[f("packed_int64"), 0]); - Assert.AreEqual(603, message[f("packed_uint32"), 0]); - Assert.AreEqual(604L, message[f("packed_uint64"), 0]); - Assert.AreEqual(605, message[f("packed_sint32"), 0]); - Assert.AreEqual(606L, message[f("packed_sint64"), 0]); - Assert.AreEqual(607, message[f("packed_fixed32"), 0]); - Assert.AreEqual(608L, message[f("packed_fixed64"), 0]); - Assert.AreEqual(609, message[f("packed_sfixed32"), 0]); - Assert.AreEqual(610L, message[f("packed_sfixed64"), 0]); - Assert.AreEqual(611F, message[f("packed_float"), 0]); - Assert.AreEqual(612D, message[f("packed_double"), 0]); - Assert.AreEqual(true, message[f("packed_bool"), 0]); - Assert.AreEqual(foreignBar, message[f("packed_enum"), 0]); - Assert.AreEqual(701, message[f("packed_int32"), 1]); - Assert.AreEqual(702L, message[f("packed_int64"), 1]); - Assert.AreEqual(703, message[f("packed_uint32"), 1]); - Assert.AreEqual(704L, message[f("packed_uint64"), 1]); - Assert.AreEqual(705, message[f("packed_sint32"), 1]); - Assert.AreEqual(706L, message[f("packed_sint64"), 1]); - Assert.AreEqual(707, message[f("packed_fixed32"), 1]); - Assert.AreEqual(708L, message[f("packed_fixed64"), 1]); - Assert.AreEqual(709, message[f("packed_sfixed32"), 1]); - Assert.AreEqual(710L, message[f("packed_sfixed64"), 1]); - Assert.AreEqual(711F, message[f("packed_float"), 1]); - Assert.AreEqual(712D, message[f("packed_double"), 1]); - Assert.AreEqual(false, message[f("packed_bool"), 1]); - Assert.AreEqual(foreignBaz, message[f("packed_enum"), 1]); - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System;
+using Google.ProtocolBuffers.Descriptors;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ /// <summary>
+ /// Performs the same things that the methods of TestUtil do, but
+ /// via the reflection interface. This is its own class because it needs
+ /// to know what descriptor to use.
+ /// </summary>
+ internal class ReflectionTester
+ {
+ private readonly MessageDescriptor baseDescriptor;
+ private readonly ExtensionRegistry extensionRegistry;
+
+ private readonly FileDescriptor file;
+ private readonly FileDescriptor importFile;
+
+ private readonly MessageDescriptor optionalGroup;
+ private readonly MessageDescriptor repeatedGroup;
+ private readonly MessageDescriptor nestedMessage;
+ private readonly MessageDescriptor foreignMessage;
+ private readonly MessageDescriptor importMessage;
+
+ private readonly FieldDescriptor groupA;
+ private readonly FieldDescriptor repeatedGroupA;
+ private readonly FieldDescriptor nestedB;
+ private readonly FieldDescriptor foreignC;
+ private readonly FieldDescriptor importD;
+
+ private readonly EnumDescriptor nestedEnum;
+ private readonly EnumDescriptor foreignEnum;
+ private readonly EnumDescriptor importEnum;
+
+ private readonly EnumValueDescriptor nestedFoo;
+ private readonly EnumValueDescriptor nestedBar;
+ private readonly EnumValueDescriptor nestedBaz;
+ private readonly EnumValueDescriptor foreignFoo;
+ private readonly EnumValueDescriptor foreignBar;
+ private readonly EnumValueDescriptor foreignBaz;
+ private readonly EnumValueDescriptor importFoo;
+ private readonly EnumValueDescriptor importBar;
+ private readonly EnumValueDescriptor importBaz;
+
+ /// <summary>
+ /// Constructs an instance that will expect messages using the given
+ /// descriptor. Normally <paramref name="baseDescriptor"/> should be
+ /// a descriptor for TestAllTypes. However, if extensionRegistry is non-null,
+ /// then baseDescriptor should be for TestAllExtensions instead, and instead of
+ /// reading and writing normal fields, the tester will read and write extensions.
+ /// All of the TestAllExtensions extensions must be registered in the registry.
+ /// </summary>
+ private ReflectionTester(MessageDescriptor baseDescriptor,
+ ExtensionRegistry extensionRegistry)
+ {
+ this.baseDescriptor = baseDescriptor;
+ this.extensionRegistry = extensionRegistry;
+
+ this.file = baseDescriptor.File;
+ // TODO(jonskeet): We've got 2 dependencies, not 1 - because of the C# options. Hmm.
+ // Assert.AreEqual(1, file.Dependencies.Count);
+ // TODO(jonskeet): Find dependency by name instead of number?
+ this.importFile = file.Dependencies[1];
+
+ MessageDescriptor testAllTypes;
+ if (baseDescriptor.Name == "TestAllTypes")
+ {
+ testAllTypes = baseDescriptor;
+ }
+ else
+ {
+ testAllTypes = file.FindTypeByName<MessageDescriptor>("TestAllTypes");
+ Assert.IsNotNull(testAllTypes);
+ }
+
+ if (extensionRegistry == null)
+ {
+ // Use testAllTypes, rather than baseDescriptor, to allow
+ // initialization using TestPackedTypes descriptors. These objects
+ // won't be used by the methods for packed fields.
+ this.optionalGroup =
+ testAllTypes.FindDescriptor<MessageDescriptor>("OptionalGroup");
+ this.repeatedGroup =
+ testAllTypes.FindDescriptor<MessageDescriptor>("RepeatedGroup");
+ }
+ else
+ {
+ this.optionalGroup =
+ file.FindTypeByName<MessageDescriptor>("OptionalGroup_extension");
+ this.repeatedGroup =
+ file.FindTypeByName<MessageDescriptor>("RepeatedGroup_extension");
+ }
+ this.nestedMessage = testAllTypes.FindDescriptor<MessageDescriptor>("NestedMessage");
+ this.foreignMessage = file.FindTypeByName<MessageDescriptor>("ForeignMessage");
+ this.importMessage = importFile.FindTypeByName<MessageDescriptor>("ImportMessage");
+
+ this.nestedEnum = testAllTypes.FindDescriptor<EnumDescriptor>("NestedEnum");
+ this.foreignEnum = file.FindTypeByName<EnumDescriptor>("ForeignEnum");
+ this.importEnum = importFile.FindTypeByName<EnumDescriptor>("ImportEnum");
+
+ Assert.IsNotNull(optionalGroup);
+ Assert.IsNotNull(repeatedGroup);
+ Assert.IsNotNull(nestedMessage);
+ Assert.IsNotNull(foreignMessage);
+ Assert.IsNotNull(importMessage);
+ Assert.IsNotNull(nestedEnum);
+ Assert.IsNotNull(foreignEnum);
+ Assert.IsNotNull(importEnum);
+
+ this.nestedB = nestedMessage.FindDescriptor<FieldDescriptor>("bb");
+ this.foreignC = foreignMessage.FindDescriptor<FieldDescriptor>("c");
+ this.importD = importMessage.FindDescriptor<FieldDescriptor>("d");
+ this.nestedFoo = nestedEnum.FindValueByName("FOO");
+ this.nestedBar = nestedEnum.FindValueByName("BAR");
+ this.nestedBaz = nestedEnum.FindValueByName("BAZ");
+ this.foreignFoo = foreignEnum.FindValueByName("FOREIGN_FOO");
+ this.foreignBar = foreignEnum.FindValueByName("FOREIGN_BAR");
+ this.foreignBaz = foreignEnum.FindValueByName("FOREIGN_BAZ");
+ this.importFoo = importEnum.FindValueByName("IMPORT_FOO");
+ this.importBar = importEnum.FindValueByName("IMPORT_BAR");
+ this.importBaz = importEnum.FindValueByName("IMPORT_BAZ");
+
+ this.groupA = optionalGroup.FindDescriptor<FieldDescriptor>("a");
+ this.repeatedGroupA = repeatedGroup.FindDescriptor<FieldDescriptor>("a");
+
+ Assert.IsNotNull(groupA);
+ Assert.IsNotNull(repeatedGroupA);
+ Assert.IsNotNull(nestedB);
+ Assert.IsNotNull(foreignC);
+ Assert.IsNotNull(importD);
+ Assert.IsNotNull(nestedFoo);
+ Assert.IsNotNull(nestedBar);
+ Assert.IsNotNull(nestedBaz);
+ Assert.IsNotNull(foreignFoo);
+ Assert.IsNotNull(foreignBar);
+ Assert.IsNotNull(foreignBaz);
+ Assert.IsNotNull(importFoo);
+ Assert.IsNotNull(importBar);
+ Assert.IsNotNull(importBaz);
+ }
+
+ /// <summary>
+ /// Creates an instance for the TestAllTypes message, with no extension registry.
+ /// </summary>
+ public static ReflectionTester CreateTestAllTypesInstance()
+ {
+ return new ReflectionTester(TestAllTypes.Descriptor, null);
+ }
+
+ /// <summary>
+ /// Creates an instance for the TestAllExtensions message, with an
+ /// extension registry from TestUtil.CreateExtensionRegistry.
+ /// </summary>
+ public static ReflectionTester CreateTestAllExtensionsInstance()
+ {
+ return new ReflectionTester(TestAllExtensions.Descriptor, TestUtil.CreateExtensionRegistry());
+ }
+
+ /// <summary>
+ /// Creates an instance for the TestPackedTypes message, with no extensions.
+ /// </summary>
+ public static ReflectionTester CreateTestPackedTypesInstance()
+ {
+ return new ReflectionTester(TestPackedTypes.Descriptor, null);
+ }
+
+ /// <summary>
+ /// Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes.
+ /// </summary>
+ private FieldDescriptor f(String name)
+ {
+ FieldDescriptor result;
+ if (extensionRegistry == null)
+ {
+ result = baseDescriptor.FindDescriptor<FieldDescriptor>(name);
+ }
+ else
+ {
+ result = file.FindTypeByName<FieldDescriptor>(name + "_extension");
+ }
+ Assert.IsNotNull(result);
+ return result;
+ }
+
+ /// <summary>
+ /// Calls parent.CreateBuilderForField() or uses the extension registry
+ /// to find an appropriate builder, depending on what type is being tested.
+ /// </summary>
+ private IBuilder CreateBuilderForField(IBuilder parent, FieldDescriptor field)
+ {
+ if (extensionRegistry == null)
+ {
+ return parent.CreateBuilderForField(field);
+ }
+ else
+ {
+ ExtensionInfo extension = extensionRegistry[field.ContainingType, field.FieldNumber];
+ Assert.IsNotNull(extension);
+ Assert.IsNotNull(extension.DefaultInstance);
+ return (IBuilder) extension.DefaultInstance.WeakCreateBuilderForType();
+ }
+ }
+
+ /// <summary>
+ /// Sets every field of the message to the values expected by
+ /// AssertAllFieldsSet, using the reflection interface.
+ /// </summary>
+ /// <param name="message"></param>
+ internal void SetAllFieldsViaReflection(IBuilder message)
+ {
+ message[f("optional_int32")] = 101;
+ message[f("optional_int64")] = 102L;
+ message[f("optional_uint32")] = 103U;
+ message[f("optional_uint64")] = 104UL;
+ message[f("optional_sint32")] = 105;
+ message[f("optional_sint64")] = 106L;
+ message[f("optional_fixed32")] = 107U;
+ message[f("optional_fixed64")] = 108UL;
+ message[f("optional_sfixed32")] = 109;
+ message[f("optional_sfixed64")] = 110L;
+ message[f("optional_float")] = 111F;
+ message[f("optional_double")] = 112D;
+ message[f("optional_bool")] = true;
+ message[f("optional_string")] = "115";
+ message[f("optional_bytes")] = TestUtil.ToBytes("116");
+
+ message[f("optionalgroup")] =
+ CreateBuilderForField(message, f("optionalgroup")).SetField(groupA, 117).WeakBuild();
+ message[f("optional_nested_message")] =
+ CreateBuilderForField(message, f("optional_nested_message")).SetField(nestedB, 118).WeakBuild();
+ message[f("optional_foreign_message")] =
+ CreateBuilderForField(message, f("optional_foreign_message")).SetField(foreignC, 119).WeakBuild();
+ message[f("optional_import_message")] =
+ CreateBuilderForField(message, f("optional_import_message")).SetField(importD, 120).WeakBuild();
+
+ message[f("optional_nested_enum")] = nestedBaz;
+ message[f("optional_foreign_enum")] = foreignBaz;
+ message[f("optional_import_enum")] = importBaz;
+
+ message[f("optional_string_piece")] = "124";
+ message[f("optional_cord")] = "125";
+
+ // -----------------------------------------------------------------
+
+ message.WeakAddRepeatedField(f("repeated_int32"), 201);
+ message.WeakAddRepeatedField(f("repeated_int64"), 202L);
+ message.WeakAddRepeatedField(f("repeated_uint32"), 203U);
+ message.WeakAddRepeatedField(f("repeated_uint64"), 204UL);
+ message.WeakAddRepeatedField(f("repeated_sint32"), 205);
+ message.WeakAddRepeatedField(f("repeated_sint64"), 206L);
+ message.WeakAddRepeatedField(f("repeated_fixed32"), 207U);
+ message.WeakAddRepeatedField(f("repeated_fixed64"), 208UL);
+ message.WeakAddRepeatedField(f("repeated_sfixed32"), 209);
+ message.WeakAddRepeatedField(f("repeated_sfixed64"), 210L);
+ message.WeakAddRepeatedField(f("repeated_float"), 211F);
+ message.WeakAddRepeatedField(f("repeated_double"), 212D);
+ message.WeakAddRepeatedField(f("repeated_bool"), true);
+ message.WeakAddRepeatedField(f("repeated_string"), "215");
+ message.WeakAddRepeatedField(f("repeated_bytes"), TestUtil.ToBytes("216"));
+
+
+ message.WeakAddRepeatedField(f("repeatedgroup"),
+ CreateBuilderForField(message, f("repeatedgroup")).SetField(repeatedGroupA, 217)
+ .WeakBuild());
+ message.WeakAddRepeatedField(f("repeated_nested_message"),
+ CreateBuilderForField(message, f("repeated_nested_message")).SetField(nestedB,
+ 218).
+ WeakBuild());
+ message.WeakAddRepeatedField(f("repeated_foreign_message"),
+ CreateBuilderForField(message, f("repeated_foreign_message")).SetField(
+ foreignC, 219).WeakBuild());
+ message.WeakAddRepeatedField(f("repeated_import_message"),
+ CreateBuilderForField(message, f("repeated_import_message")).SetField(importD,
+ 220).
+ WeakBuild());
+
+ message.WeakAddRepeatedField(f("repeated_nested_enum"), nestedBar);
+ message.WeakAddRepeatedField(f("repeated_foreign_enum"), foreignBar);
+ message.WeakAddRepeatedField(f("repeated_import_enum"), importBar);
+
+ message.WeakAddRepeatedField(f("repeated_string_piece"), "224");
+ message.WeakAddRepeatedField(f("repeated_cord"), "225");
+
+ // Add a second one of each field.
+ message.WeakAddRepeatedField(f("repeated_int32"), 301);
+ message.WeakAddRepeatedField(f("repeated_int64"), 302L);
+ message.WeakAddRepeatedField(f("repeated_uint32"), 303U);
+ message.WeakAddRepeatedField(f("repeated_uint64"), 304UL);
+ message.WeakAddRepeatedField(f("repeated_sint32"), 305);
+ message.WeakAddRepeatedField(f("repeated_sint64"), 306L);
+ message.WeakAddRepeatedField(f("repeated_fixed32"), 307U);
+ message.WeakAddRepeatedField(f("repeated_fixed64"), 308UL);
+ message.WeakAddRepeatedField(f("repeated_sfixed32"), 309);
+ message.WeakAddRepeatedField(f("repeated_sfixed64"), 310L);
+ message.WeakAddRepeatedField(f("repeated_float"), 311F);
+ message.WeakAddRepeatedField(f("repeated_double"), 312D);
+ message.WeakAddRepeatedField(f("repeated_bool"), false);
+ message.WeakAddRepeatedField(f("repeated_string"), "315");
+ message.WeakAddRepeatedField(f("repeated_bytes"), TestUtil.ToBytes("316"));
+
+ message.WeakAddRepeatedField(f("repeatedgroup"),
+ CreateBuilderForField(message, f("repeatedgroup"))
+ .SetField(repeatedGroupA, 317).WeakBuild());
+ message.WeakAddRepeatedField(f("repeated_nested_message"),
+ CreateBuilderForField(message, f("repeated_nested_message"))
+ .SetField(nestedB, 318).WeakBuild());
+ message.WeakAddRepeatedField(f("repeated_foreign_message"),
+ CreateBuilderForField(message, f("repeated_foreign_message"))
+ .SetField(foreignC, 319).WeakBuild());
+ message.WeakAddRepeatedField(f("repeated_import_message"),
+ CreateBuilderForField(message, f("repeated_import_message"))
+ .SetField(importD, 320).WeakBuild());
+
+ message.WeakAddRepeatedField(f("repeated_nested_enum"), nestedBaz);
+ message.WeakAddRepeatedField(f("repeated_foreign_enum"), foreignBaz);
+ message.WeakAddRepeatedField(f("repeated_import_enum"), importBaz);
+
+ message.WeakAddRepeatedField(f("repeated_string_piece"), "324");
+ message.WeakAddRepeatedField(f("repeated_cord"), "325");
+
+ // -----------------------------------------------------------------
+
+ message[f("default_int32")] = 401;
+ message[f("default_int64")] = 402L;
+ message[f("default_uint32")] = 403U;
+ message[f("default_uint64")] = 404UL;
+ message[f("default_sint32")] = 405;
+ message[f("default_sint64")] = 406L;
+ message[f("default_fixed32")] = 407U;
+ message[f("default_fixed64")] = 408UL;
+ message[f("default_sfixed32")] = 409;
+ message[f("default_sfixed64")] = 410L;
+ message[f("default_float")] = 411F;
+ message[f("default_double")] = 412D;
+ message[f("default_bool")] = false;
+ message[f("default_string")] = "415";
+ message[f("default_bytes")] = TestUtil.ToBytes("416");
+
+ message[f("default_nested_enum")] = nestedFoo;
+ message[f("default_foreign_enum")] = foreignFoo;
+ message[f("default_import_enum")] = importFoo;
+
+ message[f("default_string_piece")] = "424";
+ message[f("default_cord")] = "425";
+ }
+
+ // -------------------------------------------------------------------
+
+ /// <summary>
+ /// Modify the repeated fields of the specified message to contain the
+ /// values expected by AssertRepeatedFieldsModified, using the IBuilder
+ /// reflection interface.
+ /// </summary>
+ internal void ModifyRepeatedFieldsViaReflection(IBuilder message)
+ {
+ message[f("repeated_int32"), 1] = 501;
+ message[f("repeated_int64"), 1] = 502L;
+ message[f("repeated_uint32"), 1] = 503U;
+ message[f("repeated_uint64"), 1] = 504UL;
+ message[f("repeated_sint32"), 1] = 505;
+ message[f("repeated_sint64"), 1] = 506L;
+ message[f("repeated_fixed32"), 1] = 507U;
+ message[f("repeated_fixed64"), 1] = 508UL;
+ message[f("repeated_sfixed32"), 1] = 509;
+ message[f("repeated_sfixed64"), 1] = 510L;
+ message[f("repeated_float"), 1] = 511F;
+ message[f("repeated_double"), 1] = 512D;
+ message[f("repeated_bool"), 1] = true;
+ message[f("repeated_string"), 1] = "515";
+ message.SetRepeatedField(f("repeated_bytes"), 1, TestUtil.ToBytes("516"));
+
+ message.SetRepeatedField(f("repeatedgroup"), 1,
+ CreateBuilderForField(message, f("repeatedgroup")).SetField(repeatedGroupA, 517).
+ WeakBuild());
+ message.SetRepeatedField(f("repeated_nested_message"), 1,
+ CreateBuilderForField(message, f("repeated_nested_message")).SetField(nestedB, 518)
+ .WeakBuild());
+ message.SetRepeatedField(f("repeated_foreign_message"), 1,
+ CreateBuilderForField(message, f("repeated_foreign_message")).SetField(foreignC,
+ 519).
+ WeakBuild());
+ message.SetRepeatedField(f("repeated_import_message"), 1,
+ CreateBuilderForField(message, f("repeated_import_message")).SetField(importD, 520)
+ .WeakBuild());
+
+ message[f("repeated_nested_enum"), 1] = nestedFoo;
+ message[f("repeated_foreign_enum"), 1] = foreignFoo;
+ message[f("repeated_import_enum"), 1] = importFoo;
+
+ message[f("repeated_string_piece"), 1] = "524";
+ message[f("repeated_cord"), 1] = "525";
+ }
+
+ // -------------------------------------------------------------------
+
+ /// <summary>
+ /// Asserts that all fields of the specified message are set to the values
+ /// assigned by SetAllFields, using the IMessage reflection interface.
+ /// </summary>
+ public void AssertAllFieldsSetViaReflection(IMessage message)
+ {
+ Assert.IsTrue(message.HasField(f("optional_int32")));
+ Assert.IsTrue(message.HasField(f("optional_int64")));
+ Assert.IsTrue(message.HasField(f("optional_uint32")));
+ Assert.IsTrue(message.HasField(f("optional_uint64")));
+ Assert.IsTrue(message.HasField(f("optional_sint32")));
+ Assert.IsTrue(message.HasField(f("optional_sint64")));
+ Assert.IsTrue(message.HasField(f("optional_fixed32")));
+ Assert.IsTrue(message.HasField(f("optional_fixed64")));
+ Assert.IsTrue(message.HasField(f("optional_sfixed32")));
+ Assert.IsTrue(message.HasField(f("optional_sfixed64")));
+ Assert.IsTrue(message.HasField(f("optional_float")));
+ Assert.IsTrue(message.HasField(f("optional_double")));
+ Assert.IsTrue(message.HasField(f("optional_bool")));
+ Assert.IsTrue(message.HasField(f("optional_string")));
+ Assert.IsTrue(message.HasField(f("optional_bytes")));
+
+ Assert.IsTrue(message.HasField(f("optionalgroup")));
+ Assert.IsTrue(message.HasField(f("optional_nested_message")));
+ Assert.IsTrue(message.HasField(f("optional_foreign_message")));
+ Assert.IsTrue(message.HasField(f("optional_import_message")));
+
+ Assert.IsTrue(((IMessage) message[f("optionalgroup")]).HasField(groupA));
+ Assert.IsTrue(((IMessage) message[f("optional_nested_message")]).HasField(nestedB));
+ Assert.IsTrue(((IMessage) message[f("optional_foreign_message")]).HasField(foreignC));
+ Assert.IsTrue(((IMessage) message[f("optional_import_message")]).HasField(importD));
+
+ Assert.IsTrue(message.HasField(f("optional_nested_enum")));
+ Assert.IsTrue(message.HasField(f("optional_foreign_enum")));
+ Assert.IsTrue(message.HasField(f("optional_import_enum")));
+
+ Assert.IsTrue(message.HasField(f("optional_string_piece")));
+ Assert.IsTrue(message.HasField(f("optional_cord")));
+
+ Assert.AreEqual(101, message[f("optional_int32")]);
+ Assert.AreEqual(102L, message[f("optional_int64")]);
+ Assert.AreEqual(103U, message[f("optional_uint32")]);
+ Assert.AreEqual(104UL, message[f("optional_uint64")]);
+ Assert.AreEqual(105, message[f("optional_sint32")]);
+ Assert.AreEqual(106L, message[f("optional_sint64")]);
+ Assert.AreEqual(107U, message[f("optional_fixed32")]);
+ Assert.AreEqual(108UL, message[f("optional_fixed64")]);
+ Assert.AreEqual(109, message[f("optional_sfixed32")]);
+ Assert.AreEqual(110L, message[f("optional_sfixed64")]);
+ Assert.AreEqual(111F, message[f("optional_float")]);
+ Assert.AreEqual(112D, message[f("optional_double")]);
+ Assert.AreEqual(true, message[f("optional_bool")]);
+ Assert.AreEqual("115", message[f("optional_string")]);
+ Assert.AreEqual(TestUtil.ToBytes("116"), message[f("optional_bytes")]);
+
+ Assert.AreEqual(117, ((IMessage) message[f("optionalgroup")])[groupA]);
+ Assert.AreEqual(118, ((IMessage) message[f("optional_nested_message")])[nestedB]);
+ Assert.AreEqual(119, ((IMessage) message[f("optional_foreign_message")])[foreignC]);
+ Assert.AreEqual(120, ((IMessage) message[f("optional_import_message")])[importD]);
+
+ Assert.AreEqual(nestedBaz, message[f("optional_nested_enum")]);
+ Assert.AreEqual(foreignBaz, message[f("optional_foreign_enum")]);
+ Assert.AreEqual(importBaz, message[f("optional_import_enum")]);
+
+ Assert.AreEqual("124", message[f("optional_string_piece")]);
+ Assert.AreEqual("125", message[f("optional_cord")]);
+
+ // -----------------------------------------------------------------
+
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_int32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_int64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_uint32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_uint64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sint32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sint64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_fixed32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_fixed64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sfixed32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sfixed64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_float")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_double")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_bool")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_string")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_bytes")));
+
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeatedgroup")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_nested_message")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_foreign_message")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_import_message")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_nested_enum")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_foreign_enum")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_import_enum")));
+
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_string_piece")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_cord")));
+
+ Assert.AreEqual(201, message[f("repeated_int32"), 0]);
+ Assert.AreEqual(202L, message[f("repeated_int64"), 0]);
+ Assert.AreEqual(203U, message[f("repeated_uint32"), 0]);
+ Assert.AreEqual(204UL, message[f("repeated_uint64"), 0]);
+ Assert.AreEqual(205, message[f("repeated_sint32"), 0]);
+ Assert.AreEqual(206L, message[f("repeated_sint64"), 0]);
+ Assert.AreEqual(207U, message[f("repeated_fixed32"), 0]);
+ Assert.AreEqual(208UL, message[f("repeated_fixed64"), 0]);
+ Assert.AreEqual(209, message[f("repeated_sfixed32"), 0]);
+ Assert.AreEqual(210L, message[f("repeated_sfixed64"), 0]);
+ Assert.AreEqual(211F, message[f("repeated_float"), 0]);
+ Assert.AreEqual(212D, message[f("repeated_double"), 0]);
+ Assert.AreEqual(true, message[f("repeated_bool"), 0]);
+ Assert.AreEqual("215", message[f("repeated_string"), 0]);
+ Assert.AreEqual(TestUtil.ToBytes("216"), message[f("repeated_bytes"), 0]);
+
+ Assert.AreEqual(217, ((IMessage) message[f("repeatedgroup"), 0])[repeatedGroupA]);
+ Assert.AreEqual(218, ((IMessage) message[f("repeated_nested_message"), 0])[nestedB]);
+ Assert.AreEqual(219, ((IMessage) message[f("repeated_foreign_message"), 0])[foreignC]);
+ Assert.AreEqual(220, ((IMessage) message[f("repeated_import_message"), 0])[importD]);
+
+ Assert.AreEqual(nestedBar, message[f("repeated_nested_enum"), 0]);
+ Assert.AreEqual(foreignBar, message[f("repeated_foreign_enum"), 0]);
+ Assert.AreEqual(importBar, message[f("repeated_import_enum"), 0]);
+
+ Assert.AreEqual("224", message[f("repeated_string_piece"), 0]);
+ Assert.AreEqual("225", message[f("repeated_cord"), 0]);
+
+ Assert.AreEqual(301, message[f("repeated_int32"), 1]);
+ Assert.AreEqual(302L, message[f("repeated_int64"), 1]);
+ Assert.AreEqual(303U, message[f("repeated_uint32"), 1]);
+ Assert.AreEqual(304UL, message[f("repeated_uint64"), 1]);
+ Assert.AreEqual(305, message[f("repeated_sint32"), 1]);
+ Assert.AreEqual(306L, message[f("repeated_sint64"), 1]);
+ Assert.AreEqual(307U, message[f("repeated_fixed32"), 1]);
+ Assert.AreEqual(308UL, message[f("repeated_fixed64"), 1]);
+ Assert.AreEqual(309, message[f("repeated_sfixed32"), 1]);
+ Assert.AreEqual(310L, message[f("repeated_sfixed64"), 1]);
+ Assert.AreEqual(311F, message[f("repeated_float"), 1]);
+ Assert.AreEqual(312D, message[f("repeated_double"), 1]);
+ Assert.AreEqual(false, message[f("repeated_bool"), 1]);
+ Assert.AreEqual("315", message[f("repeated_string"), 1]);
+ Assert.AreEqual(TestUtil.ToBytes("316"), message[f("repeated_bytes"), 1]);
+
+ Assert.AreEqual(317, ((IMessage) message[f("repeatedgroup"), 1])[repeatedGroupA]);
+ Assert.AreEqual(318, ((IMessage) message[f("repeated_nested_message"), 1])[nestedB]);
+ Assert.AreEqual(319, ((IMessage) message[f("repeated_foreign_message"), 1])[foreignC]);
+ Assert.AreEqual(320, ((IMessage) message[f("repeated_import_message"), 1])[importD]);
+
+ Assert.AreEqual(nestedBaz, message[f("repeated_nested_enum"), 1]);
+ Assert.AreEqual(foreignBaz, message[f("repeated_foreign_enum"), 1]);
+ Assert.AreEqual(importBaz, message[f("repeated_import_enum"), 1]);
+
+ Assert.AreEqual("324", message[f("repeated_string_piece"), 1]);
+ Assert.AreEqual("325", message[f("repeated_cord"), 1]);
+
+ // -----------------------------------------------------------------
+
+ Assert.IsTrue(message.HasField(f("default_int32")));
+ Assert.IsTrue(message.HasField(f("default_int64")));
+ Assert.IsTrue(message.HasField(f("default_uint32")));
+ Assert.IsTrue(message.HasField(f("default_uint64")));
+ Assert.IsTrue(message.HasField(f("default_sint32")));
+ Assert.IsTrue(message.HasField(f("default_sint64")));
+ Assert.IsTrue(message.HasField(f("default_fixed32")));
+ Assert.IsTrue(message.HasField(f("default_fixed64")));
+ Assert.IsTrue(message.HasField(f("default_sfixed32")));
+ Assert.IsTrue(message.HasField(f("default_sfixed64")));
+ Assert.IsTrue(message.HasField(f("default_float")));
+ Assert.IsTrue(message.HasField(f("default_double")));
+ Assert.IsTrue(message.HasField(f("default_bool")));
+ Assert.IsTrue(message.HasField(f("default_string")));
+ Assert.IsTrue(message.HasField(f("default_bytes")));
+
+ Assert.IsTrue(message.HasField(f("default_nested_enum")));
+ Assert.IsTrue(message.HasField(f("default_foreign_enum")));
+ Assert.IsTrue(message.HasField(f("default_import_enum")));
+
+ Assert.IsTrue(message.HasField(f("default_string_piece")));
+ Assert.IsTrue(message.HasField(f("default_cord")));
+
+ Assert.AreEqual(401, message[f("default_int32")]);
+ Assert.AreEqual(402L, message[f("default_int64")]);
+ Assert.AreEqual(403U, message[f("default_uint32")]);
+ Assert.AreEqual(404UL, message[f("default_uint64")]);
+ Assert.AreEqual(405, message[f("default_sint32")]);
+ Assert.AreEqual(406L, message[f("default_sint64")]);
+ Assert.AreEqual(407U, message[f("default_fixed32")]);
+ Assert.AreEqual(408UL, message[f("default_fixed64")]);
+ Assert.AreEqual(409, message[f("default_sfixed32")]);
+ Assert.AreEqual(410L, message[f("default_sfixed64")]);
+ Assert.AreEqual(411F, message[f("default_float")]);
+ Assert.AreEqual(412D, message[f("default_double")]);
+ Assert.AreEqual(false, message[f("default_bool")]);
+ Assert.AreEqual("415", message[f("default_string")]);
+ Assert.AreEqual(TestUtil.ToBytes("416"), message[f("default_bytes")]);
+
+ Assert.AreEqual(nestedFoo, message[f("default_nested_enum")]);
+ Assert.AreEqual(foreignFoo, message[f("default_foreign_enum")]);
+ Assert.AreEqual(importFoo, message[f("default_import_enum")]);
+
+ Assert.AreEqual("424", message[f("default_string_piece")]);
+ Assert.AreEqual("425", message[f("default_cord")]);
+ }
+
+ /// <summary>
+ /// Assert that all fields of the message are cleared, and that
+ /// getting the fields returns their default values, using the reflection interface.
+ /// </summary>
+ public void AssertClearViaReflection(IMessage message)
+ {
+ // has_blah() should initially be false for all optional fields.
+ Assert.IsFalse(message.HasField(f("optional_int32")));
+ Assert.IsFalse(message.HasField(f("optional_int64")));
+ Assert.IsFalse(message.HasField(f("optional_uint32")));
+ Assert.IsFalse(message.HasField(f("optional_uint64")));
+ Assert.IsFalse(message.HasField(f("optional_sint32")));
+ Assert.IsFalse(message.HasField(f("optional_sint64")));
+ Assert.IsFalse(message.HasField(f("optional_fixed32")));
+ Assert.IsFalse(message.HasField(f("optional_fixed64")));
+ Assert.IsFalse(message.HasField(f("optional_sfixed32")));
+ Assert.IsFalse(message.HasField(f("optional_sfixed64")));
+ Assert.IsFalse(message.HasField(f("optional_float")));
+ Assert.IsFalse(message.HasField(f("optional_double")));
+ Assert.IsFalse(message.HasField(f("optional_bool")));
+ Assert.IsFalse(message.HasField(f("optional_string")));
+ Assert.IsFalse(message.HasField(f("optional_bytes")));
+
+ Assert.IsFalse(message.HasField(f("optionalgroup")));
+ Assert.IsFalse(message.HasField(f("optional_nested_message")));
+ Assert.IsFalse(message.HasField(f("optional_foreign_message")));
+ Assert.IsFalse(message.HasField(f("optional_import_message")));
+
+ Assert.IsFalse(message.HasField(f("optional_nested_enum")));
+ Assert.IsFalse(message.HasField(f("optional_foreign_enum")));
+ Assert.IsFalse(message.HasField(f("optional_import_enum")));
+
+ Assert.IsFalse(message.HasField(f("optional_string_piece")));
+ Assert.IsFalse(message.HasField(f("optional_cord")));
+
+ // Optional fields without defaults are set to zero or something like it.
+ Assert.AreEqual(0, message[f("optional_int32")]);
+ Assert.AreEqual(0L, message[f("optional_int64")]);
+ Assert.AreEqual(0U, message[f("optional_uint32")]);
+ Assert.AreEqual(0UL, message[f("optional_uint64")]);
+ Assert.AreEqual(0, message[f("optional_sint32")]);
+ Assert.AreEqual(0L, message[f("optional_sint64")]);
+ Assert.AreEqual(0U, message[f("optional_fixed32")]);
+ Assert.AreEqual(0UL, message[f("optional_fixed64")]);
+ Assert.AreEqual(0, message[f("optional_sfixed32")]);
+ Assert.AreEqual(0L, message[f("optional_sfixed64")]);
+ Assert.AreEqual(0F, message[f("optional_float")]);
+ Assert.AreEqual(0D, message[f("optional_double")]);
+ Assert.AreEqual(false, message[f("optional_bool")]);
+ Assert.AreEqual("", message[f("optional_string")]);
+ Assert.AreEqual(ByteString.Empty, message[f("optional_bytes")]);
+
+ // Embedded messages should also be clear.
+ Assert.IsFalse(((IMessage) message[f("optionalgroup")]).HasField(groupA));
+ Assert.IsFalse(((IMessage) message[f("optional_nested_message")])
+ .HasField(nestedB));
+ Assert.IsFalse(((IMessage) message[f("optional_foreign_message")])
+ .HasField(foreignC));
+ Assert.IsFalse(((IMessage) message[f("optional_import_message")])
+ .HasField(importD));
+
+ Assert.AreEqual(0, ((IMessage) message[f("optionalgroup")])[groupA]);
+ Assert.AreEqual(0, ((IMessage) message[f("optional_nested_message")])[nestedB]);
+ Assert.AreEqual(0, ((IMessage) message[f("optional_foreign_message")])[foreignC]);
+ Assert.AreEqual(0, ((IMessage) message[f("optional_import_message")])[importD]);
+
+ // Enums without defaults are set to the first value in the enum.
+ Assert.AreEqual(nestedFoo, message[f("optional_nested_enum")]);
+ Assert.AreEqual(foreignFoo, message[f("optional_foreign_enum")]);
+ Assert.AreEqual(importFoo, message[f("optional_import_enum")]);
+
+ Assert.AreEqual("", message[f("optional_string_piece")]);
+ Assert.AreEqual("", message[f("optional_cord")]);
+
+ // Repeated fields are empty.
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_int32")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_int64")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_uint32")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_uint64")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_sint32")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_sint64")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_fixed32")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_fixed64")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_sfixed32")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_sfixed64")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_float")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_double")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_bool")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_string")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_bytes")));
+
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeatedgroup")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_nested_message")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_foreign_message")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_import_message")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_nested_enum")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_foreign_enum")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_import_enum")));
+
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_string_piece")));
+ Assert.AreEqual(0, message.GetRepeatedFieldCount(f("repeated_cord")));
+
+ // has_blah() should also be false for all default fields.
+ Assert.IsFalse(message.HasField(f("default_int32")));
+ Assert.IsFalse(message.HasField(f("default_int64")));
+ Assert.IsFalse(message.HasField(f("default_uint32")));
+ Assert.IsFalse(message.HasField(f("default_uint64")));
+ Assert.IsFalse(message.HasField(f("default_sint32")));
+ Assert.IsFalse(message.HasField(f("default_sint64")));
+ Assert.IsFalse(message.HasField(f("default_fixed32")));
+ Assert.IsFalse(message.HasField(f("default_fixed64")));
+ Assert.IsFalse(message.HasField(f("default_sfixed32")));
+ Assert.IsFalse(message.HasField(f("default_sfixed64")));
+ Assert.IsFalse(message.HasField(f("default_float")));
+ Assert.IsFalse(message.HasField(f("default_double")));
+ Assert.IsFalse(message.HasField(f("default_bool")));
+ Assert.IsFalse(message.HasField(f("default_string")));
+ Assert.IsFalse(message.HasField(f("default_bytes")));
+
+ Assert.IsFalse(message.HasField(f("default_nested_enum")));
+ Assert.IsFalse(message.HasField(f("default_foreign_enum")));
+ Assert.IsFalse(message.HasField(f("default_import_enum")));
+
+ Assert.IsFalse(message.HasField(f("default_string_piece")));
+ Assert.IsFalse(message.HasField(f("default_cord")));
+
+ // Fields with defaults have their default values (duh).
+ Assert.AreEqual(41, message[f("default_int32")]);
+ Assert.AreEqual(42L, message[f("default_int64")]);
+ Assert.AreEqual(43U, message[f("default_uint32")]);
+ Assert.AreEqual(44UL, message[f("default_uint64")]);
+ Assert.AreEqual(-45, message[f("default_sint32")]);
+ Assert.AreEqual(46L, message[f("default_sint64")]);
+ Assert.AreEqual(47U, message[f("default_fixed32")]);
+ Assert.AreEqual(48UL, message[f("default_fixed64")]);
+ Assert.AreEqual(49, message[f("default_sfixed32")]);
+ Assert.AreEqual(-50L, message[f("default_sfixed64")]);
+ Assert.AreEqual(51.5F, message[f("default_float")]);
+ Assert.AreEqual(52e3D, message[f("default_double")]);
+ Assert.AreEqual(true, message[f("default_bool")]);
+ Assert.AreEqual("hello", message[f("default_string")]);
+ Assert.AreEqual(TestUtil.ToBytes("world"), message[f("default_bytes")]);
+
+ Assert.AreEqual(nestedBar, message[f("default_nested_enum")]);
+ Assert.AreEqual(foreignBar, message[f("default_foreign_enum")]);
+ Assert.AreEqual(importBar, message[f("default_import_enum")]);
+
+ Assert.AreEqual("abc", message[f("default_string_piece")]);
+ Assert.AreEqual("123", message[f("default_cord")]);
+ }
+
+ // ---------------------------------------------------------------
+
+ internal void AssertRepeatedFieldsModifiedViaReflection(IMessage message)
+ {
+ // ModifyRepeatedFields only sets the second repeated element of each
+ // field. In addition to verifying this, we also verify that the first
+ // element and size were *not* modified.
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_int32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_int64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_uint32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_uint64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sint32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sint64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_fixed32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_fixed64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sfixed32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_sfixed64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_float")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_double")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_bool")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_string")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_bytes")));
+
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeatedgroup")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_nested_message")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_foreign_message")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_import_message")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_nested_enum")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_foreign_enum")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_import_enum")));
+
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_string_piece")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("repeated_cord")));
+
+ Assert.AreEqual(201, message[f("repeated_int32"), 0]);
+ Assert.AreEqual(202L, message[f("repeated_int64"), 0]);
+ Assert.AreEqual(203U, message[f("repeated_uint32"), 0]);
+ Assert.AreEqual(204UL, message[f("repeated_uint64"), 0]);
+ Assert.AreEqual(205, message[f("repeated_sint32"), 0]);
+ Assert.AreEqual(206L, message[f("repeated_sint64"), 0]);
+ Assert.AreEqual(207U, message[f("repeated_fixed32"), 0]);
+ Assert.AreEqual(208UL, message[f("repeated_fixed64"), 0]);
+ Assert.AreEqual(209, message[f("repeated_sfixed32"), 0]);
+ Assert.AreEqual(210L, message[f("repeated_sfixed64"), 0]);
+ Assert.AreEqual(211F, message[f("repeated_float"), 0]);
+ Assert.AreEqual(212D, message[f("repeated_double"), 0]);
+ Assert.AreEqual(true, message[f("repeated_bool"), 0]);
+ Assert.AreEqual("215", message[f("repeated_string"), 0]);
+ Assert.AreEqual(TestUtil.ToBytes("216"), message[f("repeated_bytes"), 0]);
+
+ Assert.AreEqual(217, ((IMessage) message[f("repeatedgroup"), 0])[repeatedGroupA]);
+ Assert.AreEqual(218, ((IMessage) message[f("repeated_nested_message"), 0])[nestedB]);
+ Assert.AreEqual(219, ((IMessage) message[f("repeated_foreign_message"), 0])[foreignC]);
+ Assert.AreEqual(220, ((IMessage) message[f("repeated_import_message"), 0])[importD]);
+
+ Assert.AreEqual(nestedBar, message[f("repeated_nested_enum"), 0]);
+ Assert.AreEqual(foreignBar, message[f("repeated_foreign_enum"), 0]);
+ Assert.AreEqual(importBar, message[f("repeated_import_enum"), 0]);
+
+ Assert.AreEqual("224", message[f("repeated_string_piece"), 0]);
+ Assert.AreEqual("225", message[f("repeated_cord"), 0]);
+
+ Assert.AreEqual(501, message[f("repeated_int32"), 1]);
+ Assert.AreEqual(502L, message[f("repeated_int64"), 1]);
+ Assert.AreEqual(503U, message[f("repeated_uint32"), 1]);
+ Assert.AreEqual(504UL, message[f("repeated_uint64"), 1]);
+ Assert.AreEqual(505, message[f("repeated_sint32"), 1]);
+ Assert.AreEqual(506L, message[f("repeated_sint64"), 1]);
+ Assert.AreEqual(507U, message[f("repeated_fixed32"), 1]);
+ Assert.AreEqual(508UL, message[f("repeated_fixed64"), 1]);
+ Assert.AreEqual(509, message[f("repeated_sfixed32"), 1]);
+ Assert.AreEqual(510L, message[f("repeated_sfixed64"), 1]);
+ Assert.AreEqual(511F, message[f("repeated_float"), 1]);
+ Assert.AreEqual(512D, message[f("repeated_double"), 1]);
+ Assert.AreEqual(true, message[f("repeated_bool"), 1]);
+ Assert.AreEqual("515", message[f("repeated_string"), 1]);
+ Assert.AreEqual(TestUtil.ToBytes("516"), message[f("repeated_bytes"), 1]);
+
+ Assert.AreEqual(517, ((IMessage) message[f("repeatedgroup"), 1])[repeatedGroupA]);
+ Assert.AreEqual(518, ((IMessage) message[f("repeated_nested_message"), 1])[nestedB]);
+ Assert.AreEqual(519, ((IMessage) message[f("repeated_foreign_message"), 1])[foreignC]);
+ Assert.AreEqual(520, ((IMessage) message[f("repeated_import_message"), 1])[importD]);
+
+ Assert.AreEqual(nestedFoo, message[f("repeated_nested_enum"), 1]);
+ Assert.AreEqual(foreignFoo, message[f("repeated_foreign_enum"), 1]);
+ Assert.AreEqual(importFoo, message[f("repeated_import_enum"), 1]);
+
+ Assert.AreEqual("524", message[f("repeated_string_piece"), 1]);
+ Assert.AreEqual("525", message[f("repeated_cord"), 1]);
+ }
+
+ /// <summary>
+ /// Verifies that the reflection setters for the given Builder object throw an
+ /// ArgumentNullException if they are passed a null value.
+ /// </summary>
+ public void AssertReflectionSettersRejectNull(IBuilder builder)
+ {
+ TestUtil.AssertArgumentNullException(() => builder[f("optional_string")] = null);
+ TestUtil.AssertArgumentNullException(() => builder[f("optional_bytes")] = null);
+ TestUtil.AssertArgumentNullException(() => builder[f("optional_nested_enum")] = null);
+ TestUtil.AssertArgumentNullException(() => builder[f("optional_nested_message")] = null);
+ TestUtil.AssertArgumentNullException(() => builder[f("optional_nested_message")] = null);
+ TestUtil.AssertArgumentNullException(() => builder.WeakAddRepeatedField(f("repeated_string"), null));
+ TestUtil.AssertArgumentNullException(() => builder.WeakAddRepeatedField(f("repeated_bytes"), null));
+ TestUtil.AssertArgumentNullException(() => builder.WeakAddRepeatedField(f("repeated_nested_enum"), null));
+ TestUtil.AssertArgumentNullException(() => builder.WeakAddRepeatedField(f("repeated_nested_message"), null));
+ }
+
+ /// <summary>
+ /// Verifies that the reflection repeated setters for the given Builder object throw an
+ /// ArgumentNullException if they are passed a null value.
+ /// </summary>
+ public void AssertReflectionRepeatedSettersRejectNull(IBuilder builder)
+ {
+ builder.WeakAddRepeatedField(f("repeated_string"), "one");
+ TestUtil.AssertArgumentNullException(() => builder.SetRepeatedField(f("repeated_string"), 0, null));
+ builder.WeakAddRepeatedField(f("repeated_bytes"), TestUtil.ToBytes("one"));
+ TestUtil.AssertArgumentNullException(() => builder.SetRepeatedField(f("repeated_bytes"), 0, null));
+ builder.WeakAddRepeatedField(f("repeated_nested_enum"), nestedBaz);
+ TestUtil.AssertArgumentNullException(() => builder.SetRepeatedField(f("repeated_nested_enum"), 0, null));
+ builder.WeakAddRepeatedField(f("repeated_nested_message"),
+ new TestAllTypes.Types.NestedMessage.Builder {Bb = 218}.Build());
+ TestUtil.AssertArgumentNullException(() => builder.SetRepeatedField(f("repeated_nested_message"), 0, null));
+ }
+
+ public void SetPackedFieldsViaReflection(IBuilder message)
+ {
+ message.WeakAddRepeatedField(f("packed_int32"), 601);
+ message.WeakAddRepeatedField(f("packed_int64"), 602L);
+ message.WeakAddRepeatedField(f("packed_uint32"), 603U);
+ message.WeakAddRepeatedField(f("packed_uint64"), 604UL);
+ message.WeakAddRepeatedField(f("packed_sint32"), 605);
+ message.WeakAddRepeatedField(f("packed_sint64"), 606L);
+ message.WeakAddRepeatedField(f("packed_fixed32"), 607U);
+ message.WeakAddRepeatedField(f("packed_fixed64"), 608UL);
+ message.WeakAddRepeatedField(f("packed_sfixed32"), 609);
+ message.WeakAddRepeatedField(f("packed_sfixed64"), 610L);
+ message.WeakAddRepeatedField(f("packed_float"), 611F);
+ message.WeakAddRepeatedField(f("packed_double"), 612D);
+ message.WeakAddRepeatedField(f("packed_bool"), true);
+ message.WeakAddRepeatedField(f("packed_enum"), foreignBar);
+ // Add a second one of each field.
+ message.WeakAddRepeatedField(f("packed_int32"), 701);
+ message.WeakAddRepeatedField(f("packed_int64"), 702L);
+ message.WeakAddRepeatedField(f("packed_uint32"), 703U);
+ message.WeakAddRepeatedField(f("packed_uint64"), 704UL);
+ message.WeakAddRepeatedField(f("packed_sint32"), 705);
+ message.WeakAddRepeatedField(f("packed_sint64"), 706L);
+ message.WeakAddRepeatedField(f("packed_fixed32"), 707U);
+ message.WeakAddRepeatedField(f("packed_fixed64"), 708UL);
+ message.WeakAddRepeatedField(f("packed_sfixed32"), 709);
+ message.WeakAddRepeatedField(f("packed_sfixed64"), 710L);
+ message.WeakAddRepeatedField(f("packed_float"), 711F);
+ message.WeakAddRepeatedField(f("packed_double"), 712D);
+ message.WeakAddRepeatedField(f("packed_bool"), false);
+ message.WeakAddRepeatedField(f("packed_enum"), foreignBaz);
+ }
+
+ public void AssertPackedFieldsSetViaReflection(IMessage message)
+ {
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_int32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_int64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_uint32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_uint64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_sint32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_sint64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_fixed32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_fixed64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_sfixed32")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_sfixed64")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_float")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_double")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_bool")));
+ Assert.AreEqual(2, message.GetRepeatedFieldCount(f("packed_enum")));
+ Assert.AreEqual(601, message[f("packed_int32"), 0]);
+ Assert.AreEqual(602L, message[f("packed_int64"), 0]);
+ Assert.AreEqual(603, message[f("packed_uint32"), 0]);
+ Assert.AreEqual(604L, message[f("packed_uint64"), 0]);
+ Assert.AreEqual(605, message[f("packed_sint32"), 0]);
+ Assert.AreEqual(606L, message[f("packed_sint64"), 0]);
+ Assert.AreEqual(607, message[f("packed_fixed32"), 0]);
+ Assert.AreEqual(608L, message[f("packed_fixed64"), 0]);
+ Assert.AreEqual(609, message[f("packed_sfixed32"), 0]);
+ Assert.AreEqual(610L, message[f("packed_sfixed64"), 0]);
+ Assert.AreEqual(611F, message[f("packed_float"), 0]);
+ Assert.AreEqual(612D, message[f("packed_double"), 0]);
+ Assert.AreEqual(true, message[f("packed_bool"), 0]);
+ Assert.AreEqual(foreignBar, message[f("packed_enum"), 0]);
+ Assert.AreEqual(701, message[f("packed_int32"), 1]);
+ Assert.AreEqual(702L, message[f("packed_int64"), 1]);
+ Assert.AreEqual(703, message[f("packed_uint32"), 1]);
+ Assert.AreEqual(704L, message[f("packed_uint64"), 1]);
+ Assert.AreEqual(705, message[f("packed_sint32"), 1]);
+ Assert.AreEqual(706L, message[f("packed_sint64"), 1]);
+ Assert.AreEqual(707, message[f("packed_fixed32"), 1]);
+ Assert.AreEqual(708L, message[f("packed_fixed64"), 1]);
+ Assert.AreEqual(709, message[f("packed_sfixed32"), 1]);
+ Assert.AreEqual(710L, message[f("packed_sfixed64"), 1]);
+ Assert.AreEqual(711F, message[f("packed_float"), 1]);
+ Assert.AreEqual(712D, message[f("packed_double"), 1]);
+ Assert.AreEqual(false, message[f("packed_bool"), 1]);
+ Assert.AreEqual(foreignBaz, message[f("packed_enum"), 1]);
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/ServiceTest.cs b/src/ProtocolBuffers.Test/ServiceTest.cs index 579c4582..dbfa10c9 100644 --- a/src/ProtocolBuffers.Test/ServiceTest.cs +++ b/src/ProtocolBuffers.Test/ServiceTest.cs @@ -1,198 +1,216 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; -using Rhino.Mocks; -using Rhino.Mocks.Constraints; - -namespace Google.ProtocolBuffers { - - /// <summary> - /// Tests for generated service classes. - /// TODO(jonskeet): Convert the mocking tests using Rhino.Mocks. - /// </summary> - [TestFixture] - public class ServiceTest { - - delegate void Action<T1, T2>(T1 t1, T2 t2); - - private static readonly MethodDescriptor FooDescriptor = TestGenericService.Descriptor.Methods[0];
- private static readonly MethodDescriptor BarDescriptor = TestGenericService.Descriptor.Methods[1]; - - [Test] - public void GetRequestPrototype() { - TestGenericService service = new TestServiceImpl(); - - Assert.AreSame(service.GetRequestPrototype(FooDescriptor), FooRequest.DefaultInstance); - Assert.AreSame(service.GetRequestPrototype(BarDescriptor), BarRequest.DefaultInstance); - } - - [Test] - public void GetResponsePrototype() { - TestGenericService service = new TestServiceImpl(); - - Assert.AreSame(service.GetResponsePrototype(FooDescriptor), FooResponse.DefaultInstance); - Assert.AreSame(service.GetResponsePrototype(BarDescriptor), BarResponse.DefaultInstance); - } - - [Test] - public void CallMethodFoo() { - MockRepository mocks = new MockRepository();
- FooRequest fooRequest = FooRequest.CreateBuilder().Build();
- FooResponse fooResponse = FooResponse.CreateBuilder().Build(); - IRpcController controller = mocks.StrictMock<IRpcController>(); - - bool fooCalled = false; - - TestGenericService service = new TestServiceImpl((request, responseAction) => { - Assert.AreSame(fooRequest, request); - fooCalled = true; - responseAction(fooResponse); - }, null, controller); - - bool doneHandlerCalled = false; - Action<IMessage> doneHandler = (response => { - Assert.AreSame(fooResponse, response); - doneHandlerCalled = true; - }); - - using (mocks.Record()) { - // No mock interactions to record - } - - service.CallMethod(FooDescriptor, controller, fooRequest, doneHandler); - - Assert.IsTrue(doneHandlerCalled); - Assert.IsTrue(fooCalled); - mocks.VerifyAll(); - } - - delegate void CallFooDelegate(MethodDescriptor descriptor, IRpcController controller, - IMessage request, IMessage response, Action<IMessage> doneHandler); - - /// <summary> - /// Tests the generated stub handling of Foo. By this stage we're reasonably confident - /// that the choice between Foo and Bar is arbitrary, hence the lack of a corresponding Bar - /// test. - /// </summary> - [Test] - [Ignore("Crashes Mono - needs further investigation")] - public void GeneratedStubFooCall() { - FooRequest fooRequest = FooRequest.CreateBuilder().Build(); - MockRepository mocks = new MockRepository(); - IRpcChannel mockChannel = mocks.StrictMock<IRpcChannel>(); - IRpcController mockController = mocks.StrictMock<IRpcController>();
- TestGenericService service = TestGenericService.CreateStub(mockChannel);
- Action<FooResponse> doneHandler = mocks.StrictMock<Action<FooResponse>>(); - - using (mocks.Record()) { - - // Nasty way of mocking out "the channel calls the done handler". - Expect.Call(() => mockChannel.CallMethod(null, null, null, null, null)) - .IgnoreArguments() - .Constraints(Is.Same(FooDescriptor), Is.Same(mockController), Is.Same(fooRequest), - Is.Same(FooResponse.DefaultInstance), Is.Anything()) - .Do((CallFooDelegate) ((p1, p2, p3, response, done) => done(response)));
- doneHandler(FooResponse.DefaultInstance); - } - - service.Foo(mockController, fooRequest, doneHandler); - - mocks.VerifyAll(); - } - - [Test] - public void CallMethodBar() { - MockRepository mocks = new MockRepository();
- BarRequest barRequest = BarRequest.CreateBuilder().Build();
- BarResponse barResponse = BarResponse.CreateBuilder().Build(); - IRpcController controller = mocks.StrictMock<IRpcController>(); - - bool barCalled = false; - - TestGenericService service = new TestServiceImpl(null, (request, responseAction) => { - Assert.AreSame(barRequest, request); - barCalled = true; - responseAction(barResponse); - }, controller); - - bool doneHandlerCalled = false; - Action<IMessage> doneHandler = (response => { - Assert.AreSame(barResponse, response); - doneHandlerCalled = true; - }); - - using (mocks.Record()) { - // No mock interactions to record - } - - service.CallMethod(BarDescriptor, controller, barRequest, doneHandler); - - Assert.IsTrue(doneHandlerCalled); - Assert.IsTrue(barCalled); - mocks.VerifyAll(); - } - - - class TestServiceImpl : TestGenericService { - private readonly Action<FooRequest, Action<FooResponse>> fooHandler; - private readonly Action<BarRequest, Action<BarResponse>> barHandler; - private readonly IRpcController expectedController; - - internal TestServiceImpl() { - }
-
- internal TestServiceImpl(Action<FooRequest, Action<FooResponse>> fooHandler,
- Action<BarRequest, Action<BarResponse>> barHandler, - IRpcController expectedController) { - this.fooHandler = fooHandler; - this.barHandler = barHandler; - this.expectedController = expectedController; - } - - public override void Foo(IRpcController controller, FooRequest request, Action<FooResponse> done) { - Assert.AreSame(expectedController, controller); - fooHandler(request, done); - } - - public override void Bar(IRpcController controller, BarRequest request, Action<BarResponse> done) { - Assert.AreSame(expectedController, controller); - barHandler(request, done); - } - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System;
+using Google.ProtocolBuffers.Descriptors;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+using Rhino.Mocks;
+using Rhino.Mocks.Constraints;
+
+namespace Google.ProtocolBuffers
+{
+ /// <summary>
+ /// Tests for generated service classes.
+ /// TODO(jonskeet): Convert the mocking tests using Rhino.Mocks.
+ /// </summary>
+ [TestFixture]
+ public class ServiceTest
+ {
+ private delegate void Action<T1, T2>(T1 t1, T2 t2);
+
+ private static readonly MethodDescriptor FooDescriptor = TestGenericService.Descriptor.Methods[0];
+ private static readonly MethodDescriptor BarDescriptor = TestGenericService.Descriptor.Methods[1];
+
+ [Test]
+ public void GetRequestPrototype()
+ {
+ TestGenericService service = new TestServiceImpl();
+
+ Assert.AreSame(service.GetRequestPrototype(FooDescriptor), FooRequest.DefaultInstance);
+ Assert.AreSame(service.GetRequestPrototype(BarDescriptor), BarRequest.DefaultInstance);
+ }
+
+ [Test]
+ public void GetResponsePrototype()
+ {
+ TestGenericService service = new TestServiceImpl();
+
+ Assert.AreSame(service.GetResponsePrototype(FooDescriptor), FooResponse.DefaultInstance);
+ Assert.AreSame(service.GetResponsePrototype(BarDescriptor), BarResponse.DefaultInstance);
+ }
+
+ [Test]
+ public void CallMethodFoo()
+ {
+ MockRepository mocks = new MockRepository();
+ FooRequest fooRequest = FooRequest.CreateBuilder().Build();
+ FooResponse fooResponse = FooResponse.CreateBuilder().Build();
+ IRpcController controller = mocks.StrictMock<IRpcController>();
+
+ bool fooCalled = false;
+
+ TestGenericService service = new TestServiceImpl((request, responseAction) =>
+ {
+ Assert.AreSame(fooRequest, request);
+ fooCalled = true;
+ responseAction(fooResponse);
+ }, null, controller);
+
+ bool doneHandlerCalled = false;
+ Action<IMessage> doneHandler = (response =>
+ {
+ Assert.AreSame(fooResponse, response);
+ doneHandlerCalled = true;
+ });
+
+ using (mocks.Record())
+ {
+ // No mock interactions to record
+ }
+
+ service.CallMethod(FooDescriptor, controller, fooRequest, doneHandler);
+
+ Assert.IsTrue(doneHandlerCalled);
+ Assert.IsTrue(fooCalled);
+ mocks.VerifyAll();
+ }
+
+ private delegate void CallFooDelegate(MethodDescriptor descriptor, IRpcController controller,
+ IMessage request, IMessage response, Action<IMessage> doneHandler);
+
+ /// <summary>
+ /// Tests the generated stub handling of Foo. By this stage we're reasonably confident
+ /// that the choice between Foo and Bar is arbitrary, hence the lack of a corresponding Bar
+ /// test.
+ /// </summary>
+ [Test]
+ [Ignore("Crashes Mono - needs further investigation")]
+ public void GeneratedStubFooCall()
+ {
+ FooRequest fooRequest = FooRequest.CreateBuilder().Build();
+ MockRepository mocks = new MockRepository();
+ IRpcChannel mockChannel = mocks.StrictMock<IRpcChannel>();
+ IRpcController mockController = mocks.StrictMock<IRpcController>();
+ TestGenericService service = TestGenericService.CreateStub(mockChannel);
+ Action<FooResponse> doneHandler = mocks.StrictMock<Action<FooResponse>>();
+
+ using (mocks.Record())
+ {
+ // Nasty way of mocking out "the channel calls the done handler".
+ Expect.Call(() => mockChannel.CallMethod(null, null, null, null, null))
+ .IgnoreArguments()
+ .Constraints(Is.Same(FooDescriptor), Is.Same(mockController), Is.Same(fooRequest),
+ Is.Same(FooResponse.DefaultInstance), Is.Anything())
+ .Do((CallFooDelegate) ((p1, p2, p3, response, done) => done(response)));
+ doneHandler(FooResponse.DefaultInstance);
+ }
+
+ service.Foo(mockController, fooRequest, doneHandler);
+
+ mocks.VerifyAll();
+ }
+
+ [Test]
+ public void CallMethodBar()
+ {
+ MockRepository mocks = new MockRepository();
+ BarRequest barRequest = BarRequest.CreateBuilder().Build();
+ BarResponse barResponse = BarResponse.CreateBuilder().Build();
+ IRpcController controller = mocks.StrictMock<IRpcController>();
+
+ bool barCalled = false;
+
+ TestGenericService service = new TestServiceImpl(null, (request, responseAction) =>
+ {
+ Assert.AreSame(barRequest, request);
+ barCalled = true;
+ responseAction(barResponse);
+ }, controller);
+
+ bool doneHandlerCalled = false;
+ Action<IMessage> doneHandler = (response =>
+ {
+ Assert.AreSame(barResponse, response);
+ doneHandlerCalled = true;
+ });
+
+ using (mocks.Record())
+ {
+ // No mock interactions to record
+ }
+
+ service.CallMethod(BarDescriptor, controller, barRequest, doneHandler);
+
+ Assert.IsTrue(doneHandlerCalled);
+ Assert.IsTrue(barCalled);
+ mocks.VerifyAll();
+ }
+
+
+ private class TestServiceImpl : TestGenericService
+ {
+ private readonly Action<FooRequest, Action<FooResponse>> fooHandler;
+ private readonly Action<BarRequest, Action<BarResponse>> barHandler;
+ private readonly IRpcController expectedController;
+
+ internal TestServiceImpl()
+ {
+ }
+
+ internal TestServiceImpl(Action<FooRequest, Action<FooResponse>> fooHandler,
+ Action<BarRequest, Action<BarResponse>> barHandler,
+ IRpcController expectedController)
+ {
+ this.fooHandler = fooHandler;
+ this.barHandler = barHandler;
+ this.expectedController = expectedController;
+ }
+
+ public override void Foo(IRpcController controller, FooRequest request, Action<FooResponse> done)
+ {
+ Assert.AreSame(expectedController, controller);
+ fooHandler(request, done);
+ }
+
+ public override void Bar(IRpcController controller, BarRequest request, Action<BarResponse> done)
+ {
+ Assert.AreSame(expectedController, controller);
+ barHandler(request, done);
+ }
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/TestRpcGenerator.cs b/src/ProtocolBuffers.Test/TestRpcGenerator.cs index ac98c496..5f159b62 100644 --- a/src/ProtocolBuffers.Test/TestRpcGenerator.cs +++ b/src/ProtocolBuffers.Test/TestRpcGenerator.cs @@ -1,4 +1,5 @@ -#region Copyright notice and license
+#region Copyright notice and license
+
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
@@ -30,6 +31,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
#endregion
using System;
@@ -46,81 +48,95 @@ namespace Google.ProtocolBuffers [TestFixture]
public class TestRpcGenerator
{
- /// <summary>
- /// A sample implementation of the ISearchService for testing
- /// </summary>
- class ExampleSearchImpl : ISearchService {
- SearchResponse ISearchService.Search(SearchRequest searchRequest) {
- if (searchRequest.CriteriaCount == 0) {
- throw new ArgumentException("No criteria specified.", new InvalidOperationException());
+ /// <summary>
+ /// A sample implementation of the ISearchService for testing
+ /// </summary>
+ private class ExampleSearchImpl : ISearchService
+ {
+ SearchResponse ISearchService.Search(SearchRequest searchRequest)
+ {
+ if (searchRequest.CriteriaCount == 0)
+ {
+ throw new ArgumentException("No criteria specified.", new InvalidOperationException());
+ }
+ SearchResponse.Builder resp = SearchResponse.CreateBuilder();
+ foreach (string criteria in searchRequest.CriteriaList)
+ {
+ resp.AddResults(
+ SearchResponse.Types.ResultItem.CreateBuilder().SetName(criteria).SetUrl("http://search.com").
+ Build());
+ }
+ return resp.Build();
+ }
+
+ SearchResponse ISearchService.RefineSearch(RefineSearchRequest refineSearchRequest)
+ {
+ SearchResponse.Builder resp = refineSearchRequest.PreviousResults.ToBuilder();
+ foreach (string criteria in refineSearchRequest.CriteriaList)
+ {
+ resp.AddResults(
+ SearchResponse.Types.ResultItem.CreateBuilder().SetName(criteria).SetUrl("http://refine.com").
+ Build());
+ }
+ return resp.Build();
+ }
+ }
+
+ /// <summary>
+ /// An example extraction of the wire protocol
+ /// </summary>
+ private interface IWireTransfer
+ {
+ byte[] Execute(string method, byte[] message);
+ }
+
+ /// <summary>
+ /// An example of a server responding to a wire request
+ /// </summary>
+ private class ExampleServerHost : IWireTransfer
+ {
+ private readonly IRpcServerStub _stub;
+
+ public ExampleServerHost(ISearchService implementation)
+ {
+ //on the server, we create a dispatch to call the appropriate method by name
+ IRpcDispatch dispatch = new SearchService.Dispatch(implementation);
+ //we then wrap that dispatch in a server stub which will deserialize the wire bytes to the message
+ //type appropriate for the method name being invoked.
+ _stub = new SearchService.ServerStub(dispatch);
}
- SearchResponse.Builder resp = SearchResponse.CreateBuilder();
- foreach (string criteria in searchRequest.CriteriaList) {
- resp.AddResults(SearchResponse.Types.ResultItem.CreateBuilder().SetName(criteria).SetUrl("http://search.com").Build());
+
+ byte[] IWireTransfer.Execute(string method, byte[] message)
+ {
+ //now when we recieve a wire transmission to invoke a method by name with a byte[] or stream payload
+ //we just simply call the sub:
+ IMessageLite response = _stub.CallMethod(method, CodedInputStream.CreateInstance(message),
+ ExtensionRegistry.Empty);
+ //now we return the expected response message:
+ return response.ToByteArray();
}
- return resp.Build();
}
- SearchResponse ISearchService.RefineSearch(RefineSearchRequest refineSearchRequest) {
- SearchResponse.Builder resp = refineSearchRequest.PreviousResults.ToBuilder();
- foreach (string criteria in refineSearchRequest.CriteriaList) {
- resp.AddResults(SearchResponse.Types.ResultItem.CreateBuilder().SetName(criteria).SetUrl("http://refine.com").Build());
+ /// <summary>
+ /// An example of a client sending a wire request
+ /// </summary>
+ private class ExampleClient : IRpcDispatch
+ {
+ private readonly IWireTransfer _wire;
+
+ public ExampleClient(IWireTransfer wire)
+ {
+ _wire = wire;
+ }
+
+ TMessage IRpcDispatch.CallMethod<TMessage, TBuilder>(string method, IMessageLite request,
+ IBuilderLite<TMessage, TBuilder> response)
+ {
+ byte[] rawResponse = _wire.Execute(method, request.ToByteArray());
+ response.MergeFrom(rawResponse);
+ return response.Build();
}
- return resp.Build();
}
- }
-
- /// <summary>
- /// An example extraction of the wire protocol
- /// </summary>
- interface IWireTransfer
- {
- byte[] Execute(string method, byte[] message);
- }
-
- /// <summary>
- /// An example of a server responding to a wire request
- /// </summary>
- class ExampleServerHost : IWireTransfer
- {
- readonly IRpcServerStub _stub;
- public ExampleServerHost(ISearchService implementation)
- {
- //on the server, we create a dispatch to call the appropriate method by name
- IRpcDispatch dispatch = new SearchService.Dispatch(implementation);
- //we then wrap that dispatch in a server stub which will deserialize the wire bytes to the message
- //type appropriate for the method name being invoked.
- _stub = new SearchService.ServerStub(dispatch);
- }
-
- byte[] IWireTransfer.Execute(string method, byte[] message)
- {
- //now when we recieve a wire transmission to invoke a method by name with a byte[] or stream payload
- //we just simply call the sub:
- IMessageLite response = _stub.CallMethod(method, CodedInputStream.CreateInstance(message), ExtensionRegistry.Empty);
- //now we return the expected response message:
- return response.ToByteArray();
- }
- }
-
- /// <summary>
- /// An example of a client sending a wire request
- /// </summary>
- class ExampleClient : IRpcDispatch
- {
- readonly IWireTransfer _wire;
- public ExampleClient(IWireTransfer wire)
- {
- _wire = wire;
- }
-
- TMessage IRpcDispatch.CallMethod<TMessage, TBuilder>(string method, IMessageLite request, IBuilderLite<TMessage, TBuilder> response)
- {
- byte[] rawResponse = _wire.Execute(method, request.ToByteArray());
- response.MergeFrom(rawResponse);
- return response.Build();
- }
- }
/// <summary>
/// Put it all together to create one seamless client/server experience full of rich-type goodness ;)
@@ -141,7 +157,9 @@ namespace Google.ProtocolBuffers Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
//The test part of this, call the only other method
- result = client.RefineSearch(RefineSearchRequest.CreateBuilder().SetPreviousResults(result).AddCriteria("Refine").Build());
+ result =
+ client.RefineSearch(
+ RefineSearchRequest.CreateBuilder().SetPreviousResults(result).AddCriteria("Refine").Build());
Assert.AreEqual(2, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
diff --git a/src/ProtocolBuffers.Test/TestUtil.cs b/src/ProtocolBuffers.Test/TestUtil.cs index 63fb0817..45169840 100644 --- a/src/ProtocolBuffers.Test/TestUtil.cs +++ b/src/ProtocolBuffers.Test/TestUtil.cs @@ -1,1620 +1,1705 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Text; -using System.Threading; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - internal static class TestUtil { - - private static string testDataDirectory; - private static ByteString goldenMessage = null; - - internal static string TestDataDirectory { - get { - if (testDataDirectory != null) { - return testDataDirectory; - } - - DirectoryInfo ancestor = new DirectoryInfo("."); - // Search each parent directory looking for "testdata". - while (ancestor != null) { - string candidate = Path.Combine(ancestor.FullName, "testdata"); - if (Directory.Exists(candidate)) { - testDataDirectory = candidate; - return candidate; - } - ancestor = ancestor.Parent; - } - // TODO(jonskeet): Come up with a better exception to throw - throw new Exception("Unable to find directory containing test files"); - } - } - - internal static ByteString GoldenMessage { - get { - if (goldenMessage == null) { - goldenMessage = ReadBytesFromFile("golden_message"); - } - return goldenMessage; - } - } - - /// <summary> - /// Creates an unmodifiable ExtensionRegistry containing all the extensions - /// of TestAllExtensions. - /// </summary> - /// <returns></returns> - internal static ExtensionRegistry CreateExtensionRegistry() { - ExtensionRegistry registry = ExtensionRegistry.CreateInstance(); - RegisterAllExtensions(registry); - return registry.AsReadOnly(); - } - - /// <summary> - /// Registers all of the extensions in TestAllExtensions with the given - /// ExtensionRegistry. - /// </summary> - internal static void RegisterAllExtensions(ExtensionRegistry registry) { - registry.Add(UnitTestProtoFile.OptionalInt32Extension); - registry.Add(UnitTestProtoFile.OptionalInt64Extension); - registry.Add(UnitTestProtoFile.OptionalUint32Extension); - registry.Add(UnitTestProtoFile.OptionalUint64Extension); - registry.Add(UnitTestProtoFile.OptionalSint32Extension); - registry.Add(UnitTestProtoFile.OptionalSint64Extension); - registry.Add(UnitTestProtoFile.OptionalFixed32Extension); - registry.Add(UnitTestProtoFile.OptionalFixed64Extension); - registry.Add(UnitTestProtoFile.OptionalSfixed32Extension); - registry.Add(UnitTestProtoFile.OptionalSfixed64Extension); - registry.Add(UnitTestProtoFile.OptionalFloatExtension); - registry.Add(UnitTestProtoFile.OptionalDoubleExtension); - registry.Add(UnitTestProtoFile.OptionalBoolExtension); - registry.Add(UnitTestProtoFile.OptionalStringExtension); - registry.Add(UnitTestProtoFile.OptionalBytesExtension); - registry.Add(UnitTestProtoFile.OptionalGroupExtension); - registry.Add(UnitTestProtoFile.OptionalNestedMessageExtension); - registry.Add(UnitTestProtoFile.OptionalForeignMessageExtension); - registry.Add(UnitTestProtoFile.OptionalImportMessageExtension); - registry.Add(UnitTestProtoFile.OptionalNestedEnumExtension); - registry.Add(UnitTestProtoFile.OptionalForeignEnumExtension); - registry.Add(UnitTestProtoFile.OptionalImportEnumExtension); - registry.Add(UnitTestProtoFile.OptionalStringPieceExtension); - registry.Add(UnitTestProtoFile.OptionalCordExtension); - - registry.Add(UnitTestProtoFile.RepeatedInt32Extension); - registry.Add(UnitTestProtoFile.RepeatedInt64Extension); - registry.Add(UnitTestProtoFile.RepeatedUint32Extension); - registry.Add(UnitTestProtoFile.RepeatedUint64Extension); - registry.Add(UnitTestProtoFile.RepeatedSint32Extension); - registry.Add(UnitTestProtoFile.RepeatedSint64Extension); - registry.Add(UnitTestProtoFile.RepeatedFixed32Extension); - registry.Add(UnitTestProtoFile.RepeatedFixed64Extension); - registry.Add(UnitTestProtoFile.RepeatedSfixed32Extension); - registry.Add(UnitTestProtoFile.RepeatedSfixed64Extension); - registry.Add(UnitTestProtoFile.RepeatedFloatExtension); - registry.Add(UnitTestProtoFile.RepeatedDoubleExtension); - registry.Add(UnitTestProtoFile.RepeatedBoolExtension); - registry.Add(UnitTestProtoFile.RepeatedStringExtension); - registry.Add(UnitTestProtoFile.RepeatedBytesExtension); - registry.Add(UnitTestProtoFile.RepeatedGroupExtension); - registry.Add(UnitTestProtoFile.RepeatedNestedMessageExtension); - registry.Add(UnitTestProtoFile.RepeatedForeignMessageExtension); - registry.Add(UnitTestProtoFile.RepeatedImportMessageExtension); - registry.Add(UnitTestProtoFile.RepeatedNestedEnumExtension); - registry.Add(UnitTestProtoFile.RepeatedForeignEnumExtension); - registry.Add(UnitTestProtoFile.RepeatedImportEnumExtension); - registry.Add(UnitTestProtoFile.RepeatedStringPieceExtension); - registry.Add(UnitTestProtoFile.RepeatedCordExtension); - - registry.Add(UnitTestProtoFile.DefaultInt32Extension); - registry.Add(UnitTestProtoFile.DefaultInt64Extension); - registry.Add(UnitTestProtoFile.DefaultUint32Extension); - registry.Add(UnitTestProtoFile.DefaultUint64Extension); - registry.Add(UnitTestProtoFile.DefaultSint32Extension); - registry.Add(UnitTestProtoFile.DefaultSint64Extension); - registry.Add(UnitTestProtoFile.DefaultFixed32Extension); - registry.Add(UnitTestProtoFile.DefaultFixed64Extension); - registry.Add(UnitTestProtoFile.DefaultSfixed32Extension); - registry.Add(UnitTestProtoFile.DefaultSfixed64Extension); - registry.Add(UnitTestProtoFile.DefaultFloatExtension); - registry.Add(UnitTestProtoFile.DefaultDoubleExtension); - registry.Add(UnitTestProtoFile.DefaultBoolExtension); - registry.Add(UnitTestProtoFile.DefaultStringExtension); - registry.Add(UnitTestProtoFile.DefaultBytesExtension); - registry.Add(UnitTestProtoFile.DefaultNestedEnumExtension); - registry.Add(UnitTestProtoFile.DefaultForeignEnumExtension); - registry.Add(UnitTestProtoFile.DefaultImportEnumExtension); - registry.Add(UnitTestProtoFile.DefaultStringPieceExtension); - registry.Add(UnitTestProtoFile.DefaultCordExtension); - - registry.Add(UnitTestProtoFile.PackedInt32Extension); - registry.Add(UnitTestProtoFile.PackedInt64Extension); - registry.Add(UnitTestProtoFile.PackedUint32Extension); - registry.Add(UnitTestProtoFile.PackedUint64Extension); - registry.Add(UnitTestProtoFile.PackedSint32Extension); - registry.Add(UnitTestProtoFile.PackedSint64Extension); - registry.Add(UnitTestProtoFile.PackedFixed32Extension); - registry.Add(UnitTestProtoFile.PackedFixed64Extension); - registry.Add(UnitTestProtoFile.PackedSfixed32Extension); - registry.Add(UnitTestProtoFile.PackedSfixed64Extension); - registry.Add(UnitTestProtoFile.PackedFloatExtension); - registry.Add(UnitTestProtoFile.PackedDoubleExtension); - registry.Add(UnitTestProtoFile.PackedBoolExtension); - registry.Add(UnitTestProtoFile.PackedEnumExtension); - } - - internal static string ReadTextFromFile(string filePath) { - return ReadBytesFromFile(filePath).ToStringUtf8(); - } - - internal static ByteString ReadBytesFromFile(String filename) { - byte[] data = File.ReadAllBytes(Path.Combine(TestDataDirectory, filename)); - return ByteString.CopyFrom(data); - } - - /// <summary> - /// Helper to convert a String to ByteString. - /// </summary> - internal static ByteString ToBytes(String str) { - return ByteString.CopyFrom(Encoding.UTF8.GetBytes(str)); - } - - internal static TestAllTypes GetAllSet() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - SetAllFields(builder); - return builder.Build(); - } - - /// <summary> - /// Sets every field of the specified message to the values expected by - /// AssertAllFieldsSet. - /// </summary> - internal static void SetAllFields(TestAllTypes.Builder message) { - message.SetOptionalInt32(101); - message.SetOptionalInt64(102); - message.SetOptionalUint32(103); - message.SetOptionalUint64(104); - message.SetOptionalSint32(105); - message.SetOptionalSint64(106); - message.SetOptionalFixed32(107); - message.SetOptionalFixed64(108); - message.SetOptionalSfixed32(109); - message.SetOptionalSfixed64(110); - message.SetOptionalFloat(111); - message.SetOptionalDouble(112); - message.SetOptionalBool(true); - message.SetOptionalString("115"); - message.SetOptionalBytes(ToBytes("116")); - - message.SetOptionalGroup(TestAllTypes.Types.OptionalGroup.CreateBuilder().SetA(117).Build()); - message.SetOptionalNestedMessage(TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(118).Build()); - message.SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(119).Build()); - message.SetOptionalImportMessage(ImportMessage.CreateBuilder().SetD(120).Build()); - - message.SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.BAZ); - message.SetOptionalForeignEnum(ForeignEnum.FOREIGN_BAZ); - message.SetOptionalImportEnum(ImportEnum.IMPORT_BAZ); - - message.SetOptionalStringPiece("124"); - message.SetOptionalCord("125"); - - // ----------------------------------------------------------------- - - message.AddRepeatedInt32(201); - message.AddRepeatedInt64(202); - message.AddRepeatedUint32(203); - message.AddRepeatedUint64(204); - message.AddRepeatedSint32(205); - message.AddRepeatedSint64(206); - message.AddRepeatedFixed32(207); - message.AddRepeatedFixed64(208); - message.AddRepeatedSfixed32(209); - message.AddRepeatedSfixed64(210); - message.AddRepeatedFloat(211); - message.AddRepeatedDouble(212); - message.AddRepeatedBool(true); - message.AddRepeatedString("215"); - message.AddRepeatedBytes(ToBytes("216")); - - message.AddRepeatedGroup(TestAllTypes.Types.RepeatedGroup.CreateBuilder().SetA(217).Build()); - message.AddRepeatedNestedMessage(TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(218).Build()); - message.AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(219).Build()); - message.AddRepeatedImportMessage(ImportMessage.CreateBuilder().SetD(220).Build()); - - message.AddRepeatedNestedEnum(TestAllTypes.Types.NestedEnum.BAR); - message.AddRepeatedForeignEnum(ForeignEnum.FOREIGN_BAR); - message.AddRepeatedImportEnum(ImportEnum.IMPORT_BAR); - - message.AddRepeatedStringPiece("224"); - message.AddRepeatedCord("225"); - - // Add a second one of each field. - message.AddRepeatedInt32(301); - message.AddRepeatedInt64(302); - message.AddRepeatedUint32(303); - message.AddRepeatedUint64(304); - message.AddRepeatedSint32(305); - message.AddRepeatedSint64(306); - message.AddRepeatedFixed32(307); - message.AddRepeatedFixed64(308); - message.AddRepeatedSfixed32(309); - message.AddRepeatedSfixed64(310); - message.AddRepeatedFloat(311); - message.AddRepeatedDouble(312); - message.AddRepeatedBool(false); - message.AddRepeatedString("315"); - message.AddRepeatedBytes(ToBytes("316")); - - message.AddRepeatedGroup(TestAllTypes.Types.RepeatedGroup.CreateBuilder().SetA(317).Build()); - message.AddRepeatedNestedMessage(TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(318).Build()); - message.AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(319).Build()); - message.AddRepeatedImportMessage(ImportMessage.CreateBuilder().SetD(320).Build()); - - message.AddRepeatedNestedEnum(TestAllTypes.Types.NestedEnum.BAZ); - message.AddRepeatedForeignEnum(ForeignEnum.FOREIGN_BAZ); - message.AddRepeatedImportEnum(ImportEnum.IMPORT_BAZ); - - message.AddRepeatedStringPiece("324"); - message.AddRepeatedCord("325"); - - // ----------------------------------------------------------------- - - message.SetDefaultInt32(401); - message.SetDefaultInt64(402); - message.SetDefaultUint32(403); - message.SetDefaultUint64(404); - message.SetDefaultSint32(405); - message.SetDefaultSint64(406); - message.SetDefaultFixed32(407); - message.SetDefaultFixed64(408); - message.SetDefaultSfixed32(409); - message.SetDefaultSfixed64(410); - message.SetDefaultFloat(411); - message.SetDefaultDouble(412); - message.SetDefaultBool(false); - message.SetDefaultString("415"); - message.SetDefaultBytes(ToBytes("416")); - - message.SetDefaultNestedEnum(TestAllTypes.Types.NestedEnum.FOO); - message.SetDefaultForeignEnum(ForeignEnum.FOREIGN_FOO); - message.SetDefaultImportEnum(ImportEnum.IMPORT_FOO); - - message.SetDefaultStringPiece("424"); - message.SetDefaultCord("425"); - } - - /// <summary> - /// Asserts that all fields of the specified message are set to the values - /// assigned by SetAllFields. - /// </summary> - internal static void AssertAllFieldsSet(TestAllTypes message) { - Assert.IsTrue(message.HasOptionalInt32); - Assert.IsTrue(message.HasOptionalInt64); - Assert.IsTrue(message.HasOptionalUint32); - Assert.IsTrue(message.HasOptionalUint64); - Assert.IsTrue(message.HasOptionalSint32); - Assert.IsTrue(message.HasOptionalSint64); - Assert.IsTrue(message.HasOptionalFixed32); - Assert.IsTrue(message.HasOptionalFixed64); - Assert.IsTrue(message.HasOptionalSfixed32); - Assert.IsTrue(message.HasOptionalSfixed64); - Assert.IsTrue(message.HasOptionalFloat); - Assert.IsTrue(message.HasOptionalDouble); - Assert.IsTrue(message.HasOptionalBool); - Assert.IsTrue(message.HasOptionalString); - Assert.IsTrue(message.HasOptionalBytes); - - Assert.IsTrue(message.HasOptionalGroup); - Assert.IsTrue(message.HasOptionalNestedMessage); - Assert.IsTrue(message.HasOptionalForeignMessage); - Assert.IsTrue(message.HasOptionalImportMessage); - - Assert.IsTrue(message.OptionalGroup.HasA); - Assert.IsTrue(message.OptionalNestedMessage.HasBb); - Assert.IsTrue(message.OptionalForeignMessage.HasC); - Assert.IsTrue(message.OptionalImportMessage.HasD); - - Assert.IsTrue(message.HasOptionalNestedEnum); - Assert.IsTrue(message.HasOptionalForeignEnum); - Assert.IsTrue(message.HasOptionalImportEnum); - - Assert.IsTrue(message.HasOptionalStringPiece); - Assert.IsTrue(message.HasOptionalCord); - - Assert.AreEqual(101, message.OptionalInt32); - Assert.AreEqual(102, message.OptionalInt64); - Assert.AreEqual(103, message.OptionalUint32); - Assert.AreEqual(104, message.OptionalUint64); - Assert.AreEqual(105, message.OptionalSint32); - Assert.AreEqual(106, message.OptionalSint64); - Assert.AreEqual(107, message.OptionalFixed32); - Assert.AreEqual(108, message.OptionalFixed64); - Assert.AreEqual(109, message.OptionalSfixed32); - Assert.AreEqual(110, message.OptionalSfixed64); - Assert.AreEqual(111, message.OptionalFloat); - Assert.AreEqual(112, message.OptionalDouble); - Assert.AreEqual(true, message.OptionalBool); - Assert.AreEqual("115", message.OptionalString); - Assert.AreEqual(ToBytes("116"), message.OptionalBytes); - - Assert.AreEqual(117, message.OptionalGroup.A); - Assert.AreEqual(118, message.OptionalNestedMessage.Bb); - Assert.AreEqual(119, message.OptionalForeignMessage.C); - Assert.AreEqual(120, message.OptionalImportMessage.D); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAZ, message.OptionalNestedEnum); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, message.OptionalForeignEnum); - Assert.AreEqual(ImportEnum.IMPORT_BAZ, message.OptionalImportEnum); - - Assert.AreEqual("124", message.OptionalStringPiece); - Assert.AreEqual("125", message.OptionalCord); - - // ----------------------------------------------------------------- - - Assert.AreEqual(2, message.RepeatedInt32Count); - Assert.AreEqual(2, message.RepeatedInt64Count); - Assert.AreEqual(2, message.RepeatedUint32Count); - Assert.AreEqual(2, message.RepeatedUint64Count); - Assert.AreEqual(2, message.RepeatedSint32Count); - Assert.AreEqual(2, message.RepeatedSint64Count); - Assert.AreEqual(2, message.RepeatedFixed32Count); - Assert.AreEqual(2, message.RepeatedFixed64Count); - Assert.AreEqual(2, message.RepeatedSfixed32Count); - Assert.AreEqual(2, message.RepeatedSfixed64Count); - Assert.AreEqual(2, message.RepeatedFloatCount); - Assert.AreEqual(2, message.RepeatedDoubleCount); - Assert.AreEqual(2, message.RepeatedBoolCount); - Assert.AreEqual(2, message.RepeatedStringCount); - Assert.AreEqual(2, message.RepeatedBytesCount); - - Assert.AreEqual(2, message.RepeatedGroupCount ); - Assert.AreEqual(2, message.RepeatedNestedMessageCount ); - Assert.AreEqual(2, message.RepeatedForeignMessageCount); - Assert.AreEqual(2, message.RepeatedImportMessageCount ); - Assert.AreEqual(2, message.RepeatedNestedEnumCount ); - Assert.AreEqual(2, message.RepeatedForeignEnumCount ); - Assert.AreEqual(2, message.RepeatedImportEnumCount ); - - Assert.AreEqual(2, message.RepeatedStringPieceCount); - Assert.AreEqual(2, message.RepeatedCordCount); - - Assert.AreEqual(201, message.GetRepeatedInt32(0)); - Assert.AreEqual(202, message.GetRepeatedInt64(0)); - Assert.AreEqual(203, message.GetRepeatedUint32(0)); - Assert.AreEqual(204, message.GetRepeatedUint64(0)); - Assert.AreEqual(205, message.GetRepeatedSint32(0)); - Assert.AreEqual(206, message.GetRepeatedSint64(0)); - Assert.AreEqual(207, message.GetRepeatedFixed32(0)); - Assert.AreEqual(208, message.GetRepeatedFixed64(0)); - Assert.AreEqual(209, message.GetRepeatedSfixed32(0)); - Assert.AreEqual(210, message.GetRepeatedSfixed64(0)); - Assert.AreEqual(211, message.GetRepeatedFloat(0)); - Assert.AreEqual(212, message.GetRepeatedDouble(0)); - Assert.AreEqual(true , message.GetRepeatedBool(0)); - Assert.AreEqual("215", message.GetRepeatedString(0)); - Assert.AreEqual(ToBytes("216"), message.GetRepeatedBytes(0)); - - Assert.AreEqual(217, message.GetRepeatedGroup(0).A); - Assert.AreEqual(218, message.GetRepeatedNestedMessage (0).Bb); - Assert.AreEqual(219, message.GetRepeatedForeignMessage(0).C); - Assert.AreEqual(220, message.GetRepeatedImportMessage (0).D); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, message.GetRepeatedNestedEnum (0)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAR, message.GetRepeatedForeignEnum(0)); - Assert.AreEqual(ImportEnum.IMPORT_BAR, message.GetRepeatedImportEnum(0)); - - Assert.AreEqual("224", message.GetRepeatedStringPiece(0)); - Assert.AreEqual("225", message.GetRepeatedCord(0)); - - Assert.AreEqual(301, message.GetRepeatedInt32 (1)); - Assert.AreEqual(302, message.GetRepeatedInt64 (1)); - Assert.AreEqual(303, message.GetRepeatedUint32 (1)); - Assert.AreEqual(304, message.GetRepeatedUint64 (1)); - Assert.AreEqual(305, message.GetRepeatedSint32 (1)); - Assert.AreEqual(306, message.GetRepeatedSint64 (1)); - Assert.AreEqual(307, message.GetRepeatedFixed32 (1)); - Assert.AreEqual(308, message.GetRepeatedFixed64 (1)); - Assert.AreEqual(309, message.GetRepeatedSfixed32(1)); - Assert.AreEqual(310, message.GetRepeatedSfixed64(1)); - Assert.AreEqual(311, message.GetRepeatedFloat (1), 0.0); - Assert.AreEqual(312, message.GetRepeatedDouble (1), 0.0); - Assert.AreEqual(false, message.GetRepeatedBool (1)); - Assert.AreEqual("315", message.GetRepeatedString (1)); - Assert.AreEqual(ToBytes("316"), message.GetRepeatedBytes(1)); - - Assert.AreEqual(317, message.GetRepeatedGroup (1).A); - Assert.AreEqual(318, message.GetRepeatedNestedMessage (1).Bb); - Assert.AreEqual(319, message.GetRepeatedForeignMessage(1).C); - Assert.AreEqual(320, message.GetRepeatedImportMessage (1).D); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAZ, message.GetRepeatedNestedEnum (1)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, message.GetRepeatedForeignEnum(1)); - Assert.AreEqual(ImportEnum.IMPORT_BAZ, message.GetRepeatedImportEnum(1)); - - Assert.AreEqual("324", message.GetRepeatedStringPiece(1)); - Assert.AreEqual("325", message.GetRepeatedCord(1)); - - // ----------------------------------------------------------------- - - Assert.IsTrue(message.HasDefaultInt32 ); - Assert.IsTrue(message.HasDefaultInt64 ); - Assert.IsTrue(message.HasDefaultUint32 ); - Assert.IsTrue(message.HasDefaultUint64 ); - Assert.IsTrue(message.HasDefaultSint32 ); - Assert.IsTrue(message.HasDefaultSint64 ); - Assert.IsTrue(message.HasDefaultFixed32 ); - Assert.IsTrue(message.HasDefaultFixed64 ); - Assert.IsTrue(message.HasDefaultSfixed32); - Assert.IsTrue(message.HasDefaultSfixed64); - Assert.IsTrue(message.HasDefaultFloat ); - Assert.IsTrue(message.HasDefaultDouble ); - Assert.IsTrue(message.HasDefaultBool ); - Assert.IsTrue(message.HasDefaultString ); - Assert.IsTrue(message.HasDefaultBytes ); - - Assert.IsTrue(message.HasDefaultNestedEnum ); - Assert.IsTrue(message.HasDefaultForeignEnum); - Assert.IsTrue(message.HasDefaultImportEnum ); - - Assert.IsTrue(message.HasDefaultStringPiece); - Assert.IsTrue(message.HasDefaultCord); - - Assert.AreEqual(401, message.DefaultInt32); - Assert.AreEqual(402, message.DefaultInt64); - Assert.AreEqual(403, message.DefaultUint32); - Assert.AreEqual(404, message.DefaultUint64); - Assert.AreEqual(405, message.DefaultSint32); - Assert.AreEqual(406, message.DefaultSint64); - Assert.AreEqual(407, message.DefaultFixed32); - Assert.AreEqual(408, message.DefaultFixed64); - Assert.AreEqual(409, message.DefaultSfixed32); - Assert.AreEqual(410, message.DefaultSfixed64); - Assert.AreEqual(411, message.DefaultFloat); - Assert.AreEqual(412, message.DefaultDouble); - Assert.AreEqual(false, message.DefaultBool ); - Assert.AreEqual("415", message.DefaultString ); - Assert.AreEqual(ToBytes("416"), message.DefaultBytes); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, message.DefaultNestedEnum); - Assert.AreEqual(ForeignEnum.FOREIGN_FOO, message.DefaultForeignEnum); - Assert.AreEqual(ImportEnum.IMPORT_FOO, message.DefaultImportEnum); - - Assert.AreEqual("424", message.DefaultStringPiece); - Assert.AreEqual("425", message.DefaultCord); - } - - internal static void AssertClear(TestAllTypes message) { - // HasBlah() should initially be false for all optional fields. - Assert.IsFalse(message.HasOptionalInt32); - Assert.IsFalse(message.HasOptionalInt64); - Assert.IsFalse(message.HasOptionalUint32); - Assert.IsFalse(message.HasOptionalUint64); - Assert.IsFalse(message.HasOptionalSint32); - Assert.IsFalse(message.HasOptionalSint64); - Assert.IsFalse(message.HasOptionalFixed32); - Assert.IsFalse(message.HasOptionalFixed64); - Assert.IsFalse(message.HasOptionalSfixed32); - Assert.IsFalse(message.HasOptionalSfixed64); - Assert.IsFalse(message.HasOptionalFloat); - Assert.IsFalse(message.HasOptionalDouble); - Assert.IsFalse(message.HasOptionalBool); - Assert.IsFalse(message.HasOptionalString); - Assert.IsFalse(message.HasOptionalBytes); - - Assert.IsFalse(message.HasOptionalGroup); - Assert.IsFalse(message.HasOptionalNestedMessage); - Assert.IsFalse(message.HasOptionalForeignMessage); - Assert.IsFalse(message.HasOptionalImportMessage); - - Assert.IsFalse(message.HasOptionalNestedEnum); - Assert.IsFalse(message.HasOptionalForeignEnum); - Assert.IsFalse(message.HasOptionalImportEnum); - - Assert.IsFalse(message.HasOptionalStringPiece); - Assert.IsFalse(message.HasOptionalCord); - - // Optional fields without defaults are set to zero or something like it. - Assert.AreEqual(0, message.OptionalInt32); - Assert.AreEqual(0, message.OptionalInt64); - Assert.AreEqual(0, message.OptionalUint32); - Assert.AreEqual(0, message.OptionalUint64); - Assert.AreEqual(0, message.OptionalSint32); - Assert.AreEqual(0, message.OptionalSint64); - Assert.AreEqual(0, message.OptionalFixed32); - Assert.AreEqual(0, message.OptionalFixed64); - Assert.AreEqual(0, message.OptionalSfixed32); - Assert.AreEqual(0, message.OptionalSfixed64); - Assert.AreEqual(0, message.OptionalFloat); - Assert.AreEqual(0, message.OptionalDouble); - Assert.AreEqual(false, message.OptionalBool); - Assert.AreEqual("", message.OptionalString); - Assert.AreEqual(ByteString.Empty, message.OptionalBytes); - - // Embedded messages should also be clear. - Assert.IsFalse(message.OptionalGroup.HasA); - Assert.IsFalse(message.OptionalNestedMessage.HasBb); - Assert.IsFalse(message.OptionalForeignMessage.HasC); - Assert.IsFalse(message.OptionalImportMessage.HasD); - - Assert.AreEqual(0, message.OptionalGroup.A); - Assert.AreEqual(0, message.OptionalNestedMessage.Bb); - Assert.AreEqual(0, message.OptionalForeignMessage.C); - Assert.AreEqual(0, message.OptionalImportMessage.D); - - // Enums without defaults are set to the first value in the enum. - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, message.OptionalNestedEnum); - Assert.AreEqual(ForeignEnum.FOREIGN_FOO, message.OptionalForeignEnum); - Assert.AreEqual(ImportEnum.IMPORT_FOO, message.OptionalImportEnum); - - Assert.AreEqual("", message.OptionalStringPiece); - Assert.AreEqual("", message.OptionalCord); - - // Repeated fields are empty. - Assert.AreEqual(0, message.RepeatedInt32Count); - Assert.AreEqual(0, message.RepeatedInt64Count); - Assert.AreEqual(0, message.RepeatedUint32Count); - Assert.AreEqual(0, message.RepeatedUint64Count); - Assert.AreEqual(0, message.RepeatedSint32Count); - Assert.AreEqual(0, message.RepeatedSint64Count); - Assert.AreEqual(0, message.RepeatedFixed32Count); - Assert.AreEqual(0, message.RepeatedFixed64Count); - Assert.AreEqual(0, message.RepeatedSfixed32Count); - Assert.AreEqual(0, message.RepeatedSfixed64Count); - Assert.AreEqual(0, message.RepeatedFloatCount); - Assert.AreEqual(0, message.RepeatedDoubleCount); - Assert.AreEqual(0, message.RepeatedBoolCount); - Assert.AreEqual(0, message.RepeatedStringCount); - Assert.AreEqual(0, message.RepeatedBytesCount); - - Assert.AreEqual(0, message.RepeatedGroupCount); - Assert.AreEqual(0, message.RepeatedNestedMessageCount); - Assert.AreEqual(0, message.RepeatedForeignMessageCount); - Assert.AreEqual(0, message.RepeatedImportMessageCount); - Assert.AreEqual(0, message.RepeatedNestedEnumCount); - Assert.AreEqual(0, message.RepeatedForeignEnumCount); - Assert.AreEqual(0, message.RepeatedImportEnumCount); - - Assert.AreEqual(0, message.RepeatedStringPieceCount); - Assert.AreEqual(0, message.RepeatedCordCount); - - // HasBlah() should also be false for all default fields. - Assert.IsFalse(message.HasDefaultInt32); - Assert.IsFalse(message.HasDefaultInt64); - Assert.IsFalse(message.HasDefaultUint32); - Assert.IsFalse(message.HasDefaultUint64); - Assert.IsFalse(message.HasDefaultSint32); - Assert.IsFalse(message.HasDefaultSint64); - Assert.IsFalse(message.HasDefaultFixed32); - Assert.IsFalse(message.HasDefaultFixed64); - Assert.IsFalse(message.HasDefaultSfixed32); - Assert.IsFalse(message.HasDefaultSfixed64); - Assert.IsFalse(message.HasDefaultFloat); - Assert.IsFalse(message.HasDefaultDouble); - Assert.IsFalse(message.HasDefaultBool); - Assert.IsFalse(message.HasDefaultString); - Assert.IsFalse(message.HasDefaultBytes); - - Assert.IsFalse(message.HasDefaultNestedEnum); - Assert.IsFalse(message.HasDefaultForeignEnum); - Assert.IsFalse(message.HasDefaultImportEnum); - - Assert.IsFalse(message.HasDefaultStringPiece); - Assert.IsFalse(message.HasDefaultCord); - - // Fields with defaults have their default values (duh). - Assert.AreEqual(41, message.DefaultInt32); - Assert.AreEqual(42, message.DefaultInt64); - Assert.AreEqual(43, message.DefaultUint32); - Assert.AreEqual(44, message.DefaultUint64); - Assert.AreEqual(-45, message.DefaultSint32); - Assert.AreEqual(46, message.DefaultSint64); - Assert.AreEqual(47, message.DefaultFixed32); - Assert.AreEqual(48, message.DefaultFixed64); - Assert.AreEqual(49, message.DefaultSfixed32); - Assert.AreEqual(-50, message.DefaultSfixed64); - Assert.AreEqual(51.5, message.DefaultFloat, 0.0); - Assert.AreEqual(52e3, message.DefaultDouble, 0.0); - Assert.AreEqual(true, message.DefaultBool); - Assert.AreEqual("hello", message.DefaultString); - Assert.AreEqual(ToBytes("world"), message.DefaultBytes); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, message.DefaultNestedEnum); - Assert.AreEqual(ForeignEnum.FOREIGN_BAR, message.DefaultForeignEnum); - Assert.AreEqual(ImportEnum.IMPORT_BAR, message.DefaultImportEnum); - - Assert.AreEqual("abc", message.DefaultStringPiece); - Assert.AreEqual("123", message.DefaultCord); - } - - /// <summary> - /// Get a TestAllExtensions with all fields set as they would be by - /// SetAllExtensions(TestAllExtensions.Builder). - /// </summary> - internal static TestAllExtensions GetAllExtensionsSet() { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - SetAllExtensions(builder); - return builder.Build(); - } - - public static TestPackedTypes GetPackedSet() { - TestPackedTypes.Builder builder = TestPackedTypes.CreateBuilder(); - SetPackedFields(builder); - return builder.Build(); - } - - public static TestPackedExtensions GetPackedExtensionsSet() { - TestPackedExtensions.Builder builder = TestPackedExtensions.CreateBuilder(); - SetPackedExtensions(builder); - return builder.Build(); - } - - /// <summary> - /// Sets every field of the specified builder to the values expected by - /// AssertAllExtensionsSet. - /// </summary> - internal static void SetAllExtensions(TestAllExtensions.Builder message) { - message.SetExtension(UnitTestProtoFile.OptionalInt32Extension, 101); - message.SetExtension(UnitTestProtoFile.OptionalInt64Extension, 102L); - message.SetExtension(UnitTestProtoFile.OptionalUint32Extension, 103U); - message.SetExtension(UnitTestProtoFile.OptionalUint64Extension, 104UL); - message.SetExtension(UnitTestProtoFile.OptionalSint32Extension, 105); - message.SetExtension(UnitTestProtoFile.OptionalSint64Extension, 106L); - message.SetExtension(UnitTestProtoFile.OptionalFixed32Extension, 107U); - message.SetExtension(UnitTestProtoFile.OptionalFixed64Extension, 108UL); - message.SetExtension(UnitTestProtoFile.OptionalSfixed32Extension, 109); - message.SetExtension(UnitTestProtoFile.OptionalSfixed64Extension, 110L); - message.SetExtension(UnitTestProtoFile.OptionalFloatExtension, 111F); - message.SetExtension(UnitTestProtoFile.OptionalDoubleExtension, 112D); - message.SetExtension(UnitTestProtoFile.OptionalBoolExtension, true); - message.SetExtension(UnitTestProtoFile.OptionalStringExtension, "115"); - message.SetExtension(UnitTestProtoFile.OptionalBytesExtension, ToBytes("116")); - - message.SetExtension(UnitTestProtoFile.OptionalGroupExtension, OptionalGroup_extension.CreateBuilder().SetA(117).Build()); - message.SetExtension(UnitTestProtoFile.OptionalNestedMessageExtension, TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(118).Build()); - message.SetExtension(UnitTestProtoFile.OptionalForeignMessageExtension, ForeignMessage.CreateBuilder().SetC(119).Build()); - message.SetExtension(UnitTestProtoFile.OptionalImportMessageExtension, ImportMessage.CreateBuilder().SetD(120).Build()); - - message.SetExtension(UnitTestProtoFile.OptionalNestedEnumExtension, TestAllTypes.Types.NestedEnum.BAZ); - message.SetExtension(UnitTestProtoFile.OptionalForeignEnumExtension, ForeignEnum.FOREIGN_BAZ); - message.SetExtension(UnitTestProtoFile.OptionalImportEnumExtension, ImportEnum.IMPORT_BAZ); - - message.SetExtension(UnitTestProtoFile.OptionalStringPieceExtension, "124"); - message.SetExtension(UnitTestProtoFile.OptionalCordExtension, "125"); - - // ----------------------------------------------------------------- - - message.AddExtension(UnitTestProtoFile.RepeatedInt32Extension, 201); - message.AddExtension(UnitTestProtoFile.RepeatedInt64Extension, 202L); - message.AddExtension(UnitTestProtoFile.RepeatedUint32Extension, 203U); - message.AddExtension(UnitTestProtoFile.RepeatedUint64Extension, 204UL); - message.AddExtension(UnitTestProtoFile.RepeatedSint32Extension, 205); - message.AddExtension(UnitTestProtoFile.RepeatedSint64Extension, 206L); - message.AddExtension(UnitTestProtoFile.RepeatedFixed32Extension, 207U); - message.AddExtension(UnitTestProtoFile.RepeatedFixed64Extension, 208UL); - message.AddExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 209); - message.AddExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 210L); - message.AddExtension(UnitTestProtoFile.RepeatedFloatExtension, 211F); - message.AddExtension(UnitTestProtoFile.RepeatedDoubleExtension, 212D); - message.AddExtension(UnitTestProtoFile.RepeatedBoolExtension, true); - message.AddExtension(UnitTestProtoFile.RepeatedStringExtension, "215"); - message.AddExtension(UnitTestProtoFile.RepeatedBytesExtension, ToBytes("216")); - - message.AddExtension(UnitTestProtoFile.RepeatedGroupExtension, RepeatedGroup_extension.CreateBuilder().SetA(217).Build()); - message.AddExtension(UnitTestProtoFile.RepeatedNestedMessageExtension, TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(218).Build()); - message.AddExtension(UnitTestProtoFile.RepeatedForeignMessageExtension, ForeignMessage.CreateBuilder().SetC(219).Build()); - message.AddExtension(UnitTestProtoFile.RepeatedImportMessageExtension, ImportMessage.CreateBuilder().SetD(220).Build()); - - message.AddExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, TestAllTypes.Types.NestedEnum.BAR); - message.AddExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAR); - message.AddExtension(UnitTestProtoFile.RepeatedImportEnumExtension, ImportEnum.IMPORT_BAR); - - message.AddExtension(UnitTestProtoFile.RepeatedStringPieceExtension, "224"); - message.AddExtension(UnitTestProtoFile.RepeatedCordExtension, "225"); - - // Add a second one of each field. - message.AddExtension(UnitTestProtoFile.RepeatedInt32Extension, 301); - message.AddExtension(UnitTestProtoFile.RepeatedInt64Extension, 302L); - message.AddExtension(UnitTestProtoFile.RepeatedUint32Extension, 303U); - message.AddExtension(UnitTestProtoFile.RepeatedUint64Extension, 304UL); - message.AddExtension(UnitTestProtoFile.RepeatedSint32Extension, 305); - message.AddExtension(UnitTestProtoFile.RepeatedSint64Extension, 306L); - message.AddExtension(UnitTestProtoFile.RepeatedFixed32Extension, 307U); - message.AddExtension(UnitTestProtoFile.RepeatedFixed64Extension, 308UL); - message.AddExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 309); - message.AddExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 310L); - message.AddExtension(UnitTestProtoFile.RepeatedFloatExtension, 311F); - message.AddExtension(UnitTestProtoFile.RepeatedDoubleExtension, 312D); - message.AddExtension(UnitTestProtoFile.RepeatedBoolExtension, false); - message.AddExtension(UnitTestProtoFile.RepeatedStringExtension, "315"); - message.AddExtension(UnitTestProtoFile.RepeatedBytesExtension, ToBytes("316")); - - message.AddExtension(UnitTestProtoFile.RepeatedGroupExtension, RepeatedGroup_extension.CreateBuilder().SetA(317).Build()); - message.AddExtension(UnitTestProtoFile.RepeatedNestedMessageExtension, TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(318).Build()); - message.AddExtension(UnitTestProtoFile.RepeatedForeignMessageExtension, ForeignMessage.CreateBuilder().SetC(319).Build()); - message.AddExtension(UnitTestProtoFile.RepeatedImportMessageExtension, ImportMessage.CreateBuilder().SetD(320).Build()); - - message.AddExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, TestAllTypes.Types.NestedEnum.BAZ); - message.AddExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAZ); - message.AddExtension(UnitTestProtoFile.RepeatedImportEnumExtension, ImportEnum.IMPORT_BAZ); - - message.AddExtension(UnitTestProtoFile.RepeatedStringPieceExtension, "324"); - message.AddExtension(UnitTestProtoFile.RepeatedCordExtension, "325"); - - // ----------------------------------------------------------------- - - message.SetExtension(UnitTestProtoFile.DefaultInt32Extension, 401); - message.SetExtension(UnitTestProtoFile.DefaultInt64Extension, 402L); - message.SetExtension(UnitTestProtoFile.DefaultUint32Extension, 403U); - message.SetExtension(UnitTestProtoFile.DefaultUint64Extension, 404UL); - message.SetExtension(UnitTestProtoFile.DefaultSint32Extension, 405); - message.SetExtension(UnitTestProtoFile.DefaultSint64Extension, 406L); - message.SetExtension(UnitTestProtoFile.DefaultFixed32Extension, 407U); - message.SetExtension(UnitTestProtoFile.DefaultFixed64Extension, 408UL); - message.SetExtension(UnitTestProtoFile.DefaultSfixed32Extension, 409); - message.SetExtension(UnitTestProtoFile.DefaultSfixed64Extension, 410L); - message.SetExtension(UnitTestProtoFile.DefaultFloatExtension, 411F); - message.SetExtension(UnitTestProtoFile.DefaultDoubleExtension, 412D); - message.SetExtension(UnitTestProtoFile.DefaultBoolExtension, false); - message.SetExtension(UnitTestProtoFile.DefaultStringExtension, "415"); - message.SetExtension(UnitTestProtoFile.DefaultBytesExtension, ToBytes("416")); - - message.SetExtension(UnitTestProtoFile.DefaultNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO); - message.SetExtension(UnitTestProtoFile.DefaultForeignEnumExtension, ForeignEnum.FOREIGN_FOO); - message.SetExtension(UnitTestProtoFile.DefaultImportEnumExtension, ImportEnum.IMPORT_FOO); - - message.SetExtension(UnitTestProtoFile.DefaultStringPieceExtension, "424"); - message.SetExtension(UnitTestProtoFile.DefaultCordExtension, "425"); - } - - internal static void ModifyRepeatedFields(TestAllTypes.Builder message) { - message.SetRepeatedInt32(1, 501); - message.SetRepeatedInt64(1, 502); - message.SetRepeatedUint32(1, 503); - message.SetRepeatedUint64(1, 504); - message.SetRepeatedSint32(1, 505); - message.SetRepeatedSint64(1, 506); - message.SetRepeatedFixed32(1, 507); - message.SetRepeatedFixed64(1, 508); - message.SetRepeatedSfixed32(1, 509); - message.SetRepeatedSfixed64(1, 510); - message.SetRepeatedFloat(1, 511); - message.SetRepeatedDouble(1, 512); - message.SetRepeatedBool(1, true); - message.SetRepeatedString(1, "515"); - message.SetRepeatedBytes(1, ToBytes("516")); - - message.SetRepeatedGroup(1, TestAllTypes.Types.RepeatedGroup.CreateBuilder().SetA(517).Build()); - message.SetRepeatedNestedMessage(1, TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(518).Build()); - message.SetRepeatedForeignMessage(1, ForeignMessage.CreateBuilder().SetC(519).Build()); - message.SetRepeatedImportMessage(1, ImportMessage.CreateBuilder().SetD(520).Build()); - - message.SetRepeatedNestedEnum(1, TestAllTypes.Types.NestedEnum.FOO); - message.SetRepeatedForeignEnum(1, ForeignEnum.FOREIGN_FOO); - message.SetRepeatedImportEnum(1, ImportEnum.IMPORT_FOO); - - message.SetRepeatedStringPiece(1, "524"); - message.SetRepeatedCord(1, "525"); - } - - internal static void AssertRepeatedFieldsModified(TestAllTypes message) { - // ModifyRepeatedFields only sets the second repeated element of each - // field. In addition to verifying this, we also verify that the first - // element and size were *not* modified. - Assert.AreEqual(2, message.RepeatedInt32Count); - Assert.AreEqual(2, message.RepeatedInt64Count); - Assert.AreEqual(2, message.RepeatedUint32Count); - Assert.AreEqual(2, message.RepeatedUint64Count); - Assert.AreEqual(2, message.RepeatedSint32Count); - Assert.AreEqual(2, message.RepeatedSint64Count); - Assert.AreEqual(2, message.RepeatedFixed32Count); - Assert.AreEqual(2, message.RepeatedFixed64Count); - Assert.AreEqual(2, message.RepeatedSfixed32Count); - Assert.AreEqual(2, message.RepeatedSfixed64Count); - Assert.AreEqual(2, message.RepeatedFloatCount); - Assert.AreEqual(2, message.RepeatedDoubleCount); - Assert.AreEqual(2, message.RepeatedBoolCount); - Assert.AreEqual(2, message.RepeatedStringCount); - Assert.AreEqual(2, message.RepeatedBytesCount); - - Assert.AreEqual(2, message.RepeatedGroupCount); - Assert.AreEqual(2, message.RepeatedNestedMessageCount); - Assert.AreEqual(2, message.RepeatedForeignMessageCount); - Assert.AreEqual(2, message.RepeatedImportMessageCount); - Assert.AreEqual(2, message.RepeatedNestedEnumCount); - Assert.AreEqual(2, message.RepeatedForeignEnumCount); - Assert.AreEqual(2, message.RepeatedImportEnumCount); - - Assert.AreEqual(2, message.RepeatedStringPieceCount); - Assert.AreEqual(2, message.RepeatedCordCount); - - Assert.AreEqual(201, message.GetRepeatedInt32(0)); - Assert.AreEqual(202L, message.GetRepeatedInt64(0)); - Assert.AreEqual(203U, message.GetRepeatedUint32(0)); - Assert.AreEqual(204UL, message.GetRepeatedUint64(0)); - Assert.AreEqual(205, message.GetRepeatedSint32(0)); - Assert.AreEqual(206L, message.GetRepeatedSint64(0)); - Assert.AreEqual(207U, message.GetRepeatedFixed32(0)); - Assert.AreEqual(208UL, message.GetRepeatedFixed64(0)); - Assert.AreEqual(209, message.GetRepeatedSfixed32(0)); - Assert.AreEqual(210L, message.GetRepeatedSfixed64(0)); - Assert.AreEqual(211F, message.GetRepeatedFloat(0)); - Assert.AreEqual(212D, message.GetRepeatedDouble(0)); - Assert.AreEqual(true, message.GetRepeatedBool(0)); - Assert.AreEqual("215", message.GetRepeatedString(0)); - Assert.AreEqual(ToBytes("216"), message.GetRepeatedBytes(0)); - - Assert.AreEqual(217, message.GetRepeatedGroup(0).A); - Assert.AreEqual(218, message.GetRepeatedNestedMessage(0).Bb); - Assert.AreEqual(219, message.GetRepeatedForeignMessage(0).C); - Assert.AreEqual(220, message.GetRepeatedImportMessage(0).D); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, message.GetRepeatedNestedEnum(0)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAR, message.GetRepeatedForeignEnum(0)); - Assert.AreEqual(ImportEnum.IMPORT_BAR, message.GetRepeatedImportEnum(0)); - - Assert.AreEqual("224", message.GetRepeatedStringPiece(0)); - Assert.AreEqual("225", message.GetRepeatedCord(0)); - - // Actually verify the second (modified) elements now. - Assert.AreEqual(501, message.GetRepeatedInt32(1)); - Assert.AreEqual(502L, message.GetRepeatedInt64(1)); - Assert.AreEqual(503U, message.GetRepeatedUint32(1)); - Assert.AreEqual(504UL, message.GetRepeatedUint64(1)); - Assert.AreEqual(505, message.GetRepeatedSint32(1)); - Assert.AreEqual(506L, message.GetRepeatedSint64(1)); - Assert.AreEqual(507U, message.GetRepeatedFixed32(1)); - Assert.AreEqual(508UL, message.GetRepeatedFixed64(1)); - Assert.AreEqual(509, message.GetRepeatedSfixed32(1)); - Assert.AreEqual(510L, message.GetRepeatedSfixed64(1)); - Assert.AreEqual(511F, message.GetRepeatedFloat(1)); - Assert.AreEqual(512D, message.GetRepeatedDouble(1)); - Assert.AreEqual(true, message.GetRepeatedBool(1)); - Assert.AreEqual("515", message.GetRepeatedString(1)); - Assert.AreEqual(ToBytes("516"), message.GetRepeatedBytes(1)); - - Assert.AreEqual(517, message.GetRepeatedGroup(1).A); - Assert.AreEqual(518, message.GetRepeatedNestedMessage(1).Bb); - Assert.AreEqual(519, message.GetRepeatedForeignMessage(1).C); - Assert.AreEqual(520, message.GetRepeatedImportMessage(1).D); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, message.GetRepeatedNestedEnum(1)); - Assert.AreEqual(ForeignEnum.FOREIGN_FOO, message.GetRepeatedForeignEnum(1)); - Assert.AreEqual(ImportEnum.IMPORT_FOO, message.GetRepeatedImportEnum(1)); - - Assert.AreEqual("524", message.GetRepeatedStringPiece(1)); - Assert.AreEqual("525", message.GetRepeatedCord(1)); - } - - /// <summary> - /// Helper to assert that sequences are equal. - /// </summary> - internal static void AssertEqual<T>(IEnumerable<T> first, IEnumerable<T> second) { - using (IEnumerator<T> firstEnumerator = first.GetEnumerator()) { - foreach (T secondElement in second) { - Assert.IsTrue(firstEnumerator.MoveNext(), "First enumerator ran out of elements too early."); - Assert.AreEqual(firstEnumerator.Current, secondElement); - } - Assert.IsFalse(firstEnumerator.MoveNext(), "Second enumerator ran out of elements too early."); - } - } - - internal static void AssertEqualBytes(byte[] expected, byte[] actual) { - Assert.AreEqual(ByteString.CopyFrom(expected), ByteString.CopyFrom(actual)); - } - - internal static void AssertAllExtensionsSet(TestAllExtensions message) { - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalInt32Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalInt64Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalUint32Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalUint64Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalSint32Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalSint64Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalFixed32Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalFixed64Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalSfixed32Extension)); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalSfixed64Extension)); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalFloatExtension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalDoubleExtension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalBoolExtension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalStringExtension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalBytesExtension )); - - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalGroupExtension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalNestedMessageExtension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalForeignMessageExtension)); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalImportMessageExtension )); - - Assert.IsTrue(message.GetExtension(UnitTestProtoFile.OptionalGroupExtension ).HasA); - Assert.IsTrue(message.GetExtension(UnitTestProtoFile.OptionalNestedMessageExtension ).HasBb); - Assert.IsTrue(message.GetExtension(UnitTestProtoFile.OptionalForeignMessageExtension).HasC); - Assert.IsTrue(message.GetExtension(UnitTestProtoFile.OptionalImportMessageExtension ).HasD); - - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalNestedEnumExtension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalForeignEnumExtension)); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalImportEnumExtension )); - - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalStringPieceExtension)); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalCordExtension)); - - Assert.AreEqual(101 , message.GetExtension(UnitTestProtoFile.OptionalInt32Extension )); - Assert.AreEqual(102L , message.GetExtension(UnitTestProtoFile.OptionalInt64Extension )); - Assert.AreEqual(103U , message.GetExtension(UnitTestProtoFile.OptionalUint32Extension )); - Assert.AreEqual(104UL , message.GetExtension(UnitTestProtoFile.OptionalUint64Extension )); - Assert.AreEqual(105 , message.GetExtension(UnitTestProtoFile.OptionalSint32Extension )); - Assert.AreEqual(106L , message.GetExtension(UnitTestProtoFile.OptionalSint64Extension )); - Assert.AreEqual(107U , message.GetExtension(UnitTestProtoFile.OptionalFixed32Extension )); - Assert.AreEqual(108UL , message.GetExtension(UnitTestProtoFile.OptionalFixed64Extension )); - Assert.AreEqual(109 , message.GetExtension(UnitTestProtoFile.OptionalSfixed32Extension)); - Assert.AreEqual(110L , message.GetExtension(UnitTestProtoFile.OptionalSfixed64Extension)); - Assert.AreEqual(111F , message.GetExtension(UnitTestProtoFile.OptionalFloatExtension )); - Assert.AreEqual(112D , message.GetExtension(UnitTestProtoFile.OptionalDoubleExtension )); - Assert.AreEqual(true , message.GetExtension(UnitTestProtoFile.OptionalBoolExtension )); - Assert.AreEqual("115", message.GetExtension(UnitTestProtoFile.OptionalStringExtension )); - Assert.AreEqual(ToBytes("116"), message.GetExtension(UnitTestProtoFile.OptionalBytesExtension)); - - Assert.AreEqual(117, message.GetExtension(UnitTestProtoFile.OptionalGroupExtension ).A); - Assert.AreEqual(118, message.GetExtension(UnitTestProtoFile.OptionalNestedMessageExtension ).Bb); - Assert.AreEqual(119, message.GetExtension(UnitTestProtoFile.OptionalForeignMessageExtension).C); - Assert.AreEqual(120, message.GetExtension(UnitTestProtoFile.OptionalImportMessageExtension ).D); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAZ, message.GetExtension(UnitTestProtoFile.OptionalNestedEnumExtension)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, message.GetExtension(UnitTestProtoFile.OptionalForeignEnumExtension)); - Assert.AreEqual(ImportEnum.IMPORT_BAZ, message.GetExtension(UnitTestProtoFile.OptionalImportEnumExtension)); - - Assert.AreEqual("124", message.GetExtension(UnitTestProtoFile.OptionalStringPieceExtension)); - Assert.AreEqual("125", message.GetExtension(UnitTestProtoFile.OptionalCordExtension)); - - // ----------------------------------------------------------------- - - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedInt32Extension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedInt64Extension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedUint32Extension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedUint64Extension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSint32Extension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSint64Extension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedFixed32Extension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedFixed64Extension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSfixed32Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSfixed64Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedFloatExtension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedDoubleExtension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedBoolExtension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedStringExtension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedBytesExtension )); - - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedGroupExtension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedNestedMessageExtension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedForeignMessageExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedImportMessageExtension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedNestedEnumExtension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedForeignEnumExtension )); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedImportEnumExtension )); - - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedStringPieceExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedCordExtension)); - - Assert.AreEqual(201 , message.GetExtension(UnitTestProtoFile.RepeatedInt32Extension , 0)); - Assert.AreEqual(202L , message.GetExtension(UnitTestProtoFile.RepeatedInt64Extension , 0)); - Assert.AreEqual(203U , message.GetExtension(UnitTestProtoFile.RepeatedUint32Extension , 0)); - Assert.AreEqual(204UL , message.GetExtension(UnitTestProtoFile.RepeatedUint64Extension , 0)); - Assert.AreEqual(205 , message.GetExtension(UnitTestProtoFile.RepeatedSint32Extension , 0)); - Assert.AreEqual(206L , message.GetExtension(UnitTestProtoFile.RepeatedSint64Extension , 0)); - Assert.AreEqual(207U , message.GetExtension(UnitTestProtoFile.RepeatedFixed32Extension , 0)); - Assert.AreEqual(208UL , message.GetExtension(UnitTestProtoFile.RepeatedFixed64Extension , 0)); - Assert.AreEqual(209 , message.GetExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 0)); - Assert.AreEqual(210L , message.GetExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 0)); - Assert.AreEqual(211F , message.GetExtension(UnitTestProtoFile.RepeatedFloatExtension , 0)); - Assert.AreEqual(212D , message.GetExtension(UnitTestProtoFile.RepeatedDoubleExtension , 0)); - Assert.AreEqual(true , message.GetExtension(UnitTestProtoFile.RepeatedBoolExtension , 0)); - Assert.AreEqual("215", message.GetExtension(UnitTestProtoFile.RepeatedStringExtension , 0)); - Assert.AreEqual(ToBytes("216"), message.GetExtension(UnitTestProtoFile.RepeatedBytesExtension, 0)); - - Assert.AreEqual(217, message.GetExtension(UnitTestProtoFile.RepeatedGroupExtension , 0).A); - Assert.AreEqual(218, message.GetExtension(UnitTestProtoFile.RepeatedNestedMessageExtension , 0).Bb); - Assert.AreEqual(219, message.GetExtension(UnitTestProtoFile.RepeatedForeignMessageExtension, 0).C); - Assert.AreEqual(220, message.GetExtension(UnitTestProtoFile.RepeatedImportMessageExtension , 0).D); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, message.GetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, 0)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAR, message.GetExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, 0)); - Assert.AreEqual(ImportEnum.IMPORT_BAR, message.GetExtension(UnitTestProtoFile.RepeatedImportEnumExtension, 0)); - - Assert.AreEqual("224", message.GetExtension(UnitTestProtoFile.RepeatedStringPieceExtension, 0)); - Assert.AreEqual("225", message.GetExtension(UnitTestProtoFile.RepeatedCordExtension, 0)); - - Assert.AreEqual(301 , message.GetExtension(UnitTestProtoFile.RepeatedInt32Extension , 1)); - Assert.AreEqual(302L , message.GetExtension(UnitTestProtoFile.RepeatedInt64Extension , 1)); - Assert.AreEqual(303U , message.GetExtension(UnitTestProtoFile.RepeatedUint32Extension , 1)); - Assert.AreEqual(304UL , message.GetExtension(UnitTestProtoFile.RepeatedUint64Extension , 1)); - Assert.AreEqual(305 , message.GetExtension(UnitTestProtoFile.RepeatedSint32Extension , 1)); - Assert.AreEqual(306L , message.GetExtension(UnitTestProtoFile.RepeatedSint64Extension , 1)); - Assert.AreEqual(307U , message.GetExtension(UnitTestProtoFile.RepeatedFixed32Extension , 1)); - Assert.AreEqual(308UL , message.GetExtension(UnitTestProtoFile.RepeatedFixed64Extension , 1)); - Assert.AreEqual(309 , message.GetExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 1)); - Assert.AreEqual(310L , message.GetExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 1)); - Assert.AreEqual(311F , message.GetExtension(UnitTestProtoFile.RepeatedFloatExtension , 1)); - Assert.AreEqual(312D , message.GetExtension(UnitTestProtoFile.RepeatedDoubleExtension , 1)); - Assert.AreEqual(false, message.GetExtension(UnitTestProtoFile.RepeatedBoolExtension , 1)); - Assert.AreEqual("315", message.GetExtension(UnitTestProtoFile.RepeatedStringExtension , 1)); - Assert.AreEqual(ToBytes("316"), message.GetExtension(UnitTestProtoFile.RepeatedBytesExtension, 1)); - - Assert.AreEqual(317, message.GetExtension(UnitTestProtoFile.RepeatedGroupExtension , 1).A); - Assert.AreEqual(318, message.GetExtension(UnitTestProtoFile.RepeatedNestedMessageExtension , 1).Bb); - Assert.AreEqual(319, message.GetExtension(UnitTestProtoFile.RepeatedForeignMessageExtension, 1).C); - Assert.AreEqual(320, message.GetExtension(UnitTestProtoFile.RepeatedImportMessageExtension , 1).D); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAZ, message.GetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, 1)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, message.GetExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, 1)); - Assert.AreEqual(ImportEnum.IMPORT_BAZ, message.GetExtension(UnitTestProtoFile.RepeatedImportEnumExtension, 1)); - - Assert.AreEqual("324", message.GetExtension(UnitTestProtoFile.RepeatedStringPieceExtension, 1)); - Assert.AreEqual("325", message.GetExtension(UnitTestProtoFile.RepeatedCordExtension, 1)); - - // ----------------------------------------------------------------- - - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultInt32Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultInt64Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultUint32Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultUint64Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultSint32Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultSint64Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultFixed32Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultFixed64Extension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultSfixed32Extension)); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultSfixed64Extension)); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultFloatExtension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultDoubleExtension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultBoolExtension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultStringExtension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultBytesExtension )); - - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultNestedEnumExtension )); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultForeignEnumExtension)); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultImportEnumExtension )); - - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultStringPieceExtension)); - Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultCordExtension)); - - Assert.AreEqual(401 , message.GetExtension(UnitTestProtoFile.DefaultInt32Extension )); - Assert.AreEqual(402L , message.GetExtension(UnitTestProtoFile.DefaultInt64Extension )); - Assert.AreEqual(403U , message.GetExtension(UnitTestProtoFile.DefaultUint32Extension )); - Assert.AreEqual(404UL , message.GetExtension(UnitTestProtoFile.DefaultUint64Extension )); - Assert.AreEqual(405 , message.GetExtension(UnitTestProtoFile.DefaultSint32Extension )); - Assert.AreEqual(406L , message.GetExtension(UnitTestProtoFile.DefaultSint64Extension )); - Assert.AreEqual(407U , message.GetExtension(UnitTestProtoFile.DefaultFixed32Extension )); - Assert.AreEqual(408UL , message.GetExtension(UnitTestProtoFile.DefaultFixed64Extension )); - Assert.AreEqual(409 , message.GetExtension(UnitTestProtoFile.DefaultSfixed32Extension)); - Assert.AreEqual(410L , message.GetExtension(UnitTestProtoFile.DefaultSfixed64Extension)); - Assert.AreEqual(411F , message.GetExtension(UnitTestProtoFile.DefaultFloatExtension )); - Assert.AreEqual(412D , message.GetExtension(UnitTestProtoFile.DefaultDoubleExtension )); - Assert.AreEqual(false, message.GetExtension(UnitTestProtoFile.DefaultBoolExtension )); - Assert.AreEqual("415", message.GetExtension(UnitTestProtoFile.DefaultStringExtension )); - Assert.AreEqual(ToBytes("416"), message.GetExtension(UnitTestProtoFile.DefaultBytesExtension)); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, message.GetExtension(UnitTestProtoFile.DefaultNestedEnumExtension )); - Assert.AreEqual(ForeignEnum.FOREIGN_FOO, message.GetExtension(UnitTestProtoFile.DefaultForeignEnumExtension)); - Assert.AreEqual(ImportEnum.IMPORT_FOO, message.GetExtension(UnitTestProtoFile.DefaultImportEnumExtension)); - - Assert.AreEqual("424", message.GetExtension(UnitTestProtoFile.DefaultStringPieceExtension)); - Assert.AreEqual("425", message.GetExtension(UnitTestProtoFile.DefaultCordExtension)); - } - - /// <summary> - /// Modifies the repeated extensions of the given message to contain the values - /// expected by AssertRepeatedExtensionsModified. - /// </summary> - internal static void ModifyRepeatedExtensions(TestAllExtensions.Builder message) { - message.SetExtension(UnitTestProtoFile.RepeatedInt32Extension, 1, 501); - message.SetExtension(UnitTestProtoFile.RepeatedInt64Extension, 1, 502L); - message.SetExtension(UnitTestProtoFile.RepeatedUint32Extension, 1, 503U); - message.SetExtension(UnitTestProtoFile.RepeatedUint64Extension, 1, 504UL); - message.SetExtension(UnitTestProtoFile.RepeatedSint32Extension, 1, 505); - message.SetExtension(UnitTestProtoFile.RepeatedSint64Extension, 1, 506L); - message.SetExtension(UnitTestProtoFile.RepeatedFixed32Extension, 1, 507U); - message.SetExtension(UnitTestProtoFile.RepeatedFixed64Extension, 1, 508UL); - message.SetExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 1, 509); - message.SetExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 1, 510L); - message.SetExtension(UnitTestProtoFile.RepeatedFloatExtension, 1, 511F); - message.SetExtension(UnitTestProtoFile.RepeatedDoubleExtension, 1, 512D); - message.SetExtension(UnitTestProtoFile.RepeatedBoolExtension, 1, true); - message.SetExtension(UnitTestProtoFile.RepeatedStringExtension, 1, "515"); - message.SetExtension(UnitTestProtoFile.RepeatedBytesExtension, 1, ToBytes("516")); - - message.SetExtension(UnitTestProtoFile.RepeatedGroupExtension, 1, RepeatedGroup_extension.CreateBuilder().SetA(517).Build()); - message.SetExtension(UnitTestProtoFile.RepeatedNestedMessageExtension, 1, TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(518).Build()); - message.SetExtension(UnitTestProtoFile.RepeatedForeignMessageExtension, 1, ForeignMessage.CreateBuilder().SetC(519).Build()); - message.SetExtension(UnitTestProtoFile.RepeatedImportMessageExtension, 1, ImportMessage.CreateBuilder().SetD(520).Build()); - - message.SetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, 1, TestAllTypes.Types.NestedEnum.FOO); - message.SetExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, 1, ForeignEnum.FOREIGN_FOO); - message.SetExtension(UnitTestProtoFile.RepeatedImportEnumExtension, 1, ImportEnum.IMPORT_FOO); - - message.SetExtension(UnitTestProtoFile.RepeatedStringPieceExtension, 1, "524"); - message.SetExtension(UnitTestProtoFile.RepeatedCordExtension, 1, "525"); - } - - /// <summary> - /// Asserts that all repeated extensions are set to the values assigned by - /// SetAllExtensions follwed by ModifyRepeatedExtensions. - /// </summary> - internal static void AssertRepeatedExtensionsModified(TestAllExtensions message) { - // ModifyRepeatedFields only sets the second repeated element of each - // field. In addition to verifying this, we also verify that the first - // element and size were *not* modified. - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedInt32Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedInt64Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedUint32Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedUint64Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSint32Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSint64Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedFixed32Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedFixed64Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSfixed32Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSfixed64Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedFloatExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedDoubleExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedBoolExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedStringExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedBytesExtension)); - - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedGroupExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedNestedMessageExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedForeignMessageExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedImportMessageExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedNestedEnumExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedForeignEnumExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedImportEnumExtension)); - - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedStringPieceExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedCordExtension)); - - Assert.AreEqual(201, message.GetExtension(UnitTestProtoFile.RepeatedInt32Extension, 0)); - Assert.AreEqual(202L, message.GetExtension(UnitTestProtoFile.RepeatedInt64Extension, 0)); - Assert.AreEqual(203U, message.GetExtension(UnitTestProtoFile.RepeatedUint32Extension, 0)); - Assert.AreEqual(204UL, message.GetExtension(UnitTestProtoFile.RepeatedUint64Extension, 0)); - Assert.AreEqual(205, message.GetExtension(UnitTestProtoFile.RepeatedSint32Extension, 0)); - Assert.AreEqual(206L, message.GetExtension(UnitTestProtoFile.RepeatedSint64Extension, 0)); - Assert.AreEqual(207U, message.GetExtension(UnitTestProtoFile.RepeatedFixed32Extension, 0)); - Assert.AreEqual(208UL, message.GetExtension(UnitTestProtoFile.RepeatedFixed64Extension, 0)); - Assert.AreEqual(209, message.GetExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 0)); - Assert.AreEqual(210L, message.GetExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 0)); - Assert.AreEqual(211F, message.GetExtension(UnitTestProtoFile.RepeatedFloatExtension, 0)); - Assert.AreEqual(212D, message.GetExtension(UnitTestProtoFile.RepeatedDoubleExtension, 0)); - Assert.AreEqual(true, message.GetExtension(UnitTestProtoFile.RepeatedBoolExtension, 0)); - Assert.AreEqual("215", message.GetExtension(UnitTestProtoFile.RepeatedStringExtension, 0)); - Assert.AreEqual(ToBytes("216"), message.GetExtension(UnitTestProtoFile.RepeatedBytesExtension, 0)); - - Assert.AreEqual(217, message.GetExtension(UnitTestProtoFile.RepeatedGroupExtension, 0).A); - Assert.AreEqual(218, message.GetExtension(UnitTestProtoFile.RepeatedNestedMessageExtension, 0).Bb); - Assert.AreEqual(219, message.GetExtension(UnitTestProtoFile.RepeatedForeignMessageExtension, 0).C); - Assert.AreEqual(220, message.GetExtension(UnitTestProtoFile.RepeatedImportMessageExtension, 0).D); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, message.GetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, 0)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAR, message.GetExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, 0)); - Assert.AreEqual(ImportEnum.IMPORT_BAR, message.GetExtension(UnitTestProtoFile.RepeatedImportEnumExtension, 0)); - - Assert.AreEqual("224", message.GetExtension(UnitTestProtoFile.RepeatedStringPieceExtension, 0)); - Assert.AreEqual("225", message.GetExtension(UnitTestProtoFile.RepeatedCordExtension, 0)); - - // Actually verify the second (modified) elements now. - Assert.AreEqual(501, message.GetExtension(UnitTestProtoFile.RepeatedInt32Extension, 1)); - Assert.AreEqual(502L, message.GetExtension(UnitTestProtoFile.RepeatedInt64Extension, 1)); - Assert.AreEqual(503U, message.GetExtension(UnitTestProtoFile.RepeatedUint32Extension, 1)); - Assert.AreEqual(504UL, message.GetExtension(UnitTestProtoFile.RepeatedUint64Extension, 1)); - Assert.AreEqual(505, message.GetExtension(UnitTestProtoFile.RepeatedSint32Extension, 1)); - Assert.AreEqual(506L, message.GetExtension(UnitTestProtoFile.RepeatedSint64Extension, 1)); - Assert.AreEqual(507U, message.GetExtension(UnitTestProtoFile.RepeatedFixed32Extension, 1)); - Assert.AreEqual(508UL, message.GetExtension(UnitTestProtoFile.RepeatedFixed64Extension, 1)); - Assert.AreEqual(509, message.GetExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 1)); - Assert.AreEqual(510L, message.GetExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 1)); - Assert.AreEqual(511F, message.GetExtension(UnitTestProtoFile.RepeatedFloatExtension, 1)); - Assert.AreEqual(512D, message.GetExtension(UnitTestProtoFile.RepeatedDoubleExtension, 1)); - Assert.AreEqual(true, message.GetExtension(UnitTestProtoFile.RepeatedBoolExtension, 1)); - Assert.AreEqual("515", message.GetExtension(UnitTestProtoFile.RepeatedStringExtension, 1)); - Assert.AreEqual(ToBytes("516"), message.GetExtension(UnitTestProtoFile.RepeatedBytesExtension, 1)); - - Assert.AreEqual(517, message.GetExtension(UnitTestProtoFile.RepeatedGroupExtension, 1).A); - Assert.AreEqual(518, message.GetExtension(UnitTestProtoFile.RepeatedNestedMessageExtension, 1).Bb); - Assert.AreEqual(519, message.GetExtension(UnitTestProtoFile.RepeatedForeignMessageExtension, 1).C); - Assert.AreEqual(520, message.GetExtension(UnitTestProtoFile.RepeatedImportMessageExtension, 1).D); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, message.GetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, 1)); - Assert.AreEqual(ForeignEnum.FOREIGN_FOO, message.GetExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, 1)); - Assert.AreEqual(ImportEnum.IMPORT_FOO, message.GetExtension(UnitTestProtoFile.RepeatedImportEnumExtension, 1)); - - Assert.AreEqual("524", message.GetExtension(UnitTestProtoFile.RepeatedStringPieceExtension, 1)); - Assert.AreEqual("525", message.GetExtension(UnitTestProtoFile.RepeatedCordExtension, 1)); - } - - internal static void AssertExtensionsClear(TestAllExtensions message) { - // HasBlah() should initially be false for all optional fields. - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalInt32Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalInt64Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalUint32Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalUint64Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalSint32Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalSint64Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalFixed32Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalFixed64Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalSfixed32Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalSfixed64Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalFloatExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalDoubleExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalBoolExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalStringExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalBytesExtension)); - - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalGroupExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalNestedMessageExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalForeignMessageExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalImportMessageExtension)); - - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalNestedEnumExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalForeignEnumExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalImportEnumExtension)); - - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalStringPieceExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalCordExtension)); - - // Optional fields without defaults are set to zero or something like it. - Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalInt32Extension)); - Assert.AreEqual(0L, message.GetExtension(UnitTestProtoFile.OptionalInt64Extension)); - Assert.AreEqual(0U, message.GetExtension(UnitTestProtoFile.OptionalUint32Extension)); - Assert.AreEqual(0UL, message.GetExtension(UnitTestProtoFile.OptionalUint64Extension)); - Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalSint32Extension)); - Assert.AreEqual(0L, message.GetExtension(UnitTestProtoFile.OptionalSint64Extension)); - Assert.AreEqual(0U, message.GetExtension(UnitTestProtoFile.OptionalFixed32Extension)); - Assert.AreEqual(0UL, message.GetExtension(UnitTestProtoFile.OptionalFixed64Extension)); - Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalSfixed32Extension)); - Assert.AreEqual(0L, message.GetExtension(UnitTestProtoFile.OptionalSfixed64Extension)); - Assert.AreEqual(0F, message.GetExtension(UnitTestProtoFile.OptionalFloatExtension)); - Assert.AreEqual(0D, message.GetExtension(UnitTestProtoFile.OptionalDoubleExtension)); - Assert.AreEqual(false, message.GetExtension(UnitTestProtoFile.OptionalBoolExtension)); - Assert.AreEqual("", message.GetExtension(UnitTestProtoFile.OptionalStringExtension)); - Assert.AreEqual(ByteString.Empty, message.GetExtension(UnitTestProtoFile.OptionalBytesExtension)); - - // Embedded messages should also be clear. - Assert.IsFalse(message.GetExtension(UnitTestProtoFile.OptionalGroupExtension).HasA); - Assert.IsFalse(message.GetExtension(UnitTestProtoFile.OptionalNestedMessageExtension).HasBb); - Assert.IsFalse(message.GetExtension(UnitTestProtoFile.OptionalForeignMessageExtension).HasC); - Assert.IsFalse(message.GetExtension(UnitTestProtoFile.OptionalImportMessageExtension).HasD); - - Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalGroupExtension).A); - Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalNestedMessageExtension).Bb); - Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalForeignMessageExtension).C); - Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalImportMessageExtension).D); - - // Enums without defaults are set to the first value in the enum. - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, message.GetExtension(UnitTestProtoFile.OptionalNestedEnumExtension)); - Assert.AreEqual(ForeignEnum.FOREIGN_FOO, message.GetExtension(UnitTestProtoFile.OptionalForeignEnumExtension)); - Assert.AreEqual(ImportEnum.IMPORT_FOO, message.GetExtension(UnitTestProtoFile.OptionalImportEnumExtension)); - - Assert.AreEqual("", message.GetExtension(UnitTestProtoFile.OptionalStringPieceExtension)); - Assert.AreEqual("", message.GetExtension(UnitTestProtoFile.OptionalCordExtension)); - - // Repeated fields are empty. - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedInt32Extension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedInt64Extension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedUint32Extension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedUint64Extension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedSint32Extension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedSint64Extension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedFixed32Extension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedFixed64Extension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedSfixed32Extension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedSfixed64Extension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedFloatExtension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedDoubleExtension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedBoolExtension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedStringExtension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedBytesExtension)); - - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedGroupExtension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedNestedMessageExtension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedForeignMessageExtension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedImportMessageExtension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedNestedEnumExtension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedForeignEnumExtension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedImportEnumExtension)); - - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedStringPieceExtension)); - Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedCordExtension)); - - // HasBlah() should also be false for all default fields. - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultInt32Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultInt64Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultUint32Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultUint64Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultSint32Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultSint64Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultFixed32Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultFixed64Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultSfixed32Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultSfixed64Extension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultFloatExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultDoubleExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultBoolExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultStringExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultBytesExtension)); - - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultNestedEnumExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultForeignEnumExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultImportEnumExtension)); - - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultStringPieceExtension)); - Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultCordExtension)); - - // Fields with defaults have their default values (duh). - Assert.AreEqual(41, message.GetExtension(UnitTestProtoFile.DefaultInt32Extension)); - Assert.AreEqual(42L, message.GetExtension(UnitTestProtoFile.DefaultInt64Extension)); - Assert.AreEqual(43U, message.GetExtension(UnitTestProtoFile.DefaultUint32Extension)); - Assert.AreEqual(44UL, message.GetExtension(UnitTestProtoFile.DefaultUint64Extension)); - Assert.AreEqual(-45, message.GetExtension(UnitTestProtoFile.DefaultSint32Extension)); - Assert.AreEqual(46L, message.GetExtension(UnitTestProtoFile.DefaultSint64Extension)); - Assert.AreEqual(47U, message.GetExtension(UnitTestProtoFile.DefaultFixed32Extension)); - Assert.AreEqual(48UL, message.GetExtension(UnitTestProtoFile.DefaultFixed64Extension)); - Assert.AreEqual(49, message.GetExtension(UnitTestProtoFile.DefaultSfixed32Extension)); - Assert.AreEqual(-50L, message.GetExtension(UnitTestProtoFile.DefaultSfixed64Extension)); - Assert.AreEqual(51.5F, message.GetExtension(UnitTestProtoFile.DefaultFloatExtension)); - Assert.AreEqual(52e3D, message.GetExtension(UnitTestProtoFile.DefaultDoubleExtension)); - Assert.AreEqual(true, message.GetExtension(UnitTestProtoFile.DefaultBoolExtension)); - Assert.AreEqual("hello", message.GetExtension(UnitTestProtoFile.DefaultStringExtension)); - Assert.AreEqual(ToBytes("world"), message.GetExtension(UnitTestProtoFile.DefaultBytesExtension)); - - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, message.GetExtension(UnitTestProtoFile.DefaultNestedEnumExtension)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAR, message.GetExtension(UnitTestProtoFile.DefaultForeignEnumExtension)); - Assert.AreEqual(ImportEnum.IMPORT_BAR, message.GetExtension(UnitTestProtoFile.DefaultImportEnumExtension)); - - Assert.AreEqual("abc", message.GetExtension(UnitTestProtoFile.DefaultStringPieceExtension)); - Assert.AreEqual("123", message.GetExtension(UnitTestProtoFile.DefaultCordExtension)); - } - - /// <summary> - /// Set every field of the specified message to a unique value. - /// </summary> - public static void SetPackedFields(TestPackedTypes.Builder message) { - message.AddPackedInt32(601); - message.AddPackedInt64(602); - message.AddPackedUint32(603); - message.AddPackedUint64(604); - message.AddPackedSint32(605); - message.AddPackedSint64(606); - message.AddPackedFixed32(607); - message.AddPackedFixed64(608); - message.AddPackedSfixed32(609); - message.AddPackedSfixed64(610); - message.AddPackedFloat(611); - message.AddPackedDouble(612); - message.AddPackedBool(true); - message.AddPackedEnum(ForeignEnum.FOREIGN_BAR); - // Add a second one of each field. - message.AddPackedInt32(701); - message.AddPackedInt64(702); - message.AddPackedUint32(703); - message.AddPackedUint64(704); - message.AddPackedSint32(705); - message.AddPackedSint64(706); - message.AddPackedFixed32(707); - message.AddPackedFixed64(708); - message.AddPackedSfixed32(709); - message.AddPackedSfixed64(710); - message.AddPackedFloat(711); - message.AddPackedDouble(712); - message.AddPackedBool(false); - message.AddPackedEnum(ForeignEnum.FOREIGN_BAZ); - } - - /// <summary> - /// Asserts that all the fields of the specified message are set to the values assigned - /// in SetPackedFields. - /// </summary> - public static void AssertPackedFieldsSet(TestPackedTypes message) { - Assert.AreEqual(2, message.PackedInt32Count); - Assert.AreEqual(2, message.PackedInt64Count); - Assert.AreEqual(2, message.PackedUint32Count); - Assert.AreEqual(2, message.PackedUint64Count); - Assert.AreEqual(2, message.PackedSint32Count); - Assert.AreEqual(2, message.PackedSint64Count); - Assert.AreEqual(2, message.PackedFixed32Count); - Assert.AreEqual(2, message.PackedFixed64Count); - Assert.AreEqual(2, message.PackedSfixed32Count); - Assert.AreEqual(2, message.PackedSfixed64Count); - Assert.AreEqual(2, message.PackedFloatCount); - Assert.AreEqual(2, message.PackedDoubleCount); - Assert.AreEqual(2, message.PackedBoolCount); - Assert.AreEqual(2, message.PackedEnumCount); - Assert.AreEqual(601, message.GetPackedInt32(0)); - Assert.AreEqual(602, message.GetPackedInt64(0)); - Assert.AreEqual(603, message.GetPackedUint32(0)); - Assert.AreEqual(604, message.GetPackedUint64(0)); - Assert.AreEqual(605, message.GetPackedSint32(0)); - Assert.AreEqual(606, message.GetPackedSint64(0)); - Assert.AreEqual(607, message.GetPackedFixed32(0)); - Assert.AreEqual(608, message.GetPackedFixed64(0)); - Assert.AreEqual(609, message.GetPackedSfixed32(0)); - Assert.AreEqual(610, message.GetPackedSfixed64(0)); - Assert.AreEqual(611, message.GetPackedFloat(0), 0.0); - Assert.AreEqual(612, message.GetPackedDouble(0), 0.0); - Assert.AreEqual(true, message.GetPackedBool(0)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAR, message.GetPackedEnum(0)); - Assert.AreEqual(701, message.GetPackedInt32(1)); - Assert.AreEqual(702, message.GetPackedInt64(1)); - Assert.AreEqual(703, message.GetPackedUint32(1)); - Assert.AreEqual(704, message.GetPackedUint64(1)); - Assert.AreEqual(705, message.GetPackedSint32(1)); - Assert.AreEqual(706, message.GetPackedSint64(1)); - Assert.AreEqual(707, message.GetPackedFixed32(1)); - Assert.AreEqual(708, message.GetPackedFixed64(1)); - Assert.AreEqual(709, message.GetPackedSfixed32(1)); - Assert.AreEqual(710, message.GetPackedSfixed64(1)); - Assert.AreEqual(711, message.GetPackedFloat(1), 0.0); - Assert.AreEqual(712, message.GetPackedDouble(1), 0.0); - Assert.AreEqual(false, message.GetPackedBool(1)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, message.GetPackedEnum(1)); - } - - public static void SetPackedExtensions(TestPackedExtensions.Builder message) { - message.AddExtension(UnitTestProtoFile.PackedInt32Extension, 601); - message.AddExtension(UnitTestProtoFile.PackedInt64Extension, 602L); - message.AddExtension(UnitTestProtoFile.PackedUint32Extension, 603U); - message.AddExtension(UnitTestProtoFile.PackedUint64Extension, 604UL); - message.AddExtension(UnitTestProtoFile.PackedSint32Extension, 605); - message.AddExtension(UnitTestProtoFile.PackedSint64Extension, 606L); - message.AddExtension(UnitTestProtoFile.PackedFixed32Extension, 607U); - message.AddExtension(UnitTestProtoFile.PackedFixed64Extension, 608UL); - message.AddExtension(UnitTestProtoFile.PackedSfixed32Extension, 609); - message.AddExtension(UnitTestProtoFile.PackedSfixed64Extension, 610L); - message.AddExtension(UnitTestProtoFile.PackedFloatExtension, 611F); - message.AddExtension(UnitTestProtoFile.PackedDoubleExtension, 612D); - message.AddExtension(UnitTestProtoFile.PackedBoolExtension, true); - message.AddExtension(UnitTestProtoFile.PackedEnumExtension, ForeignEnum.FOREIGN_BAR); - // Add a second one of each field. - message.AddExtension(UnitTestProtoFile.PackedInt32Extension, 701); - message.AddExtension(UnitTestProtoFile.PackedInt64Extension, 702L); - message.AddExtension(UnitTestProtoFile.PackedUint32Extension, 703U); - message.AddExtension(UnitTestProtoFile.PackedUint64Extension, 704UL); - message.AddExtension(UnitTestProtoFile.PackedSint32Extension, 705); - message.AddExtension(UnitTestProtoFile.PackedSint64Extension, 706L); - message.AddExtension(UnitTestProtoFile.PackedFixed32Extension, 707U); - message.AddExtension(UnitTestProtoFile.PackedFixed64Extension, 708UL); - message.AddExtension(UnitTestProtoFile.PackedSfixed32Extension, 709); - message.AddExtension(UnitTestProtoFile.PackedSfixed64Extension, 710L); - message.AddExtension(UnitTestProtoFile.PackedFloatExtension, 711F); - message.AddExtension(UnitTestProtoFile.PackedDoubleExtension, 712D); - message.AddExtension(UnitTestProtoFile.PackedBoolExtension, false); - message.AddExtension(UnitTestProtoFile.PackedEnumExtension, ForeignEnum.FOREIGN_BAZ); - } - - public static void AssertPackedExtensionsSet(TestPackedExtensions message) { - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedInt32Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedInt64Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedUint32Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedUint64Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedSint32Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedSint64Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedFixed32Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedFixed64Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedSfixed32Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedSfixed64Extension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedFloatExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedDoubleExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedBoolExtension)); - Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedEnumExtension)); - Assert.AreEqual(601, message.GetExtension(UnitTestProtoFile.PackedInt32Extension, 0)); - Assert.AreEqual(602L, message.GetExtension(UnitTestProtoFile.PackedInt64Extension, 0)); - Assert.AreEqual(603, message.GetExtension(UnitTestProtoFile.PackedUint32Extension, 0)); - Assert.AreEqual(604L, message.GetExtension(UnitTestProtoFile.PackedUint64Extension, 0)); - Assert.AreEqual(605, message.GetExtension(UnitTestProtoFile.PackedSint32Extension, 0)); - Assert.AreEqual(606L, message.GetExtension(UnitTestProtoFile.PackedSint64Extension, 0)); - Assert.AreEqual(607, message.GetExtension(UnitTestProtoFile.PackedFixed32Extension, 0)); - Assert.AreEqual(608L, message.GetExtension(UnitTestProtoFile.PackedFixed64Extension, 0)); - Assert.AreEqual(609, message.GetExtension(UnitTestProtoFile.PackedSfixed32Extension, 0)); - Assert.AreEqual(610L, message.GetExtension(UnitTestProtoFile.PackedSfixed64Extension, 0)); - Assert.AreEqual(611F, message.GetExtension(UnitTestProtoFile.PackedFloatExtension, 0)); - Assert.AreEqual(612D, message.GetExtension(UnitTestProtoFile.PackedDoubleExtension, 0)); - Assert.AreEqual(true, message.GetExtension(UnitTestProtoFile.PackedBoolExtension, 0)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAR, - message.GetExtension(UnitTestProtoFile.PackedEnumExtension, 0)); - Assert.AreEqual(701, message.GetExtension(UnitTestProtoFile.PackedInt32Extension, 1)); - Assert.AreEqual(702L, message.GetExtension(UnitTestProtoFile.PackedInt64Extension, 1)); - Assert.AreEqual(703, message.GetExtension(UnitTestProtoFile.PackedUint32Extension, 1)); - Assert.AreEqual(704L, message.GetExtension(UnitTestProtoFile.PackedUint64Extension, 1)); - Assert.AreEqual(705, message.GetExtension(UnitTestProtoFile.PackedSint32Extension, 1)); - Assert.AreEqual(706L, message.GetExtension(UnitTestProtoFile.PackedSint64Extension, 1)); - Assert.AreEqual(707, message.GetExtension(UnitTestProtoFile.PackedFixed32Extension, 1)); - Assert.AreEqual(708L, message.GetExtension(UnitTestProtoFile.PackedFixed64Extension, 1)); - Assert.AreEqual(709, message.GetExtension(UnitTestProtoFile.PackedSfixed32Extension, 1)); - Assert.AreEqual(710L, message.GetExtension(UnitTestProtoFile.PackedSfixed64Extension, 1)); - Assert.AreEqual(711F, message.GetExtension(UnitTestProtoFile.PackedFloatExtension, 1)); - Assert.AreEqual(712D, message.GetExtension(UnitTestProtoFile.PackedDoubleExtension, 1)); - Assert.AreEqual(false, message.GetExtension(UnitTestProtoFile.PackedBoolExtension, 1)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, message.GetExtension(UnitTestProtoFile.PackedEnumExtension, 1)); - } - - private static ByteString goldenPackedFieldsMessage = null; - - /// <summary> - /// Get the bytes of the "golden packed fields message". This is a serialized - /// TestPackedTypes with all fields set as they would be by SetPackedFields, - /// but it is loaded from a file on disk rather than generated dynamically. - /// The file is actually generated by C++ code, so testing against it verifies compatibility - /// with C++. - /// </summary> - public static ByteString GetGoldenPackedFieldsMessage() { - if (goldenPackedFieldsMessage == null) { - goldenPackedFieldsMessage = ReadBytesFromFile("golden_packed_fields_message"); - } - return goldenPackedFieldsMessage; - } - - private static readonly string[] TestCultures = { "en-US", "en-GB", "fr-FR", "de-DE" }; - - public static void TestInMultipleCultures(Action test) { - CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture; - foreach (string culture in TestCultures) { - try { - Thread.CurrentThread.CurrentCulture = new CultureInfo(culture); - test(); - } finally { - Thread.CurrentThread.CurrentCulture = originalCulture; - } - } - } - - /// <summary> - /// Helper to construct a byte array from a bunch of bytes. - /// </summary> - internal static byte[] Bytes(params byte[] bytesAsInts) { - byte[] bytes = new byte[bytesAsInts.Length]; - for (int i = 0; i < bytesAsInts.Length; i++) { - bytes[i] = (byte)bytesAsInts[i]; - } - return bytes; - } - - internal static void AssertArgumentNullException(Action action) { - try { - action(); - Assert.Fail("Exception was not thrown"); - } catch (ArgumentNullException) { - // We expect this exception. - } - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Text;
+using System.Threading;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ internal static class TestUtil
+ {
+ private static string testDataDirectory;
+ private static ByteString goldenMessage = null;
+
+ internal static string TestDataDirectory
+ {
+ get
+ {
+ if (testDataDirectory != null)
+ {
+ return testDataDirectory;
+ }
+
+ DirectoryInfo ancestor = new DirectoryInfo(".");
+ // Search each parent directory looking for "testdata".
+ while (ancestor != null)
+ {
+ string candidate = Path.Combine(ancestor.FullName, "testdata");
+ if (Directory.Exists(candidate))
+ {
+ testDataDirectory = candidate;
+ return candidate;
+ }
+ ancestor = ancestor.Parent;
+ }
+ // TODO(jonskeet): Come up with a better exception to throw
+ throw new Exception("Unable to find directory containing test files");
+ }
+ }
+
+ internal static ByteString GoldenMessage
+ {
+ get
+ {
+ if (goldenMessage == null)
+ {
+ goldenMessage = ReadBytesFromFile("golden_message");
+ }
+ return goldenMessage;
+ }
+ }
+
+ /// <summary>
+ /// Creates an unmodifiable ExtensionRegistry containing all the extensions
+ /// of TestAllExtensions.
+ /// </summary>
+ /// <returns></returns>
+ internal static ExtensionRegistry CreateExtensionRegistry()
+ {
+ ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
+ RegisterAllExtensions(registry);
+ return registry.AsReadOnly();
+ }
+
+ /// <summary>
+ /// Registers all of the extensions in TestAllExtensions with the given
+ /// ExtensionRegistry.
+ /// </summary>
+ internal static void RegisterAllExtensions(ExtensionRegistry registry)
+ {
+ registry.Add(UnitTestProtoFile.OptionalInt32Extension);
+ registry.Add(UnitTestProtoFile.OptionalInt64Extension);
+ registry.Add(UnitTestProtoFile.OptionalUint32Extension);
+ registry.Add(UnitTestProtoFile.OptionalUint64Extension);
+ registry.Add(UnitTestProtoFile.OptionalSint32Extension);
+ registry.Add(UnitTestProtoFile.OptionalSint64Extension);
+ registry.Add(UnitTestProtoFile.OptionalFixed32Extension);
+ registry.Add(UnitTestProtoFile.OptionalFixed64Extension);
+ registry.Add(UnitTestProtoFile.OptionalSfixed32Extension);
+ registry.Add(UnitTestProtoFile.OptionalSfixed64Extension);
+ registry.Add(UnitTestProtoFile.OptionalFloatExtension);
+ registry.Add(UnitTestProtoFile.OptionalDoubleExtension);
+ registry.Add(UnitTestProtoFile.OptionalBoolExtension);
+ registry.Add(UnitTestProtoFile.OptionalStringExtension);
+ registry.Add(UnitTestProtoFile.OptionalBytesExtension);
+ registry.Add(UnitTestProtoFile.OptionalGroupExtension);
+ registry.Add(UnitTestProtoFile.OptionalNestedMessageExtension);
+ registry.Add(UnitTestProtoFile.OptionalForeignMessageExtension);
+ registry.Add(UnitTestProtoFile.OptionalImportMessageExtension);
+ registry.Add(UnitTestProtoFile.OptionalNestedEnumExtension);
+ registry.Add(UnitTestProtoFile.OptionalForeignEnumExtension);
+ registry.Add(UnitTestProtoFile.OptionalImportEnumExtension);
+ registry.Add(UnitTestProtoFile.OptionalStringPieceExtension);
+ registry.Add(UnitTestProtoFile.OptionalCordExtension);
+
+ registry.Add(UnitTestProtoFile.RepeatedInt32Extension);
+ registry.Add(UnitTestProtoFile.RepeatedInt64Extension);
+ registry.Add(UnitTestProtoFile.RepeatedUint32Extension);
+ registry.Add(UnitTestProtoFile.RepeatedUint64Extension);
+ registry.Add(UnitTestProtoFile.RepeatedSint32Extension);
+ registry.Add(UnitTestProtoFile.RepeatedSint64Extension);
+ registry.Add(UnitTestProtoFile.RepeatedFixed32Extension);
+ registry.Add(UnitTestProtoFile.RepeatedFixed64Extension);
+ registry.Add(UnitTestProtoFile.RepeatedSfixed32Extension);
+ registry.Add(UnitTestProtoFile.RepeatedSfixed64Extension);
+ registry.Add(UnitTestProtoFile.RepeatedFloatExtension);
+ registry.Add(UnitTestProtoFile.RepeatedDoubleExtension);
+ registry.Add(UnitTestProtoFile.RepeatedBoolExtension);
+ registry.Add(UnitTestProtoFile.RepeatedStringExtension);
+ registry.Add(UnitTestProtoFile.RepeatedBytesExtension);
+ registry.Add(UnitTestProtoFile.RepeatedGroupExtension);
+ registry.Add(UnitTestProtoFile.RepeatedNestedMessageExtension);
+ registry.Add(UnitTestProtoFile.RepeatedForeignMessageExtension);
+ registry.Add(UnitTestProtoFile.RepeatedImportMessageExtension);
+ registry.Add(UnitTestProtoFile.RepeatedNestedEnumExtension);
+ registry.Add(UnitTestProtoFile.RepeatedForeignEnumExtension);
+ registry.Add(UnitTestProtoFile.RepeatedImportEnumExtension);
+ registry.Add(UnitTestProtoFile.RepeatedStringPieceExtension);
+ registry.Add(UnitTestProtoFile.RepeatedCordExtension);
+
+ registry.Add(UnitTestProtoFile.DefaultInt32Extension);
+ registry.Add(UnitTestProtoFile.DefaultInt64Extension);
+ registry.Add(UnitTestProtoFile.DefaultUint32Extension);
+ registry.Add(UnitTestProtoFile.DefaultUint64Extension);
+ registry.Add(UnitTestProtoFile.DefaultSint32Extension);
+ registry.Add(UnitTestProtoFile.DefaultSint64Extension);
+ registry.Add(UnitTestProtoFile.DefaultFixed32Extension);
+ registry.Add(UnitTestProtoFile.DefaultFixed64Extension);
+ registry.Add(UnitTestProtoFile.DefaultSfixed32Extension);
+ registry.Add(UnitTestProtoFile.DefaultSfixed64Extension);
+ registry.Add(UnitTestProtoFile.DefaultFloatExtension);
+ registry.Add(UnitTestProtoFile.DefaultDoubleExtension);
+ registry.Add(UnitTestProtoFile.DefaultBoolExtension);
+ registry.Add(UnitTestProtoFile.DefaultStringExtension);
+ registry.Add(UnitTestProtoFile.DefaultBytesExtension);
+ registry.Add(UnitTestProtoFile.DefaultNestedEnumExtension);
+ registry.Add(UnitTestProtoFile.DefaultForeignEnumExtension);
+ registry.Add(UnitTestProtoFile.DefaultImportEnumExtension);
+ registry.Add(UnitTestProtoFile.DefaultStringPieceExtension);
+ registry.Add(UnitTestProtoFile.DefaultCordExtension);
+
+ registry.Add(UnitTestProtoFile.PackedInt32Extension);
+ registry.Add(UnitTestProtoFile.PackedInt64Extension);
+ registry.Add(UnitTestProtoFile.PackedUint32Extension);
+ registry.Add(UnitTestProtoFile.PackedUint64Extension);
+ registry.Add(UnitTestProtoFile.PackedSint32Extension);
+ registry.Add(UnitTestProtoFile.PackedSint64Extension);
+ registry.Add(UnitTestProtoFile.PackedFixed32Extension);
+ registry.Add(UnitTestProtoFile.PackedFixed64Extension);
+ registry.Add(UnitTestProtoFile.PackedSfixed32Extension);
+ registry.Add(UnitTestProtoFile.PackedSfixed64Extension);
+ registry.Add(UnitTestProtoFile.PackedFloatExtension);
+ registry.Add(UnitTestProtoFile.PackedDoubleExtension);
+ registry.Add(UnitTestProtoFile.PackedBoolExtension);
+ registry.Add(UnitTestProtoFile.PackedEnumExtension);
+ }
+
+ internal static string ReadTextFromFile(string filePath)
+ {
+ return ReadBytesFromFile(filePath).ToStringUtf8();
+ }
+
+ internal static ByteString ReadBytesFromFile(String filename)
+ {
+ byte[] data = File.ReadAllBytes(Path.Combine(TestDataDirectory, filename));
+ return ByteString.CopyFrom(data);
+ }
+
+ /// <summary>
+ /// Helper to convert a String to ByteString.
+ /// </summary>
+ internal static ByteString ToBytes(String str)
+ {
+ return ByteString.CopyFrom(Encoding.UTF8.GetBytes(str));
+ }
+
+ internal static TestAllTypes GetAllSet()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ SetAllFields(builder);
+ return builder.Build();
+ }
+
+ /// <summary>
+ /// Sets every field of the specified message to the values expected by
+ /// AssertAllFieldsSet.
+ /// </summary>
+ internal static void SetAllFields(TestAllTypes.Builder message)
+ {
+ message.SetOptionalInt32(101);
+ message.SetOptionalInt64(102);
+ message.SetOptionalUint32(103);
+ message.SetOptionalUint64(104);
+ message.SetOptionalSint32(105);
+ message.SetOptionalSint64(106);
+ message.SetOptionalFixed32(107);
+ message.SetOptionalFixed64(108);
+ message.SetOptionalSfixed32(109);
+ message.SetOptionalSfixed64(110);
+ message.SetOptionalFloat(111);
+ message.SetOptionalDouble(112);
+ message.SetOptionalBool(true);
+ message.SetOptionalString("115");
+ message.SetOptionalBytes(ToBytes("116"));
+
+ message.SetOptionalGroup(TestAllTypes.Types.OptionalGroup.CreateBuilder().SetA(117).Build());
+ message.SetOptionalNestedMessage(TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(118).Build());
+ message.SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(119).Build());
+ message.SetOptionalImportMessage(ImportMessage.CreateBuilder().SetD(120).Build());
+
+ message.SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.BAZ);
+ message.SetOptionalForeignEnum(ForeignEnum.FOREIGN_BAZ);
+ message.SetOptionalImportEnum(ImportEnum.IMPORT_BAZ);
+
+ message.SetOptionalStringPiece("124");
+ message.SetOptionalCord("125");
+
+ // -----------------------------------------------------------------
+
+ message.AddRepeatedInt32(201);
+ message.AddRepeatedInt64(202);
+ message.AddRepeatedUint32(203);
+ message.AddRepeatedUint64(204);
+ message.AddRepeatedSint32(205);
+ message.AddRepeatedSint64(206);
+ message.AddRepeatedFixed32(207);
+ message.AddRepeatedFixed64(208);
+ message.AddRepeatedSfixed32(209);
+ message.AddRepeatedSfixed64(210);
+ message.AddRepeatedFloat(211);
+ message.AddRepeatedDouble(212);
+ message.AddRepeatedBool(true);
+ message.AddRepeatedString("215");
+ message.AddRepeatedBytes(ToBytes("216"));
+
+ message.AddRepeatedGroup(TestAllTypes.Types.RepeatedGroup.CreateBuilder().SetA(217).Build());
+ message.AddRepeatedNestedMessage(TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(218).Build());
+ message.AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(219).Build());
+ message.AddRepeatedImportMessage(ImportMessage.CreateBuilder().SetD(220).Build());
+
+ message.AddRepeatedNestedEnum(TestAllTypes.Types.NestedEnum.BAR);
+ message.AddRepeatedForeignEnum(ForeignEnum.FOREIGN_BAR);
+ message.AddRepeatedImportEnum(ImportEnum.IMPORT_BAR);
+
+ message.AddRepeatedStringPiece("224");
+ message.AddRepeatedCord("225");
+
+ // Add a second one of each field.
+ message.AddRepeatedInt32(301);
+ message.AddRepeatedInt64(302);
+ message.AddRepeatedUint32(303);
+ message.AddRepeatedUint64(304);
+ message.AddRepeatedSint32(305);
+ message.AddRepeatedSint64(306);
+ message.AddRepeatedFixed32(307);
+ message.AddRepeatedFixed64(308);
+ message.AddRepeatedSfixed32(309);
+ message.AddRepeatedSfixed64(310);
+ message.AddRepeatedFloat(311);
+ message.AddRepeatedDouble(312);
+ message.AddRepeatedBool(false);
+ message.AddRepeatedString("315");
+ message.AddRepeatedBytes(ToBytes("316"));
+
+ message.AddRepeatedGroup(TestAllTypes.Types.RepeatedGroup.CreateBuilder().SetA(317).Build());
+ message.AddRepeatedNestedMessage(TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(318).Build());
+ message.AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(319).Build());
+ message.AddRepeatedImportMessage(ImportMessage.CreateBuilder().SetD(320).Build());
+
+ message.AddRepeatedNestedEnum(TestAllTypes.Types.NestedEnum.BAZ);
+ message.AddRepeatedForeignEnum(ForeignEnum.FOREIGN_BAZ);
+ message.AddRepeatedImportEnum(ImportEnum.IMPORT_BAZ);
+
+ message.AddRepeatedStringPiece("324");
+ message.AddRepeatedCord("325");
+
+ // -----------------------------------------------------------------
+
+ message.SetDefaultInt32(401);
+ message.SetDefaultInt64(402);
+ message.SetDefaultUint32(403);
+ message.SetDefaultUint64(404);
+ message.SetDefaultSint32(405);
+ message.SetDefaultSint64(406);
+ message.SetDefaultFixed32(407);
+ message.SetDefaultFixed64(408);
+ message.SetDefaultSfixed32(409);
+ message.SetDefaultSfixed64(410);
+ message.SetDefaultFloat(411);
+ message.SetDefaultDouble(412);
+ message.SetDefaultBool(false);
+ message.SetDefaultString("415");
+ message.SetDefaultBytes(ToBytes("416"));
+
+ message.SetDefaultNestedEnum(TestAllTypes.Types.NestedEnum.FOO);
+ message.SetDefaultForeignEnum(ForeignEnum.FOREIGN_FOO);
+ message.SetDefaultImportEnum(ImportEnum.IMPORT_FOO);
+
+ message.SetDefaultStringPiece("424");
+ message.SetDefaultCord("425");
+ }
+
+ /// <summary>
+ /// Asserts that all fields of the specified message are set to the values
+ /// assigned by SetAllFields.
+ /// </summary>
+ internal static void AssertAllFieldsSet(TestAllTypes message)
+ {
+ Assert.IsTrue(message.HasOptionalInt32);
+ Assert.IsTrue(message.HasOptionalInt64);
+ Assert.IsTrue(message.HasOptionalUint32);
+ Assert.IsTrue(message.HasOptionalUint64);
+ Assert.IsTrue(message.HasOptionalSint32);
+ Assert.IsTrue(message.HasOptionalSint64);
+ Assert.IsTrue(message.HasOptionalFixed32);
+ Assert.IsTrue(message.HasOptionalFixed64);
+ Assert.IsTrue(message.HasOptionalSfixed32);
+ Assert.IsTrue(message.HasOptionalSfixed64);
+ Assert.IsTrue(message.HasOptionalFloat);
+ Assert.IsTrue(message.HasOptionalDouble);
+ Assert.IsTrue(message.HasOptionalBool);
+ Assert.IsTrue(message.HasOptionalString);
+ Assert.IsTrue(message.HasOptionalBytes);
+
+ Assert.IsTrue(message.HasOptionalGroup);
+ Assert.IsTrue(message.HasOptionalNestedMessage);
+ Assert.IsTrue(message.HasOptionalForeignMessage);
+ Assert.IsTrue(message.HasOptionalImportMessage);
+
+ Assert.IsTrue(message.OptionalGroup.HasA);
+ Assert.IsTrue(message.OptionalNestedMessage.HasBb);
+ Assert.IsTrue(message.OptionalForeignMessage.HasC);
+ Assert.IsTrue(message.OptionalImportMessage.HasD);
+
+ Assert.IsTrue(message.HasOptionalNestedEnum);
+ Assert.IsTrue(message.HasOptionalForeignEnum);
+ Assert.IsTrue(message.HasOptionalImportEnum);
+
+ Assert.IsTrue(message.HasOptionalStringPiece);
+ Assert.IsTrue(message.HasOptionalCord);
+
+ Assert.AreEqual(101, message.OptionalInt32);
+ Assert.AreEqual(102, message.OptionalInt64);
+ Assert.AreEqual(103, message.OptionalUint32);
+ Assert.AreEqual(104, message.OptionalUint64);
+ Assert.AreEqual(105, message.OptionalSint32);
+ Assert.AreEqual(106, message.OptionalSint64);
+ Assert.AreEqual(107, message.OptionalFixed32);
+ Assert.AreEqual(108, message.OptionalFixed64);
+ Assert.AreEqual(109, message.OptionalSfixed32);
+ Assert.AreEqual(110, message.OptionalSfixed64);
+ Assert.AreEqual(111, message.OptionalFloat);
+ Assert.AreEqual(112, message.OptionalDouble);
+ Assert.AreEqual(true, message.OptionalBool);
+ Assert.AreEqual("115", message.OptionalString);
+ Assert.AreEqual(ToBytes("116"), message.OptionalBytes);
+
+ Assert.AreEqual(117, message.OptionalGroup.A);
+ Assert.AreEqual(118, message.OptionalNestedMessage.Bb);
+ Assert.AreEqual(119, message.OptionalForeignMessage.C);
+ Assert.AreEqual(120, message.OptionalImportMessage.D);
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAZ, message.OptionalNestedEnum);
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, message.OptionalForeignEnum);
+ Assert.AreEqual(ImportEnum.IMPORT_BAZ, message.OptionalImportEnum);
+
+ Assert.AreEqual("124", message.OptionalStringPiece);
+ Assert.AreEqual("125", message.OptionalCord);
+
+ // -----------------------------------------------------------------
+
+ Assert.AreEqual(2, message.RepeatedInt32Count);
+ Assert.AreEqual(2, message.RepeatedInt64Count);
+ Assert.AreEqual(2, message.RepeatedUint32Count);
+ Assert.AreEqual(2, message.RepeatedUint64Count);
+ Assert.AreEqual(2, message.RepeatedSint32Count);
+ Assert.AreEqual(2, message.RepeatedSint64Count);
+ Assert.AreEqual(2, message.RepeatedFixed32Count);
+ Assert.AreEqual(2, message.RepeatedFixed64Count);
+ Assert.AreEqual(2, message.RepeatedSfixed32Count);
+ Assert.AreEqual(2, message.RepeatedSfixed64Count);
+ Assert.AreEqual(2, message.RepeatedFloatCount);
+ Assert.AreEqual(2, message.RepeatedDoubleCount);
+ Assert.AreEqual(2, message.RepeatedBoolCount);
+ Assert.AreEqual(2, message.RepeatedStringCount);
+ Assert.AreEqual(2, message.RepeatedBytesCount);
+
+ Assert.AreEqual(2, message.RepeatedGroupCount);
+ Assert.AreEqual(2, message.RepeatedNestedMessageCount);
+ Assert.AreEqual(2, message.RepeatedForeignMessageCount);
+ Assert.AreEqual(2, message.RepeatedImportMessageCount);
+ Assert.AreEqual(2, message.RepeatedNestedEnumCount);
+ Assert.AreEqual(2, message.RepeatedForeignEnumCount);
+ Assert.AreEqual(2, message.RepeatedImportEnumCount);
+
+ Assert.AreEqual(2, message.RepeatedStringPieceCount);
+ Assert.AreEqual(2, message.RepeatedCordCount);
+
+ Assert.AreEqual(201, message.GetRepeatedInt32(0));
+ Assert.AreEqual(202, message.GetRepeatedInt64(0));
+ Assert.AreEqual(203, message.GetRepeatedUint32(0));
+ Assert.AreEqual(204, message.GetRepeatedUint64(0));
+ Assert.AreEqual(205, message.GetRepeatedSint32(0));
+ Assert.AreEqual(206, message.GetRepeatedSint64(0));
+ Assert.AreEqual(207, message.GetRepeatedFixed32(0));
+ Assert.AreEqual(208, message.GetRepeatedFixed64(0));
+ Assert.AreEqual(209, message.GetRepeatedSfixed32(0));
+ Assert.AreEqual(210, message.GetRepeatedSfixed64(0));
+ Assert.AreEqual(211, message.GetRepeatedFloat(0));
+ Assert.AreEqual(212, message.GetRepeatedDouble(0));
+ Assert.AreEqual(true, message.GetRepeatedBool(0));
+ Assert.AreEqual("215", message.GetRepeatedString(0));
+ Assert.AreEqual(ToBytes("216"), message.GetRepeatedBytes(0));
+
+ Assert.AreEqual(217, message.GetRepeatedGroup(0).A);
+ Assert.AreEqual(218, message.GetRepeatedNestedMessage(0).Bb);
+ Assert.AreEqual(219, message.GetRepeatedForeignMessage(0).C);
+ Assert.AreEqual(220, message.GetRepeatedImportMessage(0).D);
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, message.GetRepeatedNestedEnum(0));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAR, message.GetRepeatedForeignEnum(0));
+ Assert.AreEqual(ImportEnum.IMPORT_BAR, message.GetRepeatedImportEnum(0));
+
+ Assert.AreEqual("224", message.GetRepeatedStringPiece(0));
+ Assert.AreEqual("225", message.GetRepeatedCord(0));
+
+ Assert.AreEqual(301, message.GetRepeatedInt32(1));
+ Assert.AreEqual(302, message.GetRepeatedInt64(1));
+ Assert.AreEqual(303, message.GetRepeatedUint32(1));
+ Assert.AreEqual(304, message.GetRepeatedUint64(1));
+ Assert.AreEqual(305, message.GetRepeatedSint32(1));
+ Assert.AreEqual(306, message.GetRepeatedSint64(1));
+ Assert.AreEqual(307, message.GetRepeatedFixed32(1));
+ Assert.AreEqual(308, message.GetRepeatedFixed64(1));
+ Assert.AreEqual(309, message.GetRepeatedSfixed32(1));
+ Assert.AreEqual(310, message.GetRepeatedSfixed64(1));
+ Assert.AreEqual(311, message.GetRepeatedFloat(1), 0.0);
+ Assert.AreEqual(312, message.GetRepeatedDouble(1), 0.0);
+ Assert.AreEqual(false, message.GetRepeatedBool(1));
+ Assert.AreEqual("315", message.GetRepeatedString(1));
+ Assert.AreEqual(ToBytes("316"), message.GetRepeatedBytes(1));
+
+ Assert.AreEqual(317, message.GetRepeatedGroup(1).A);
+ Assert.AreEqual(318, message.GetRepeatedNestedMessage(1).Bb);
+ Assert.AreEqual(319, message.GetRepeatedForeignMessage(1).C);
+ Assert.AreEqual(320, message.GetRepeatedImportMessage(1).D);
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAZ, message.GetRepeatedNestedEnum(1));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, message.GetRepeatedForeignEnum(1));
+ Assert.AreEqual(ImportEnum.IMPORT_BAZ, message.GetRepeatedImportEnum(1));
+
+ Assert.AreEqual("324", message.GetRepeatedStringPiece(1));
+ Assert.AreEqual("325", message.GetRepeatedCord(1));
+
+ // -----------------------------------------------------------------
+
+ Assert.IsTrue(message.HasDefaultInt32);
+ Assert.IsTrue(message.HasDefaultInt64);
+ Assert.IsTrue(message.HasDefaultUint32);
+ Assert.IsTrue(message.HasDefaultUint64);
+ Assert.IsTrue(message.HasDefaultSint32);
+ Assert.IsTrue(message.HasDefaultSint64);
+ Assert.IsTrue(message.HasDefaultFixed32);
+ Assert.IsTrue(message.HasDefaultFixed64);
+ Assert.IsTrue(message.HasDefaultSfixed32);
+ Assert.IsTrue(message.HasDefaultSfixed64);
+ Assert.IsTrue(message.HasDefaultFloat);
+ Assert.IsTrue(message.HasDefaultDouble);
+ Assert.IsTrue(message.HasDefaultBool);
+ Assert.IsTrue(message.HasDefaultString);
+ Assert.IsTrue(message.HasDefaultBytes);
+
+ Assert.IsTrue(message.HasDefaultNestedEnum);
+ Assert.IsTrue(message.HasDefaultForeignEnum);
+ Assert.IsTrue(message.HasDefaultImportEnum);
+
+ Assert.IsTrue(message.HasDefaultStringPiece);
+ Assert.IsTrue(message.HasDefaultCord);
+
+ Assert.AreEqual(401, message.DefaultInt32);
+ Assert.AreEqual(402, message.DefaultInt64);
+ Assert.AreEqual(403, message.DefaultUint32);
+ Assert.AreEqual(404, message.DefaultUint64);
+ Assert.AreEqual(405, message.DefaultSint32);
+ Assert.AreEqual(406, message.DefaultSint64);
+ Assert.AreEqual(407, message.DefaultFixed32);
+ Assert.AreEqual(408, message.DefaultFixed64);
+ Assert.AreEqual(409, message.DefaultSfixed32);
+ Assert.AreEqual(410, message.DefaultSfixed64);
+ Assert.AreEqual(411, message.DefaultFloat);
+ Assert.AreEqual(412, message.DefaultDouble);
+ Assert.AreEqual(false, message.DefaultBool);
+ Assert.AreEqual("415", message.DefaultString);
+ Assert.AreEqual(ToBytes("416"), message.DefaultBytes);
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, message.DefaultNestedEnum);
+ Assert.AreEqual(ForeignEnum.FOREIGN_FOO, message.DefaultForeignEnum);
+ Assert.AreEqual(ImportEnum.IMPORT_FOO, message.DefaultImportEnum);
+
+ Assert.AreEqual("424", message.DefaultStringPiece);
+ Assert.AreEqual("425", message.DefaultCord);
+ }
+
+ internal static void AssertClear(TestAllTypes message)
+ {
+ // HasBlah() should initially be false for all optional fields.
+ Assert.IsFalse(message.HasOptionalInt32);
+ Assert.IsFalse(message.HasOptionalInt64);
+ Assert.IsFalse(message.HasOptionalUint32);
+ Assert.IsFalse(message.HasOptionalUint64);
+ Assert.IsFalse(message.HasOptionalSint32);
+ Assert.IsFalse(message.HasOptionalSint64);
+ Assert.IsFalse(message.HasOptionalFixed32);
+ Assert.IsFalse(message.HasOptionalFixed64);
+ Assert.IsFalse(message.HasOptionalSfixed32);
+ Assert.IsFalse(message.HasOptionalSfixed64);
+ Assert.IsFalse(message.HasOptionalFloat);
+ Assert.IsFalse(message.HasOptionalDouble);
+ Assert.IsFalse(message.HasOptionalBool);
+ Assert.IsFalse(message.HasOptionalString);
+ Assert.IsFalse(message.HasOptionalBytes);
+
+ Assert.IsFalse(message.HasOptionalGroup);
+ Assert.IsFalse(message.HasOptionalNestedMessage);
+ Assert.IsFalse(message.HasOptionalForeignMessage);
+ Assert.IsFalse(message.HasOptionalImportMessage);
+
+ Assert.IsFalse(message.HasOptionalNestedEnum);
+ Assert.IsFalse(message.HasOptionalForeignEnum);
+ Assert.IsFalse(message.HasOptionalImportEnum);
+
+ Assert.IsFalse(message.HasOptionalStringPiece);
+ Assert.IsFalse(message.HasOptionalCord);
+
+ // Optional fields without defaults are set to zero or something like it.
+ Assert.AreEqual(0, message.OptionalInt32);
+ Assert.AreEqual(0, message.OptionalInt64);
+ Assert.AreEqual(0, message.OptionalUint32);
+ Assert.AreEqual(0, message.OptionalUint64);
+ Assert.AreEqual(0, message.OptionalSint32);
+ Assert.AreEqual(0, message.OptionalSint64);
+ Assert.AreEqual(0, message.OptionalFixed32);
+ Assert.AreEqual(0, message.OptionalFixed64);
+ Assert.AreEqual(0, message.OptionalSfixed32);
+ Assert.AreEqual(0, message.OptionalSfixed64);
+ Assert.AreEqual(0, message.OptionalFloat);
+ Assert.AreEqual(0, message.OptionalDouble);
+ Assert.AreEqual(false, message.OptionalBool);
+ Assert.AreEqual("", message.OptionalString);
+ Assert.AreEqual(ByteString.Empty, message.OptionalBytes);
+
+ // Embedded messages should also be clear.
+ Assert.IsFalse(message.OptionalGroup.HasA);
+ Assert.IsFalse(message.OptionalNestedMessage.HasBb);
+ Assert.IsFalse(message.OptionalForeignMessage.HasC);
+ Assert.IsFalse(message.OptionalImportMessage.HasD);
+
+ Assert.AreEqual(0, message.OptionalGroup.A);
+ Assert.AreEqual(0, message.OptionalNestedMessage.Bb);
+ Assert.AreEqual(0, message.OptionalForeignMessage.C);
+ Assert.AreEqual(0, message.OptionalImportMessage.D);
+
+ // Enums without defaults are set to the first value in the enum.
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, message.OptionalNestedEnum);
+ Assert.AreEqual(ForeignEnum.FOREIGN_FOO, message.OptionalForeignEnum);
+ Assert.AreEqual(ImportEnum.IMPORT_FOO, message.OptionalImportEnum);
+
+ Assert.AreEqual("", message.OptionalStringPiece);
+ Assert.AreEqual("", message.OptionalCord);
+
+ // Repeated fields are empty.
+ Assert.AreEqual(0, message.RepeatedInt32Count);
+ Assert.AreEqual(0, message.RepeatedInt64Count);
+ Assert.AreEqual(0, message.RepeatedUint32Count);
+ Assert.AreEqual(0, message.RepeatedUint64Count);
+ Assert.AreEqual(0, message.RepeatedSint32Count);
+ Assert.AreEqual(0, message.RepeatedSint64Count);
+ Assert.AreEqual(0, message.RepeatedFixed32Count);
+ Assert.AreEqual(0, message.RepeatedFixed64Count);
+ Assert.AreEqual(0, message.RepeatedSfixed32Count);
+ Assert.AreEqual(0, message.RepeatedSfixed64Count);
+ Assert.AreEqual(0, message.RepeatedFloatCount);
+ Assert.AreEqual(0, message.RepeatedDoubleCount);
+ Assert.AreEqual(0, message.RepeatedBoolCount);
+ Assert.AreEqual(0, message.RepeatedStringCount);
+ Assert.AreEqual(0, message.RepeatedBytesCount);
+
+ Assert.AreEqual(0, message.RepeatedGroupCount);
+ Assert.AreEqual(0, message.RepeatedNestedMessageCount);
+ Assert.AreEqual(0, message.RepeatedForeignMessageCount);
+ Assert.AreEqual(0, message.RepeatedImportMessageCount);
+ Assert.AreEqual(0, message.RepeatedNestedEnumCount);
+ Assert.AreEqual(0, message.RepeatedForeignEnumCount);
+ Assert.AreEqual(0, message.RepeatedImportEnumCount);
+
+ Assert.AreEqual(0, message.RepeatedStringPieceCount);
+ Assert.AreEqual(0, message.RepeatedCordCount);
+
+ // HasBlah() should also be false for all default fields.
+ Assert.IsFalse(message.HasDefaultInt32);
+ Assert.IsFalse(message.HasDefaultInt64);
+ Assert.IsFalse(message.HasDefaultUint32);
+ Assert.IsFalse(message.HasDefaultUint64);
+ Assert.IsFalse(message.HasDefaultSint32);
+ Assert.IsFalse(message.HasDefaultSint64);
+ Assert.IsFalse(message.HasDefaultFixed32);
+ Assert.IsFalse(message.HasDefaultFixed64);
+ Assert.IsFalse(message.HasDefaultSfixed32);
+ Assert.IsFalse(message.HasDefaultSfixed64);
+ Assert.IsFalse(message.HasDefaultFloat);
+ Assert.IsFalse(message.HasDefaultDouble);
+ Assert.IsFalse(message.HasDefaultBool);
+ Assert.IsFalse(message.HasDefaultString);
+ Assert.IsFalse(message.HasDefaultBytes);
+
+ Assert.IsFalse(message.HasDefaultNestedEnum);
+ Assert.IsFalse(message.HasDefaultForeignEnum);
+ Assert.IsFalse(message.HasDefaultImportEnum);
+
+ Assert.IsFalse(message.HasDefaultStringPiece);
+ Assert.IsFalse(message.HasDefaultCord);
+
+ // Fields with defaults have their default values (duh).
+ Assert.AreEqual(41, message.DefaultInt32);
+ Assert.AreEqual(42, message.DefaultInt64);
+ Assert.AreEqual(43, message.DefaultUint32);
+ Assert.AreEqual(44, message.DefaultUint64);
+ Assert.AreEqual(-45, message.DefaultSint32);
+ Assert.AreEqual(46, message.DefaultSint64);
+ Assert.AreEqual(47, message.DefaultFixed32);
+ Assert.AreEqual(48, message.DefaultFixed64);
+ Assert.AreEqual(49, message.DefaultSfixed32);
+ Assert.AreEqual(-50, message.DefaultSfixed64);
+ Assert.AreEqual(51.5, message.DefaultFloat, 0.0);
+ Assert.AreEqual(52e3, message.DefaultDouble, 0.0);
+ Assert.AreEqual(true, message.DefaultBool);
+ Assert.AreEqual("hello", message.DefaultString);
+ Assert.AreEqual(ToBytes("world"), message.DefaultBytes);
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, message.DefaultNestedEnum);
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAR, message.DefaultForeignEnum);
+ Assert.AreEqual(ImportEnum.IMPORT_BAR, message.DefaultImportEnum);
+
+ Assert.AreEqual("abc", message.DefaultStringPiece);
+ Assert.AreEqual("123", message.DefaultCord);
+ }
+
+ /// <summary>
+ /// Get a TestAllExtensions with all fields set as they would be by
+ /// SetAllExtensions(TestAllExtensions.Builder).
+ /// </summary>
+ internal static TestAllExtensions GetAllExtensionsSet()
+ {
+ TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
+ SetAllExtensions(builder);
+ return builder.Build();
+ }
+
+ public static TestPackedTypes GetPackedSet()
+ {
+ TestPackedTypes.Builder builder = TestPackedTypes.CreateBuilder();
+ SetPackedFields(builder);
+ return builder.Build();
+ }
+
+ public static TestPackedExtensions GetPackedExtensionsSet()
+ {
+ TestPackedExtensions.Builder builder = TestPackedExtensions.CreateBuilder();
+ SetPackedExtensions(builder);
+ return builder.Build();
+ }
+
+ /// <summary>
+ /// Sets every field of the specified builder to the values expected by
+ /// AssertAllExtensionsSet.
+ /// </summary>
+ internal static void SetAllExtensions(TestAllExtensions.Builder message)
+ {
+ message.SetExtension(UnitTestProtoFile.OptionalInt32Extension, 101);
+ message.SetExtension(UnitTestProtoFile.OptionalInt64Extension, 102L);
+ message.SetExtension(UnitTestProtoFile.OptionalUint32Extension, 103U);
+ message.SetExtension(UnitTestProtoFile.OptionalUint64Extension, 104UL);
+ message.SetExtension(UnitTestProtoFile.OptionalSint32Extension, 105);
+ message.SetExtension(UnitTestProtoFile.OptionalSint64Extension, 106L);
+ message.SetExtension(UnitTestProtoFile.OptionalFixed32Extension, 107U);
+ message.SetExtension(UnitTestProtoFile.OptionalFixed64Extension, 108UL);
+ message.SetExtension(UnitTestProtoFile.OptionalSfixed32Extension, 109);
+ message.SetExtension(UnitTestProtoFile.OptionalSfixed64Extension, 110L);
+ message.SetExtension(UnitTestProtoFile.OptionalFloatExtension, 111F);
+ message.SetExtension(UnitTestProtoFile.OptionalDoubleExtension, 112D);
+ message.SetExtension(UnitTestProtoFile.OptionalBoolExtension, true);
+ message.SetExtension(UnitTestProtoFile.OptionalStringExtension, "115");
+ message.SetExtension(UnitTestProtoFile.OptionalBytesExtension, ToBytes("116"));
+
+ message.SetExtension(UnitTestProtoFile.OptionalGroupExtension,
+ OptionalGroup_extension.CreateBuilder().SetA(117).Build());
+ message.SetExtension(UnitTestProtoFile.OptionalNestedMessageExtension,
+ TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(118).Build());
+ message.SetExtension(UnitTestProtoFile.OptionalForeignMessageExtension,
+ ForeignMessage.CreateBuilder().SetC(119).Build());
+ message.SetExtension(UnitTestProtoFile.OptionalImportMessageExtension,
+ ImportMessage.CreateBuilder().SetD(120).Build());
+
+ message.SetExtension(UnitTestProtoFile.OptionalNestedEnumExtension, TestAllTypes.Types.NestedEnum.BAZ);
+ message.SetExtension(UnitTestProtoFile.OptionalForeignEnumExtension, ForeignEnum.FOREIGN_BAZ);
+ message.SetExtension(UnitTestProtoFile.OptionalImportEnumExtension, ImportEnum.IMPORT_BAZ);
+
+ message.SetExtension(UnitTestProtoFile.OptionalStringPieceExtension, "124");
+ message.SetExtension(UnitTestProtoFile.OptionalCordExtension, "125");
+
+ // -----------------------------------------------------------------
+
+ message.AddExtension(UnitTestProtoFile.RepeatedInt32Extension, 201);
+ message.AddExtension(UnitTestProtoFile.RepeatedInt64Extension, 202L);
+ message.AddExtension(UnitTestProtoFile.RepeatedUint32Extension, 203U);
+ message.AddExtension(UnitTestProtoFile.RepeatedUint64Extension, 204UL);
+ message.AddExtension(UnitTestProtoFile.RepeatedSint32Extension, 205);
+ message.AddExtension(UnitTestProtoFile.RepeatedSint64Extension, 206L);
+ message.AddExtension(UnitTestProtoFile.RepeatedFixed32Extension, 207U);
+ message.AddExtension(UnitTestProtoFile.RepeatedFixed64Extension, 208UL);
+ message.AddExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 209);
+ message.AddExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 210L);
+ message.AddExtension(UnitTestProtoFile.RepeatedFloatExtension, 211F);
+ message.AddExtension(UnitTestProtoFile.RepeatedDoubleExtension, 212D);
+ message.AddExtension(UnitTestProtoFile.RepeatedBoolExtension, true);
+ message.AddExtension(UnitTestProtoFile.RepeatedStringExtension, "215");
+ message.AddExtension(UnitTestProtoFile.RepeatedBytesExtension, ToBytes("216"));
+
+ message.AddExtension(UnitTestProtoFile.RepeatedGroupExtension,
+ RepeatedGroup_extension.CreateBuilder().SetA(217).Build());
+ message.AddExtension(UnitTestProtoFile.RepeatedNestedMessageExtension,
+ TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(218).Build());
+ message.AddExtension(UnitTestProtoFile.RepeatedForeignMessageExtension,
+ ForeignMessage.CreateBuilder().SetC(219).Build());
+ message.AddExtension(UnitTestProtoFile.RepeatedImportMessageExtension,
+ ImportMessage.CreateBuilder().SetD(220).Build());
+
+ message.AddExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, TestAllTypes.Types.NestedEnum.BAR);
+ message.AddExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAR);
+ message.AddExtension(UnitTestProtoFile.RepeatedImportEnumExtension, ImportEnum.IMPORT_BAR);
+
+ message.AddExtension(UnitTestProtoFile.RepeatedStringPieceExtension, "224");
+ message.AddExtension(UnitTestProtoFile.RepeatedCordExtension, "225");
+
+ // Add a second one of each field.
+ message.AddExtension(UnitTestProtoFile.RepeatedInt32Extension, 301);
+ message.AddExtension(UnitTestProtoFile.RepeatedInt64Extension, 302L);
+ message.AddExtension(UnitTestProtoFile.RepeatedUint32Extension, 303U);
+ message.AddExtension(UnitTestProtoFile.RepeatedUint64Extension, 304UL);
+ message.AddExtension(UnitTestProtoFile.RepeatedSint32Extension, 305);
+ message.AddExtension(UnitTestProtoFile.RepeatedSint64Extension, 306L);
+ message.AddExtension(UnitTestProtoFile.RepeatedFixed32Extension, 307U);
+ message.AddExtension(UnitTestProtoFile.RepeatedFixed64Extension, 308UL);
+ message.AddExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 309);
+ message.AddExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 310L);
+ message.AddExtension(UnitTestProtoFile.RepeatedFloatExtension, 311F);
+ message.AddExtension(UnitTestProtoFile.RepeatedDoubleExtension, 312D);
+ message.AddExtension(UnitTestProtoFile.RepeatedBoolExtension, false);
+ message.AddExtension(UnitTestProtoFile.RepeatedStringExtension, "315");
+ message.AddExtension(UnitTestProtoFile.RepeatedBytesExtension, ToBytes("316"));
+
+ message.AddExtension(UnitTestProtoFile.RepeatedGroupExtension,
+ RepeatedGroup_extension.CreateBuilder().SetA(317).Build());
+ message.AddExtension(UnitTestProtoFile.RepeatedNestedMessageExtension,
+ TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(318).Build());
+ message.AddExtension(UnitTestProtoFile.RepeatedForeignMessageExtension,
+ ForeignMessage.CreateBuilder().SetC(319).Build());
+ message.AddExtension(UnitTestProtoFile.RepeatedImportMessageExtension,
+ ImportMessage.CreateBuilder().SetD(320).Build());
+
+ message.AddExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, TestAllTypes.Types.NestedEnum.BAZ);
+ message.AddExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAZ);
+ message.AddExtension(UnitTestProtoFile.RepeatedImportEnumExtension, ImportEnum.IMPORT_BAZ);
+
+ message.AddExtension(UnitTestProtoFile.RepeatedStringPieceExtension, "324");
+ message.AddExtension(UnitTestProtoFile.RepeatedCordExtension, "325");
+
+ // -----------------------------------------------------------------
+
+ message.SetExtension(UnitTestProtoFile.DefaultInt32Extension, 401);
+ message.SetExtension(UnitTestProtoFile.DefaultInt64Extension, 402L);
+ message.SetExtension(UnitTestProtoFile.DefaultUint32Extension, 403U);
+ message.SetExtension(UnitTestProtoFile.DefaultUint64Extension, 404UL);
+ message.SetExtension(UnitTestProtoFile.DefaultSint32Extension, 405);
+ message.SetExtension(UnitTestProtoFile.DefaultSint64Extension, 406L);
+ message.SetExtension(UnitTestProtoFile.DefaultFixed32Extension, 407U);
+ message.SetExtension(UnitTestProtoFile.DefaultFixed64Extension, 408UL);
+ message.SetExtension(UnitTestProtoFile.DefaultSfixed32Extension, 409);
+ message.SetExtension(UnitTestProtoFile.DefaultSfixed64Extension, 410L);
+ message.SetExtension(UnitTestProtoFile.DefaultFloatExtension, 411F);
+ message.SetExtension(UnitTestProtoFile.DefaultDoubleExtension, 412D);
+ message.SetExtension(UnitTestProtoFile.DefaultBoolExtension, false);
+ message.SetExtension(UnitTestProtoFile.DefaultStringExtension, "415");
+ message.SetExtension(UnitTestProtoFile.DefaultBytesExtension, ToBytes("416"));
+
+ message.SetExtension(UnitTestProtoFile.DefaultNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO);
+ message.SetExtension(UnitTestProtoFile.DefaultForeignEnumExtension, ForeignEnum.FOREIGN_FOO);
+ message.SetExtension(UnitTestProtoFile.DefaultImportEnumExtension, ImportEnum.IMPORT_FOO);
+
+ message.SetExtension(UnitTestProtoFile.DefaultStringPieceExtension, "424");
+ message.SetExtension(UnitTestProtoFile.DefaultCordExtension, "425");
+ }
+
+ internal static void ModifyRepeatedFields(TestAllTypes.Builder message)
+ {
+ message.SetRepeatedInt32(1, 501);
+ message.SetRepeatedInt64(1, 502);
+ message.SetRepeatedUint32(1, 503);
+ message.SetRepeatedUint64(1, 504);
+ message.SetRepeatedSint32(1, 505);
+ message.SetRepeatedSint64(1, 506);
+ message.SetRepeatedFixed32(1, 507);
+ message.SetRepeatedFixed64(1, 508);
+ message.SetRepeatedSfixed32(1, 509);
+ message.SetRepeatedSfixed64(1, 510);
+ message.SetRepeatedFloat(1, 511);
+ message.SetRepeatedDouble(1, 512);
+ message.SetRepeatedBool(1, true);
+ message.SetRepeatedString(1, "515");
+ message.SetRepeatedBytes(1, ToBytes("516"));
+
+ message.SetRepeatedGroup(1, TestAllTypes.Types.RepeatedGroup.CreateBuilder().SetA(517).Build());
+ message.SetRepeatedNestedMessage(1, TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(518).Build());
+ message.SetRepeatedForeignMessage(1, ForeignMessage.CreateBuilder().SetC(519).Build());
+ message.SetRepeatedImportMessage(1, ImportMessage.CreateBuilder().SetD(520).Build());
+
+ message.SetRepeatedNestedEnum(1, TestAllTypes.Types.NestedEnum.FOO);
+ message.SetRepeatedForeignEnum(1, ForeignEnum.FOREIGN_FOO);
+ message.SetRepeatedImportEnum(1, ImportEnum.IMPORT_FOO);
+
+ message.SetRepeatedStringPiece(1, "524");
+ message.SetRepeatedCord(1, "525");
+ }
+
+ internal static void AssertRepeatedFieldsModified(TestAllTypes message)
+ {
+ // ModifyRepeatedFields only sets the second repeated element of each
+ // field. In addition to verifying this, we also verify that the first
+ // element and size were *not* modified.
+ Assert.AreEqual(2, message.RepeatedInt32Count);
+ Assert.AreEqual(2, message.RepeatedInt64Count);
+ Assert.AreEqual(2, message.RepeatedUint32Count);
+ Assert.AreEqual(2, message.RepeatedUint64Count);
+ Assert.AreEqual(2, message.RepeatedSint32Count);
+ Assert.AreEqual(2, message.RepeatedSint64Count);
+ Assert.AreEqual(2, message.RepeatedFixed32Count);
+ Assert.AreEqual(2, message.RepeatedFixed64Count);
+ Assert.AreEqual(2, message.RepeatedSfixed32Count);
+ Assert.AreEqual(2, message.RepeatedSfixed64Count);
+ Assert.AreEqual(2, message.RepeatedFloatCount);
+ Assert.AreEqual(2, message.RepeatedDoubleCount);
+ Assert.AreEqual(2, message.RepeatedBoolCount);
+ Assert.AreEqual(2, message.RepeatedStringCount);
+ Assert.AreEqual(2, message.RepeatedBytesCount);
+
+ Assert.AreEqual(2, message.RepeatedGroupCount);
+ Assert.AreEqual(2, message.RepeatedNestedMessageCount);
+ Assert.AreEqual(2, message.RepeatedForeignMessageCount);
+ Assert.AreEqual(2, message.RepeatedImportMessageCount);
+ Assert.AreEqual(2, message.RepeatedNestedEnumCount);
+ Assert.AreEqual(2, message.RepeatedForeignEnumCount);
+ Assert.AreEqual(2, message.RepeatedImportEnumCount);
+
+ Assert.AreEqual(2, message.RepeatedStringPieceCount);
+ Assert.AreEqual(2, message.RepeatedCordCount);
+
+ Assert.AreEqual(201, message.GetRepeatedInt32(0));
+ Assert.AreEqual(202L, message.GetRepeatedInt64(0));
+ Assert.AreEqual(203U, message.GetRepeatedUint32(0));
+ Assert.AreEqual(204UL, message.GetRepeatedUint64(0));
+ Assert.AreEqual(205, message.GetRepeatedSint32(0));
+ Assert.AreEqual(206L, message.GetRepeatedSint64(0));
+ Assert.AreEqual(207U, message.GetRepeatedFixed32(0));
+ Assert.AreEqual(208UL, message.GetRepeatedFixed64(0));
+ Assert.AreEqual(209, message.GetRepeatedSfixed32(0));
+ Assert.AreEqual(210L, message.GetRepeatedSfixed64(0));
+ Assert.AreEqual(211F, message.GetRepeatedFloat(0));
+ Assert.AreEqual(212D, message.GetRepeatedDouble(0));
+ Assert.AreEqual(true, message.GetRepeatedBool(0));
+ Assert.AreEqual("215", message.GetRepeatedString(0));
+ Assert.AreEqual(ToBytes("216"), message.GetRepeatedBytes(0));
+
+ Assert.AreEqual(217, message.GetRepeatedGroup(0).A);
+ Assert.AreEqual(218, message.GetRepeatedNestedMessage(0).Bb);
+ Assert.AreEqual(219, message.GetRepeatedForeignMessage(0).C);
+ Assert.AreEqual(220, message.GetRepeatedImportMessage(0).D);
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, message.GetRepeatedNestedEnum(0));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAR, message.GetRepeatedForeignEnum(0));
+ Assert.AreEqual(ImportEnum.IMPORT_BAR, message.GetRepeatedImportEnum(0));
+
+ Assert.AreEqual("224", message.GetRepeatedStringPiece(0));
+ Assert.AreEqual("225", message.GetRepeatedCord(0));
+
+ // Actually verify the second (modified) elements now.
+ Assert.AreEqual(501, message.GetRepeatedInt32(1));
+ Assert.AreEqual(502L, message.GetRepeatedInt64(1));
+ Assert.AreEqual(503U, message.GetRepeatedUint32(1));
+ Assert.AreEqual(504UL, message.GetRepeatedUint64(1));
+ Assert.AreEqual(505, message.GetRepeatedSint32(1));
+ Assert.AreEqual(506L, message.GetRepeatedSint64(1));
+ Assert.AreEqual(507U, message.GetRepeatedFixed32(1));
+ Assert.AreEqual(508UL, message.GetRepeatedFixed64(1));
+ Assert.AreEqual(509, message.GetRepeatedSfixed32(1));
+ Assert.AreEqual(510L, message.GetRepeatedSfixed64(1));
+ Assert.AreEqual(511F, message.GetRepeatedFloat(1));
+ Assert.AreEqual(512D, message.GetRepeatedDouble(1));
+ Assert.AreEqual(true, message.GetRepeatedBool(1));
+ Assert.AreEqual("515", message.GetRepeatedString(1));
+ Assert.AreEqual(ToBytes("516"), message.GetRepeatedBytes(1));
+
+ Assert.AreEqual(517, message.GetRepeatedGroup(1).A);
+ Assert.AreEqual(518, message.GetRepeatedNestedMessage(1).Bb);
+ Assert.AreEqual(519, message.GetRepeatedForeignMessage(1).C);
+ Assert.AreEqual(520, message.GetRepeatedImportMessage(1).D);
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, message.GetRepeatedNestedEnum(1));
+ Assert.AreEqual(ForeignEnum.FOREIGN_FOO, message.GetRepeatedForeignEnum(1));
+ Assert.AreEqual(ImportEnum.IMPORT_FOO, message.GetRepeatedImportEnum(1));
+
+ Assert.AreEqual("524", message.GetRepeatedStringPiece(1));
+ Assert.AreEqual("525", message.GetRepeatedCord(1));
+ }
+
+ /// <summary>
+ /// Helper to assert that sequences are equal.
+ /// </summary>
+ internal static void AssertEqual<T>(IEnumerable<T> first, IEnumerable<T> second)
+ {
+ using (IEnumerator<T> firstEnumerator = first.GetEnumerator())
+ {
+ foreach (T secondElement in second)
+ {
+ Assert.IsTrue(firstEnumerator.MoveNext(), "First enumerator ran out of elements too early.");
+ Assert.AreEqual(firstEnumerator.Current, secondElement);
+ }
+ Assert.IsFalse(firstEnumerator.MoveNext(), "Second enumerator ran out of elements too early.");
+ }
+ }
+
+ internal static void AssertEqualBytes(byte[] expected, byte[] actual)
+ {
+ Assert.AreEqual(ByteString.CopyFrom(expected), ByteString.CopyFrom(actual));
+ }
+
+ internal static void AssertAllExtensionsSet(TestAllExtensions message)
+ {
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalInt32Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalInt64Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalUint32Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalUint64Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalSint32Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalSint64Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalFixed32Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalFixed64Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalSfixed32Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalSfixed64Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalFloatExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalDoubleExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalBoolExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalStringExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalBytesExtension));
+
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalGroupExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalNestedMessageExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalForeignMessageExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalImportMessageExtension));
+
+ Assert.IsTrue(message.GetExtension(UnitTestProtoFile.OptionalGroupExtension).HasA);
+ Assert.IsTrue(message.GetExtension(UnitTestProtoFile.OptionalNestedMessageExtension).HasBb);
+ Assert.IsTrue(message.GetExtension(UnitTestProtoFile.OptionalForeignMessageExtension).HasC);
+ Assert.IsTrue(message.GetExtension(UnitTestProtoFile.OptionalImportMessageExtension).HasD);
+
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalNestedEnumExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalForeignEnumExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalImportEnumExtension));
+
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalStringPieceExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.OptionalCordExtension));
+
+ Assert.AreEqual(101, message.GetExtension(UnitTestProtoFile.OptionalInt32Extension));
+ Assert.AreEqual(102L, message.GetExtension(UnitTestProtoFile.OptionalInt64Extension));
+ Assert.AreEqual(103U, message.GetExtension(UnitTestProtoFile.OptionalUint32Extension));
+ Assert.AreEqual(104UL, message.GetExtension(UnitTestProtoFile.OptionalUint64Extension));
+ Assert.AreEqual(105, message.GetExtension(UnitTestProtoFile.OptionalSint32Extension));
+ Assert.AreEqual(106L, message.GetExtension(UnitTestProtoFile.OptionalSint64Extension));
+ Assert.AreEqual(107U, message.GetExtension(UnitTestProtoFile.OptionalFixed32Extension));
+ Assert.AreEqual(108UL, message.GetExtension(UnitTestProtoFile.OptionalFixed64Extension));
+ Assert.AreEqual(109, message.GetExtension(UnitTestProtoFile.OptionalSfixed32Extension));
+ Assert.AreEqual(110L, message.GetExtension(UnitTestProtoFile.OptionalSfixed64Extension));
+ Assert.AreEqual(111F, message.GetExtension(UnitTestProtoFile.OptionalFloatExtension));
+ Assert.AreEqual(112D, message.GetExtension(UnitTestProtoFile.OptionalDoubleExtension));
+ Assert.AreEqual(true, message.GetExtension(UnitTestProtoFile.OptionalBoolExtension));
+ Assert.AreEqual("115", message.GetExtension(UnitTestProtoFile.OptionalStringExtension));
+ Assert.AreEqual(ToBytes("116"), message.GetExtension(UnitTestProtoFile.OptionalBytesExtension));
+
+ Assert.AreEqual(117, message.GetExtension(UnitTestProtoFile.OptionalGroupExtension).A);
+ Assert.AreEqual(118, message.GetExtension(UnitTestProtoFile.OptionalNestedMessageExtension).Bb);
+ Assert.AreEqual(119, message.GetExtension(UnitTestProtoFile.OptionalForeignMessageExtension).C);
+ Assert.AreEqual(120, message.GetExtension(UnitTestProtoFile.OptionalImportMessageExtension).D);
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAZ,
+ message.GetExtension(UnitTestProtoFile.OptionalNestedEnumExtension));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAZ,
+ message.GetExtension(UnitTestProtoFile.OptionalForeignEnumExtension));
+ Assert.AreEqual(ImportEnum.IMPORT_BAZ, message.GetExtension(UnitTestProtoFile.OptionalImportEnumExtension));
+
+ Assert.AreEqual("124", message.GetExtension(UnitTestProtoFile.OptionalStringPieceExtension));
+ Assert.AreEqual("125", message.GetExtension(UnitTestProtoFile.OptionalCordExtension));
+
+ // -----------------------------------------------------------------
+
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedInt32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedInt64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedUint32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedUint64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSint32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSint64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedFixed32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedFixed64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSfixed32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSfixed64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedFloatExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedDoubleExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedBoolExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedStringExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedBytesExtension));
+
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedGroupExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedNestedMessageExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedForeignMessageExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedImportMessageExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedNestedEnumExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedForeignEnumExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedImportEnumExtension));
+
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedStringPieceExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedCordExtension));
+
+ Assert.AreEqual(201, message.GetExtension(UnitTestProtoFile.RepeatedInt32Extension, 0));
+ Assert.AreEqual(202L, message.GetExtension(UnitTestProtoFile.RepeatedInt64Extension, 0));
+ Assert.AreEqual(203U, message.GetExtension(UnitTestProtoFile.RepeatedUint32Extension, 0));
+ Assert.AreEqual(204UL, message.GetExtension(UnitTestProtoFile.RepeatedUint64Extension, 0));
+ Assert.AreEqual(205, message.GetExtension(UnitTestProtoFile.RepeatedSint32Extension, 0));
+ Assert.AreEqual(206L, message.GetExtension(UnitTestProtoFile.RepeatedSint64Extension, 0));
+ Assert.AreEqual(207U, message.GetExtension(UnitTestProtoFile.RepeatedFixed32Extension, 0));
+ Assert.AreEqual(208UL, message.GetExtension(UnitTestProtoFile.RepeatedFixed64Extension, 0));
+ Assert.AreEqual(209, message.GetExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 0));
+ Assert.AreEqual(210L, message.GetExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 0));
+ Assert.AreEqual(211F, message.GetExtension(UnitTestProtoFile.RepeatedFloatExtension, 0));
+ Assert.AreEqual(212D, message.GetExtension(UnitTestProtoFile.RepeatedDoubleExtension, 0));
+ Assert.AreEqual(true, message.GetExtension(UnitTestProtoFile.RepeatedBoolExtension, 0));
+ Assert.AreEqual("215", message.GetExtension(UnitTestProtoFile.RepeatedStringExtension, 0));
+ Assert.AreEqual(ToBytes("216"), message.GetExtension(UnitTestProtoFile.RepeatedBytesExtension, 0));
+
+ Assert.AreEqual(217, message.GetExtension(UnitTestProtoFile.RepeatedGroupExtension, 0).A);
+ Assert.AreEqual(218, message.GetExtension(UnitTestProtoFile.RepeatedNestedMessageExtension, 0).Bb);
+ Assert.AreEqual(219, message.GetExtension(UnitTestProtoFile.RepeatedForeignMessageExtension, 0).C);
+ Assert.AreEqual(220, message.GetExtension(UnitTestProtoFile.RepeatedImportMessageExtension, 0).D);
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR,
+ message.GetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, 0));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAR,
+ message.GetExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, 0));
+ Assert.AreEqual(ImportEnum.IMPORT_BAR,
+ message.GetExtension(UnitTestProtoFile.RepeatedImportEnumExtension, 0));
+
+ Assert.AreEqual("224", message.GetExtension(UnitTestProtoFile.RepeatedStringPieceExtension, 0));
+ Assert.AreEqual("225", message.GetExtension(UnitTestProtoFile.RepeatedCordExtension, 0));
+
+ Assert.AreEqual(301, message.GetExtension(UnitTestProtoFile.RepeatedInt32Extension, 1));
+ Assert.AreEqual(302L, message.GetExtension(UnitTestProtoFile.RepeatedInt64Extension, 1));
+ Assert.AreEqual(303U, message.GetExtension(UnitTestProtoFile.RepeatedUint32Extension, 1));
+ Assert.AreEqual(304UL, message.GetExtension(UnitTestProtoFile.RepeatedUint64Extension, 1));
+ Assert.AreEqual(305, message.GetExtension(UnitTestProtoFile.RepeatedSint32Extension, 1));
+ Assert.AreEqual(306L, message.GetExtension(UnitTestProtoFile.RepeatedSint64Extension, 1));
+ Assert.AreEqual(307U, message.GetExtension(UnitTestProtoFile.RepeatedFixed32Extension, 1));
+ Assert.AreEqual(308UL, message.GetExtension(UnitTestProtoFile.RepeatedFixed64Extension, 1));
+ Assert.AreEqual(309, message.GetExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 1));
+ Assert.AreEqual(310L, message.GetExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 1));
+ Assert.AreEqual(311F, message.GetExtension(UnitTestProtoFile.RepeatedFloatExtension, 1));
+ Assert.AreEqual(312D, message.GetExtension(UnitTestProtoFile.RepeatedDoubleExtension, 1));
+ Assert.AreEqual(false, message.GetExtension(UnitTestProtoFile.RepeatedBoolExtension, 1));
+ Assert.AreEqual("315", message.GetExtension(UnitTestProtoFile.RepeatedStringExtension, 1));
+ Assert.AreEqual(ToBytes("316"), message.GetExtension(UnitTestProtoFile.RepeatedBytesExtension, 1));
+
+ Assert.AreEqual(317, message.GetExtension(UnitTestProtoFile.RepeatedGroupExtension, 1).A);
+ Assert.AreEqual(318, message.GetExtension(UnitTestProtoFile.RepeatedNestedMessageExtension, 1).Bb);
+ Assert.AreEqual(319, message.GetExtension(UnitTestProtoFile.RepeatedForeignMessageExtension, 1).C);
+ Assert.AreEqual(320, message.GetExtension(UnitTestProtoFile.RepeatedImportMessageExtension, 1).D);
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAZ,
+ message.GetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, 1));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAZ,
+ message.GetExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, 1));
+ Assert.AreEqual(ImportEnum.IMPORT_BAZ,
+ message.GetExtension(UnitTestProtoFile.RepeatedImportEnumExtension, 1));
+
+ Assert.AreEqual("324", message.GetExtension(UnitTestProtoFile.RepeatedStringPieceExtension, 1));
+ Assert.AreEqual("325", message.GetExtension(UnitTestProtoFile.RepeatedCordExtension, 1));
+
+ // -----------------------------------------------------------------
+
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultInt32Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultInt64Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultUint32Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultUint64Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultSint32Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultSint64Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultFixed32Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultFixed64Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultSfixed32Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultSfixed64Extension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultFloatExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultDoubleExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultBoolExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultStringExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultBytesExtension));
+
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultNestedEnumExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultForeignEnumExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultImportEnumExtension));
+
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultStringPieceExtension));
+ Assert.IsTrue(message.HasExtension(UnitTestProtoFile.DefaultCordExtension));
+
+ Assert.AreEqual(401, message.GetExtension(UnitTestProtoFile.DefaultInt32Extension));
+ Assert.AreEqual(402L, message.GetExtension(UnitTestProtoFile.DefaultInt64Extension));
+ Assert.AreEqual(403U, message.GetExtension(UnitTestProtoFile.DefaultUint32Extension));
+ Assert.AreEqual(404UL, message.GetExtension(UnitTestProtoFile.DefaultUint64Extension));
+ Assert.AreEqual(405, message.GetExtension(UnitTestProtoFile.DefaultSint32Extension));
+ Assert.AreEqual(406L, message.GetExtension(UnitTestProtoFile.DefaultSint64Extension));
+ Assert.AreEqual(407U, message.GetExtension(UnitTestProtoFile.DefaultFixed32Extension));
+ Assert.AreEqual(408UL, message.GetExtension(UnitTestProtoFile.DefaultFixed64Extension));
+ Assert.AreEqual(409, message.GetExtension(UnitTestProtoFile.DefaultSfixed32Extension));
+ Assert.AreEqual(410L, message.GetExtension(UnitTestProtoFile.DefaultSfixed64Extension));
+ Assert.AreEqual(411F, message.GetExtension(UnitTestProtoFile.DefaultFloatExtension));
+ Assert.AreEqual(412D, message.GetExtension(UnitTestProtoFile.DefaultDoubleExtension));
+ Assert.AreEqual(false, message.GetExtension(UnitTestProtoFile.DefaultBoolExtension));
+ Assert.AreEqual("415", message.GetExtension(UnitTestProtoFile.DefaultStringExtension));
+ Assert.AreEqual(ToBytes("416"), message.GetExtension(UnitTestProtoFile.DefaultBytesExtension));
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO,
+ message.GetExtension(UnitTestProtoFile.DefaultNestedEnumExtension));
+ Assert.AreEqual(ForeignEnum.FOREIGN_FOO, message.GetExtension(UnitTestProtoFile.DefaultForeignEnumExtension));
+ Assert.AreEqual(ImportEnum.IMPORT_FOO, message.GetExtension(UnitTestProtoFile.DefaultImportEnumExtension));
+
+ Assert.AreEqual("424", message.GetExtension(UnitTestProtoFile.DefaultStringPieceExtension));
+ Assert.AreEqual("425", message.GetExtension(UnitTestProtoFile.DefaultCordExtension));
+ }
+
+ /// <summary>
+ /// Modifies the repeated extensions of the given message to contain the values
+ /// expected by AssertRepeatedExtensionsModified.
+ /// </summary>
+ internal static void ModifyRepeatedExtensions(TestAllExtensions.Builder message)
+ {
+ message.SetExtension(UnitTestProtoFile.RepeatedInt32Extension, 1, 501);
+ message.SetExtension(UnitTestProtoFile.RepeatedInt64Extension, 1, 502L);
+ message.SetExtension(UnitTestProtoFile.RepeatedUint32Extension, 1, 503U);
+ message.SetExtension(UnitTestProtoFile.RepeatedUint64Extension, 1, 504UL);
+ message.SetExtension(UnitTestProtoFile.RepeatedSint32Extension, 1, 505);
+ message.SetExtension(UnitTestProtoFile.RepeatedSint64Extension, 1, 506L);
+ message.SetExtension(UnitTestProtoFile.RepeatedFixed32Extension, 1, 507U);
+ message.SetExtension(UnitTestProtoFile.RepeatedFixed64Extension, 1, 508UL);
+ message.SetExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 1, 509);
+ message.SetExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 1, 510L);
+ message.SetExtension(UnitTestProtoFile.RepeatedFloatExtension, 1, 511F);
+ message.SetExtension(UnitTestProtoFile.RepeatedDoubleExtension, 1, 512D);
+ message.SetExtension(UnitTestProtoFile.RepeatedBoolExtension, 1, true);
+ message.SetExtension(UnitTestProtoFile.RepeatedStringExtension, 1, "515");
+ message.SetExtension(UnitTestProtoFile.RepeatedBytesExtension, 1, ToBytes("516"));
+
+ message.SetExtension(UnitTestProtoFile.RepeatedGroupExtension, 1,
+ RepeatedGroup_extension.CreateBuilder().SetA(517).Build());
+ message.SetExtension(UnitTestProtoFile.RepeatedNestedMessageExtension, 1,
+ TestAllTypes.Types.NestedMessage.CreateBuilder().SetBb(518).Build());
+ message.SetExtension(UnitTestProtoFile.RepeatedForeignMessageExtension, 1,
+ ForeignMessage.CreateBuilder().SetC(519).Build());
+ message.SetExtension(UnitTestProtoFile.RepeatedImportMessageExtension, 1,
+ ImportMessage.CreateBuilder().SetD(520).Build());
+
+ message.SetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, 1, TestAllTypes.Types.NestedEnum.FOO);
+ message.SetExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, 1, ForeignEnum.FOREIGN_FOO);
+ message.SetExtension(UnitTestProtoFile.RepeatedImportEnumExtension, 1, ImportEnum.IMPORT_FOO);
+
+ message.SetExtension(UnitTestProtoFile.RepeatedStringPieceExtension, 1, "524");
+ message.SetExtension(UnitTestProtoFile.RepeatedCordExtension, 1, "525");
+ }
+
+ /// <summary>
+ /// Asserts that all repeated extensions are set to the values assigned by
+ /// SetAllExtensions follwed by ModifyRepeatedExtensions.
+ /// </summary>
+ internal static void AssertRepeatedExtensionsModified(TestAllExtensions message)
+ {
+ // ModifyRepeatedFields only sets the second repeated element of each
+ // field. In addition to verifying this, we also verify that the first
+ // element and size were *not* modified.
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedInt32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedInt64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedUint32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedUint64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSint32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSint64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedFixed32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedFixed64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSfixed32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedSfixed64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedFloatExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedDoubleExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedBoolExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedStringExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedBytesExtension));
+
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedGroupExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedNestedMessageExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedForeignMessageExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedImportMessageExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedNestedEnumExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedForeignEnumExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedImportEnumExtension));
+
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedStringPieceExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.RepeatedCordExtension));
+
+ Assert.AreEqual(201, message.GetExtension(UnitTestProtoFile.RepeatedInt32Extension, 0));
+ Assert.AreEqual(202L, message.GetExtension(UnitTestProtoFile.RepeatedInt64Extension, 0));
+ Assert.AreEqual(203U, message.GetExtension(UnitTestProtoFile.RepeatedUint32Extension, 0));
+ Assert.AreEqual(204UL, message.GetExtension(UnitTestProtoFile.RepeatedUint64Extension, 0));
+ Assert.AreEqual(205, message.GetExtension(UnitTestProtoFile.RepeatedSint32Extension, 0));
+ Assert.AreEqual(206L, message.GetExtension(UnitTestProtoFile.RepeatedSint64Extension, 0));
+ Assert.AreEqual(207U, message.GetExtension(UnitTestProtoFile.RepeatedFixed32Extension, 0));
+ Assert.AreEqual(208UL, message.GetExtension(UnitTestProtoFile.RepeatedFixed64Extension, 0));
+ Assert.AreEqual(209, message.GetExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 0));
+ Assert.AreEqual(210L, message.GetExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 0));
+ Assert.AreEqual(211F, message.GetExtension(UnitTestProtoFile.RepeatedFloatExtension, 0));
+ Assert.AreEqual(212D, message.GetExtension(UnitTestProtoFile.RepeatedDoubleExtension, 0));
+ Assert.AreEqual(true, message.GetExtension(UnitTestProtoFile.RepeatedBoolExtension, 0));
+ Assert.AreEqual("215", message.GetExtension(UnitTestProtoFile.RepeatedStringExtension, 0));
+ Assert.AreEqual(ToBytes("216"), message.GetExtension(UnitTestProtoFile.RepeatedBytesExtension, 0));
+
+ Assert.AreEqual(217, message.GetExtension(UnitTestProtoFile.RepeatedGroupExtension, 0).A);
+ Assert.AreEqual(218, message.GetExtension(UnitTestProtoFile.RepeatedNestedMessageExtension, 0).Bb);
+ Assert.AreEqual(219, message.GetExtension(UnitTestProtoFile.RepeatedForeignMessageExtension, 0).C);
+ Assert.AreEqual(220, message.GetExtension(UnitTestProtoFile.RepeatedImportMessageExtension, 0).D);
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR,
+ message.GetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, 0));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAR,
+ message.GetExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, 0));
+ Assert.AreEqual(ImportEnum.IMPORT_BAR,
+ message.GetExtension(UnitTestProtoFile.RepeatedImportEnumExtension, 0));
+
+ Assert.AreEqual("224", message.GetExtension(UnitTestProtoFile.RepeatedStringPieceExtension, 0));
+ Assert.AreEqual("225", message.GetExtension(UnitTestProtoFile.RepeatedCordExtension, 0));
+
+ // Actually verify the second (modified) elements now.
+ Assert.AreEqual(501, message.GetExtension(UnitTestProtoFile.RepeatedInt32Extension, 1));
+ Assert.AreEqual(502L, message.GetExtension(UnitTestProtoFile.RepeatedInt64Extension, 1));
+ Assert.AreEqual(503U, message.GetExtension(UnitTestProtoFile.RepeatedUint32Extension, 1));
+ Assert.AreEqual(504UL, message.GetExtension(UnitTestProtoFile.RepeatedUint64Extension, 1));
+ Assert.AreEqual(505, message.GetExtension(UnitTestProtoFile.RepeatedSint32Extension, 1));
+ Assert.AreEqual(506L, message.GetExtension(UnitTestProtoFile.RepeatedSint64Extension, 1));
+ Assert.AreEqual(507U, message.GetExtension(UnitTestProtoFile.RepeatedFixed32Extension, 1));
+ Assert.AreEqual(508UL, message.GetExtension(UnitTestProtoFile.RepeatedFixed64Extension, 1));
+ Assert.AreEqual(509, message.GetExtension(UnitTestProtoFile.RepeatedSfixed32Extension, 1));
+ Assert.AreEqual(510L, message.GetExtension(UnitTestProtoFile.RepeatedSfixed64Extension, 1));
+ Assert.AreEqual(511F, message.GetExtension(UnitTestProtoFile.RepeatedFloatExtension, 1));
+ Assert.AreEqual(512D, message.GetExtension(UnitTestProtoFile.RepeatedDoubleExtension, 1));
+ Assert.AreEqual(true, message.GetExtension(UnitTestProtoFile.RepeatedBoolExtension, 1));
+ Assert.AreEqual("515", message.GetExtension(UnitTestProtoFile.RepeatedStringExtension, 1));
+ Assert.AreEqual(ToBytes("516"), message.GetExtension(UnitTestProtoFile.RepeatedBytesExtension, 1));
+
+ Assert.AreEqual(517, message.GetExtension(UnitTestProtoFile.RepeatedGroupExtension, 1).A);
+ Assert.AreEqual(518, message.GetExtension(UnitTestProtoFile.RepeatedNestedMessageExtension, 1).Bb);
+ Assert.AreEqual(519, message.GetExtension(UnitTestProtoFile.RepeatedForeignMessageExtension, 1).C);
+ Assert.AreEqual(520, message.GetExtension(UnitTestProtoFile.RepeatedImportMessageExtension, 1).D);
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO,
+ message.GetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension, 1));
+ Assert.AreEqual(ForeignEnum.FOREIGN_FOO,
+ message.GetExtension(UnitTestProtoFile.RepeatedForeignEnumExtension, 1));
+ Assert.AreEqual(ImportEnum.IMPORT_FOO,
+ message.GetExtension(UnitTestProtoFile.RepeatedImportEnumExtension, 1));
+
+ Assert.AreEqual("524", message.GetExtension(UnitTestProtoFile.RepeatedStringPieceExtension, 1));
+ Assert.AreEqual("525", message.GetExtension(UnitTestProtoFile.RepeatedCordExtension, 1));
+ }
+
+ internal static void AssertExtensionsClear(TestAllExtensions message)
+ {
+ // HasBlah() should initially be false for all optional fields.
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalInt32Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalInt64Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalUint32Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalUint64Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalSint32Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalSint64Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalFixed32Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalFixed64Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalSfixed32Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalSfixed64Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalFloatExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalDoubleExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalBoolExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalStringExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalBytesExtension));
+
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalGroupExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalNestedMessageExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalForeignMessageExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalImportMessageExtension));
+
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalNestedEnumExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalForeignEnumExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalImportEnumExtension));
+
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalStringPieceExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.OptionalCordExtension));
+
+ // Optional fields without defaults are set to zero or something like it.
+ Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalInt32Extension));
+ Assert.AreEqual(0L, message.GetExtension(UnitTestProtoFile.OptionalInt64Extension));
+ Assert.AreEqual(0U, message.GetExtension(UnitTestProtoFile.OptionalUint32Extension));
+ Assert.AreEqual(0UL, message.GetExtension(UnitTestProtoFile.OptionalUint64Extension));
+ Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalSint32Extension));
+ Assert.AreEqual(0L, message.GetExtension(UnitTestProtoFile.OptionalSint64Extension));
+ Assert.AreEqual(0U, message.GetExtension(UnitTestProtoFile.OptionalFixed32Extension));
+ Assert.AreEqual(0UL, message.GetExtension(UnitTestProtoFile.OptionalFixed64Extension));
+ Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalSfixed32Extension));
+ Assert.AreEqual(0L, message.GetExtension(UnitTestProtoFile.OptionalSfixed64Extension));
+ Assert.AreEqual(0F, message.GetExtension(UnitTestProtoFile.OptionalFloatExtension));
+ Assert.AreEqual(0D, message.GetExtension(UnitTestProtoFile.OptionalDoubleExtension));
+ Assert.AreEqual(false, message.GetExtension(UnitTestProtoFile.OptionalBoolExtension));
+ Assert.AreEqual("", message.GetExtension(UnitTestProtoFile.OptionalStringExtension));
+ Assert.AreEqual(ByteString.Empty, message.GetExtension(UnitTestProtoFile.OptionalBytesExtension));
+
+ // Embedded messages should also be clear.
+ Assert.IsFalse(message.GetExtension(UnitTestProtoFile.OptionalGroupExtension).HasA);
+ Assert.IsFalse(message.GetExtension(UnitTestProtoFile.OptionalNestedMessageExtension).HasBb);
+ Assert.IsFalse(message.GetExtension(UnitTestProtoFile.OptionalForeignMessageExtension).HasC);
+ Assert.IsFalse(message.GetExtension(UnitTestProtoFile.OptionalImportMessageExtension).HasD);
+
+ Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalGroupExtension).A);
+ Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalNestedMessageExtension).Bb);
+ Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalForeignMessageExtension).C);
+ Assert.AreEqual(0, message.GetExtension(UnitTestProtoFile.OptionalImportMessageExtension).D);
+
+ // Enums without defaults are set to the first value in the enum.
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO,
+ message.GetExtension(UnitTestProtoFile.OptionalNestedEnumExtension));
+ Assert.AreEqual(ForeignEnum.FOREIGN_FOO,
+ message.GetExtension(UnitTestProtoFile.OptionalForeignEnumExtension));
+ Assert.AreEqual(ImportEnum.IMPORT_FOO, message.GetExtension(UnitTestProtoFile.OptionalImportEnumExtension));
+
+ Assert.AreEqual("", message.GetExtension(UnitTestProtoFile.OptionalStringPieceExtension));
+ Assert.AreEqual("", message.GetExtension(UnitTestProtoFile.OptionalCordExtension));
+
+ // Repeated fields are empty.
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedInt32Extension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedInt64Extension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedUint32Extension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedUint64Extension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedSint32Extension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedSint64Extension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedFixed32Extension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedFixed64Extension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedSfixed32Extension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedSfixed64Extension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedFloatExtension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedDoubleExtension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedBoolExtension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedStringExtension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedBytesExtension));
+
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedGroupExtension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedNestedMessageExtension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedForeignMessageExtension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedImportMessageExtension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedNestedEnumExtension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedForeignEnumExtension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedImportEnumExtension));
+
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedStringPieceExtension));
+ Assert.AreEqual(0, message.GetExtensionCount(UnitTestProtoFile.RepeatedCordExtension));
+
+ // HasBlah() should also be false for all default fields.
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultInt32Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultInt64Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultUint32Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultUint64Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultSint32Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultSint64Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultFixed32Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultFixed64Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultSfixed32Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultSfixed64Extension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultFloatExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultDoubleExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultBoolExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultStringExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultBytesExtension));
+
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultNestedEnumExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultForeignEnumExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultImportEnumExtension));
+
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultStringPieceExtension));
+ Assert.IsFalse(message.HasExtension(UnitTestProtoFile.DefaultCordExtension));
+
+ // Fields with defaults have their default values (duh).
+ Assert.AreEqual(41, message.GetExtension(UnitTestProtoFile.DefaultInt32Extension));
+ Assert.AreEqual(42L, message.GetExtension(UnitTestProtoFile.DefaultInt64Extension));
+ Assert.AreEqual(43U, message.GetExtension(UnitTestProtoFile.DefaultUint32Extension));
+ Assert.AreEqual(44UL, message.GetExtension(UnitTestProtoFile.DefaultUint64Extension));
+ Assert.AreEqual(-45, message.GetExtension(UnitTestProtoFile.DefaultSint32Extension));
+ Assert.AreEqual(46L, message.GetExtension(UnitTestProtoFile.DefaultSint64Extension));
+ Assert.AreEqual(47U, message.GetExtension(UnitTestProtoFile.DefaultFixed32Extension));
+ Assert.AreEqual(48UL, message.GetExtension(UnitTestProtoFile.DefaultFixed64Extension));
+ Assert.AreEqual(49, message.GetExtension(UnitTestProtoFile.DefaultSfixed32Extension));
+ Assert.AreEqual(-50L, message.GetExtension(UnitTestProtoFile.DefaultSfixed64Extension));
+ Assert.AreEqual(51.5F, message.GetExtension(UnitTestProtoFile.DefaultFloatExtension));
+ Assert.AreEqual(52e3D, message.GetExtension(UnitTestProtoFile.DefaultDoubleExtension));
+ Assert.AreEqual(true, message.GetExtension(UnitTestProtoFile.DefaultBoolExtension));
+ Assert.AreEqual("hello", message.GetExtension(UnitTestProtoFile.DefaultStringExtension));
+ Assert.AreEqual(ToBytes("world"), message.GetExtension(UnitTestProtoFile.DefaultBytesExtension));
+
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR,
+ message.GetExtension(UnitTestProtoFile.DefaultNestedEnumExtension));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAR, message.GetExtension(UnitTestProtoFile.DefaultForeignEnumExtension));
+ Assert.AreEqual(ImportEnum.IMPORT_BAR, message.GetExtension(UnitTestProtoFile.DefaultImportEnumExtension));
+
+ Assert.AreEqual("abc", message.GetExtension(UnitTestProtoFile.DefaultStringPieceExtension));
+ Assert.AreEqual("123", message.GetExtension(UnitTestProtoFile.DefaultCordExtension));
+ }
+
+ /// <summary>
+ /// Set every field of the specified message to a unique value.
+ /// </summary>
+ public static void SetPackedFields(TestPackedTypes.Builder message)
+ {
+ message.AddPackedInt32(601);
+ message.AddPackedInt64(602);
+ message.AddPackedUint32(603);
+ message.AddPackedUint64(604);
+ message.AddPackedSint32(605);
+ message.AddPackedSint64(606);
+ message.AddPackedFixed32(607);
+ message.AddPackedFixed64(608);
+ message.AddPackedSfixed32(609);
+ message.AddPackedSfixed64(610);
+ message.AddPackedFloat(611);
+ message.AddPackedDouble(612);
+ message.AddPackedBool(true);
+ message.AddPackedEnum(ForeignEnum.FOREIGN_BAR);
+ // Add a second one of each field.
+ message.AddPackedInt32(701);
+ message.AddPackedInt64(702);
+ message.AddPackedUint32(703);
+ message.AddPackedUint64(704);
+ message.AddPackedSint32(705);
+ message.AddPackedSint64(706);
+ message.AddPackedFixed32(707);
+ message.AddPackedFixed64(708);
+ message.AddPackedSfixed32(709);
+ message.AddPackedSfixed64(710);
+ message.AddPackedFloat(711);
+ message.AddPackedDouble(712);
+ message.AddPackedBool(false);
+ message.AddPackedEnum(ForeignEnum.FOREIGN_BAZ);
+ }
+
+ /// <summary>
+ /// Asserts that all the fields of the specified message are set to the values assigned
+ /// in SetPackedFields.
+ /// </summary>
+ public static void AssertPackedFieldsSet(TestPackedTypes message)
+ {
+ Assert.AreEqual(2, message.PackedInt32Count);
+ Assert.AreEqual(2, message.PackedInt64Count);
+ Assert.AreEqual(2, message.PackedUint32Count);
+ Assert.AreEqual(2, message.PackedUint64Count);
+ Assert.AreEqual(2, message.PackedSint32Count);
+ Assert.AreEqual(2, message.PackedSint64Count);
+ Assert.AreEqual(2, message.PackedFixed32Count);
+ Assert.AreEqual(2, message.PackedFixed64Count);
+ Assert.AreEqual(2, message.PackedSfixed32Count);
+ Assert.AreEqual(2, message.PackedSfixed64Count);
+ Assert.AreEqual(2, message.PackedFloatCount);
+ Assert.AreEqual(2, message.PackedDoubleCount);
+ Assert.AreEqual(2, message.PackedBoolCount);
+ Assert.AreEqual(2, message.PackedEnumCount);
+ Assert.AreEqual(601, message.GetPackedInt32(0));
+ Assert.AreEqual(602, message.GetPackedInt64(0));
+ Assert.AreEqual(603, message.GetPackedUint32(0));
+ Assert.AreEqual(604, message.GetPackedUint64(0));
+ Assert.AreEqual(605, message.GetPackedSint32(0));
+ Assert.AreEqual(606, message.GetPackedSint64(0));
+ Assert.AreEqual(607, message.GetPackedFixed32(0));
+ Assert.AreEqual(608, message.GetPackedFixed64(0));
+ Assert.AreEqual(609, message.GetPackedSfixed32(0));
+ Assert.AreEqual(610, message.GetPackedSfixed64(0));
+ Assert.AreEqual(611, message.GetPackedFloat(0), 0.0);
+ Assert.AreEqual(612, message.GetPackedDouble(0), 0.0);
+ Assert.AreEqual(true, message.GetPackedBool(0));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAR, message.GetPackedEnum(0));
+ Assert.AreEqual(701, message.GetPackedInt32(1));
+ Assert.AreEqual(702, message.GetPackedInt64(1));
+ Assert.AreEqual(703, message.GetPackedUint32(1));
+ Assert.AreEqual(704, message.GetPackedUint64(1));
+ Assert.AreEqual(705, message.GetPackedSint32(1));
+ Assert.AreEqual(706, message.GetPackedSint64(1));
+ Assert.AreEqual(707, message.GetPackedFixed32(1));
+ Assert.AreEqual(708, message.GetPackedFixed64(1));
+ Assert.AreEqual(709, message.GetPackedSfixed32(1));
+ Assert.AreEqual(710, message.GetPackedSfixed64(1));
+ Assert.AreEqual(711, message.GetPackedFloat(1), 0.0);
+ Assert.AreEqual(712, message.GetPackedDouble(1), 0.0);
+ Assert.AreEqual(false, message.GetPackedBool(1));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, message.GetPackedEnum(1));
+ }
+
+ public static void SetPackedExtensions(TestPackedExtensions.Builder message)
+ {
+ message.AddExtension(UnitTestProtoFile.PackedInt32Extension, 601);
+ message.AddExtension(UnitTestProtoFile.PackedInt64Extension, 602L);
+ message.AddExtension(UnitTestProtoFile.PackedUint32Extension, 603U);
+ message.AddExtension(UnitTestProtoFile.PackedUint64Extension, 604UL);
+ message.AddExtension(UnitTestProtoFile.PackedSint32Extension, 605);
+ message.AddExtension(UnitTestProtoFile.PackedSint64Extension, 606L);
+ message.AddExtension(UnitTestProtoFile.PackedFixed32Extension, 607U);
+ message.AddExtension(UnitTestProtoFile.PackedFixed64Extension, 608UL);
+ message.AddExtension(UnitTestProtoFile.PackedSfixed32Extension, 609);
+ message.AddExtension(UnitTestProtoFile.PackedSfixed64Extension, 610L);
+ message.AddExtension(UnitTestProtoFile.PackedFloatExtension, 611F);
+ message.AddExtension(UnitTestProtoFile.PackedDoubleExtension, 612D);
+ message.AddExtension(UnitTestProtoFile.PackedBoolExtension, true);
+ message.AddExtension(UnitTestProtoFile.PackedEnumExtension, ForeignEnum.FOREIGN_BAR);
+ // Add a second one of each field.
+ message.AddExtension(UnitTestProtoFile.PackedInt32Extension, 701);
+ message.AddExtension(UnitTestProtoFile.PackedInt64Extension, 702L);
+ message.AddExtension(UnitTestProtoFile.PackedUint32Extension, 703U);
+ message.AddExtension(UnitTestProtoFile.PackedUint64Extension, 704UL);
+ message.AddExtension(UnitTestProtoFile.PackedSint32Extension, 705);
+ message.AddExtension(UnitTestProtoFile.PackedSint64Extension, 706L);
+ message.AddExtension(UnitTestProtoFile.PackedFixed32Extension, 707U);
+ message.AddExtension(UnitTestProtoFile.PackedFixed64Extension, 708UL);
+ message.AddExtension(UnitTestProtoFile.PackedSfixed32Extension, 709);
+ message.AddExtension(UnitTestProtoFile.PackedSfixed64Extension, 710L);
+ message.AddExtension(UnitTestProtoFile.PackedFloatExtension, 711F);
+ message.AddExtension(UnitTestProtoFile.PackedDoubleExtension, 712D);
+ message.AddExtension(UnitTestProtoFile.PackedBoolExtension, false);
+ message.AddExtension(UnitTestProtoFile.PackedEnumExtension, ForeignEnum.FOREIGN_BAZ);
+ }
+
+ public static void AssertPackedExtensionsSet(TestPackedExtensions message)
+ {
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedInt32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedInt64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedUint32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedUint64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedSint32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedSint64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedFixed32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedFixed64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedSfixed32Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedSfixed64Extension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedFloatExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedDoubleExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedBoolExtension));
+ Assert.AreEqual(2, message.GetExtensionCount(UnitTestProtoFile.PackedEnumExtension));
+ Assert.AreEqual(601, message.GetExtension(UnitTestProtoFile.PackedInt32Extension, 0));
+ Assert.AreEqual(602L, message.GetExtension(UnitTestProtoFile.PackedInt64Extension, 0));
+ Assert.AreEqual(603, message.GetExtension(UnitTestProtoFile.PackedUint32Extension, 0));
+ Assert.AreEqual(604L, message.GetExtension(UnitTestProtoFile.PackedUint64Extension, 0));
+ Assert.AreEqual(605, message.GetExtension(UnitTestProtoFile.PackedSint32Extension, 0));
+ Assert.AreEqual(606L, message.GetExtension(UnitTestProtoFile.PackedSint64Extension, 0));
+ Assert.AreEqual(607, message.GetExtension(UnitTestProtoFile.PackedFixed32Extension, 0));
+ Assert.AreEqual(608L, message.GetExtension(UnitTestProtoFile.PackedFixed64Extension, 0));
+ Assert.AreEqual(609, message.GetExtension(UnitTestProtoFile.PackedSfixed32Extension, 0));
+ Assert.AreEqual(610L, message.GetExtension(UnitTestProtoFile.PackedSfixed64Extension, 0));
+ Assert.AreEqual(611F, message.GetExtension(UnitTestProtoFile.PackedFloatExtension, 0));
+ Assert.AreEqual(612D, message.GetExtension(UnitTestProtoFile.PackedDoubleExtension, 0));
+ Assert.AreEqual(true, message.GetExtension(UnitTestProtoFile.PackedBoolExtension, 0));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAR,
+ message.GetExtension(UnitTestProtoFile.PackedEnumExtension, 0));
+ Assert.AreEqual(701, message.GetExtension(UnitTestProtoFile.PackedInt32Extension, 1));
+ Assert.AreEqual(702L, message.GetExtension(UnitTestProtoFile.PackedInt64Extension, 1));
+ Assert.AreEqual(703, message.GetExtension(UnitTestProtoFile.PackedUint32Extension, 1));
+ Assert.AreEqual(704L, message.GetExtension(UnitTestProtoFile.PackedUint64Extension, 1));
+ Assert.AreEqual(705, message.GetExtension(UnitTestProtoFile.PackedSint32Extension, 1));
+ Assert.AreEqual(706L, message.GetExtension(UnitTestProtoFile.PackedSint64Extension, 1));
+ Assert.AreEqual(707, message.GetExtension(UnitTestProtoFile.PackedFixed32Extension, 1));
+ Assert.AreEqual(708L, message.GetExtension(UnitTestProtoFile.PackedFixed64Extension, 1));
+ Assert.AreEqual(709, message.GetExtension(UnitTestProtoFile.PackedSfixed32Extension, 1));
+ Assert.AreEqual(710L, message.GetExtension(UnitTestProtoFile.PackedSfixed64Extension, 1));
+ Assert.AreEqual(711F, message.GetExtension(UnitTestProtoFile.PackedFloatExtension, 1));
+ Assert.AreEqual(712D, message.GetExtension(UnitTestProtoFile.PackedDoubleExtension, 1));
+ Assert.AreEqual(false, message.GetExtension(UnitTestProtoFile.PackedBoolExtension, 1));
+ Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, message.GetExtension(UnitTestProtoFile.PackedEnumExtension, 1));
+ }
+
+ private static ByteString goldenPackedFieldsMessage = null;
+
+ /// <summary>
+ /// Get the bytes of the "golden packed fields message". This is a serialized
+ /// TestPackedTypes with all fields set as they would be by SetPackedFields,
+ /// but it is loaded from a file on disk rather than generated dynamically.
+ /// The file is actually generated by C++ code, so testing against it verifies compatibility
+ /// with C++.
+ /// </summary>
+ public static ByteString GetGoldenPackedFieldsMessage()
+ {
+ if (goldenPackedFieldsMessage == null)
+ {
+ goldenPackedFieldsMessage = ReadBytesFromFile("golden_packed_fields_message");
+ }
+ return goldenPackedFieldsMessage;
+ }
+
+ private static readonly string[] TestCultures = {"en-US", "en-GB", "fr-FR", "de-DE"};
+
+ public static void TestInMultipleCultures(Action test)
+ {
+ CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
+ foreach (string culture in TestCultures)
+ {
+ try
+ {
+ Thread.CurrentThread.CurrentCulture = new CultureInfo(culture);
+ test();
+ }
+ finally
+ {
+ Thread.CurrentThread.CurrentCulture = originalCulture;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Helper to construct a byte array from a bunch of bytes.
+ /// </summary>
+ internal static byte[] Bytes(params byte[] bytesAsInts)
+ {
+ byte[] bytes = new byte[bytesAsInts.Length];
+ for (int i = 0; i < bytesAsInts.Length; i++)
+ {
+ bytes[i] = (byte) bytesAsInts[i];
+ }
+ return bytes;
+ }
+
+ internal static void AssertArgumentNullException(Action action)
+ {
+ try
+ {
+ action();
+ Assert.Fail("Exception was not thrown");
+ }
+ catch (ArgumentNullException)
+ {
+ // We expect this exception.
+ }
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/TextFormatTest.cs b/src/ProtocolBuffers.Test/TextFormatTest.cs index 681c9d0c..76b89203 100644 --- a/src/ProtocolBuffers.Test/TextFormatTest.cs +++ b/src/ProtocolBuffers.Test/TextFormatTest.cs @@ -1,536 +1,571 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.IO; -using System.Text; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; -using System.Globalization; -using System.Threading; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class TextFormatTest { - - private static readonly string AllFieldsSetText = TestUtil.ReadTextFromFile("text_format_unittest_data.txt"); - private static readonly string AllExtensionsSetText = TestUtil.ReadTextFromFile("text_format_unittest_extensions_data.txt"); - - /// <summary> - /// Note that this is slightly different to the Java - 123.0 becomes 123, and 1.23E17 becomes 1.23E+17. - /// Both of these differences can be parsed by the Java and the C++, and we can parse their output too. - /// </summary> - private const string ExoticText = - "repeated_int32: -1\n" + - "repeated_int32: -2147483648\n" + - "repeated_int64: -1\n" + - "repeated_int64: -9223372036854775808\n" + - "repeated_uint32: 4294967295\n" + - "repeated_uint32: 2147483648\n" + - "repeated_uint64: 18446744073709551615\n" + - "repeated_uint64: 9223372036854775808\n" + - "repeated_double: 123\n" + - "repeated_double: 123.5\n" + - "repeated_double: 0.125\n" + - "repeated_double: 1.23E+17\n" + - "repeated_double: 1.235E+22\n" + - "repeated_double: 1.235E-18\n" + - "repeated_double: 123.456789\n" + - "repeated_double: Infinity\n" + - "repeated_double: -Infinity\n" + - "repeated_double: NaN\n" + - "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"" + - "\\341\\210\\264\"\n" + - "repeated_bytes: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\376\"\n"; - - private const string MessageSetText = - "[protobuf_unittest.TestMessageSetExtension1] {\n" + - " i: 123\n" + - "}\n" + - "[protobuf_unittest.TestMessageSetExtension2] {\n" + - " str: \"foo\"\n" + - "}\n"; - - /// <summary> - /// Print TestAllTypes and compare with golden file. - /// </summary> - [Test] - public void PrintMessage() { - TestUtil.TestInMultipleCultures(() => { - string text = TextFormat.PrintToString(TestUtil.GetAllSet()); - Assert.AreEqual(AllFieldsSetText.Replace("\r\n", "\n"), text.Replace("\r\n", "\n")); - }); - } - - /// <summary> - /// Print TestAllExtensions and compare with golden file. - /// </summary> - [Test] - public void PrintExtensions() { - string text = TextFormat.PrintToString(TestUtil.GetAllExtensionsSet()); - - Assert.AreEqual(AllExtensionsSetText.Replace("\r\n", "\n"), text.Replace("\r\n", "\n")); - } - - /// <summary> - /// Test printing of unknown fields in a message. - /// </summary> - [Test] - public void PrintUnknownFields() { - TestEmptyMessage message = - TestEmptyMessage.CreateBuilder() - .SetUnknownFields( - UnknownFieldSet.CreateBuilder() - .AddField(5, - UnknownField.CreateBuilder() - .AddVarint(1) - .AddFixed32(2) - .AddFixed64(3) - .AddLengthDelimited(ByteString.CopyFromUtf8("4")) - .AddGroup( - UnknownFieldSet.CreateBuilder() - .AddField(10, - UnknownField.CreateBuilder() - .AddVarint(5) - .Build()) - .Build()) - .Build()) - .AddField(8, - UnknownField.CreateBuilder() - .AddVarint(1) - .AddVarint(2) - .AddVarint(3) - .Build()) - .AddField(15, - UnknownField.CreateBuilder() - .AddVarint(0xABCDEF1234567890L) - .AddFixed32(0xABCD1234) - .AddFixed64(0xABCDEF1234567890L) - .Build()) - .Build()) - .Build(); - - Assert.AreEqual( - "5: 1\n" + - "5: 0x00000002\n" + - "5: 0x0000000000000003\n" + - "5: \"4\"\n" + - "5 {\n" + - " 10: 5\n" + - "}\n" + - "8: 1\n" + - "8: 2\n" + - "8: 3\n" + - "15: 12379813812177893520\n" + - "15: 0xabcd1234\n" + - "15: 0xabcdef1234567890\n", - TextFormat.PrintToString(message)); - } - - /// <summary> - /// Helper to construct a ByteString from a string containing only 8-bit - /// characters. The characters are converted directly to bytes, *not* - /// encoded using UTF-8. - /// </summary> - private static ByteString Bytes(string str) { - return ByteString.CopyFrom(Encoding.GetEncoding(28591).GetBytes(str)); - } - - [Test] - public void PrintExotic() { - IMessage message = TestAllTypes.CreateBuilder() - // Signed vs. unsigned numbers. - .AddRepeatedInt32 (-1) - .AddRepeatedUint32(uint.MaxValue) - .AddRepeatedInt64 (-1) - .AddRepeatedUint64(ulong.MaxValue) - - .AddRepeatedInt32 (1 << 31) - .AddRepeatedUint32(1U << 31) - .AddRepeatedInt64 (1L << 63) - .AddRepeatedUint64(1UL << 63) - - // Floats of various precisions and exponents. - .AddRepeatedDouble(123) - .AddRepeatedDouble(123.5) - .AddRepeatedDouble(0.125) - .AddRepeatedDouble(123e15) - .AddRepeatedDouble(123.5e20) - .AddRepeatedDouble(123.5e-20) - .AddRepeatedDouble(123.456789) - .AddRepeatedDouble(Double.PositiveInfinity) - .AddRepeatedDouble(Double.NegativeInfinity) - .AddRepeatedDouble(Double.NaN) - - // Strings and bytes that needing escaping. - .AddRepeatedString("\0\u0001\u0007\b\f\n\r\t\v\\\'\"\u1234") - .AddRepeatedBytes(Bytes("\0\u0001\u0007\b\f\n\r\t\v\\\'\"\u00fe")) - .Build(); - - Assert.AreEqual(ExoticText, message.ToString()); - } - - [Test] - public void PrintMessageSet() { - TestMessageSet messageSet = - TestMessageSet.CreateBuilder() - .SetExtension( - TestMessageSetExtension1.MessageSetExtension, - TestMessageSetExtension1.CreateBuilder().SetI(123).Build()) - .SetExtension( - TestMessageSetExtension2.MessageSetExtension, - TestMessageSetExtension2.CreateBuilder().SetStr("foo").Build()) - .Build(); - - Assert.AreEqual(MessageSetText, messageSet.ToString()); - } - - // ================================================================= - - [Test] - public void Parse() { - TestUtil.TestInMultipleCultures(() => { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TextFormat.Merge(AllFieldsSetText, builder); - TestUtil.AssertAllFieldsSet(builder.Build()); - }); - } - - [Test] - public void ParseReader() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TextFormat.Merge(new StringReader(AllFieldsSetText), builder); - TestUtil.AssertAllFieldsSet(builder.Build()); - } - - [Test] - public void ParseExtensions() { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - TextFormat.Merge(AllExtensionsSetText, - TestUtil.CreateExtensionRegistry(), - builder); - TestUtil.AssertAllExtensionsSet(builder.Build()); - } - - [Test] - public void ParseCompatibility() { - string original = "repeated_float: inf\n" + - "repeated_float: -inf\n" + - "repeated_float: nan\n" + - "repeated_float: inff\n" + - "repeated_float: -inff\n" + - "repeated_float: nanf\n" + - "repeated_float: 1.0f\n" + - "repeated_float: infinityf\n" + - "repeated_float: -Infinityf\n" + - "repeated_double: infinity\n" + - "repeated_double: -infinity\n" + - "repeated_double: nan\n"; - string canonical = "repeated_float: Infinity\n" + - "repeated_float: -Infinity\n" + - "repeated_float: NaN\n" + - "repeated_float: Infinity\n" + - "repeated_float: -Infinity\n" + - "repeated_float: NaN\n" + - "repeated_float: 1\n" + // Java has 1.0; this is fine - "repeated_float: Infinity\n" + - "repeated_float: -Infinity\n" + - "repeated_double: Infinity\n" + - "repeated_double: -Infinity\n" + - "repeated_double: NaN\n"; - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TextFormat.Merge(original, builder); - Assert.AreEqual(canonical, builder.Build().ToString()); - } - - [Test] - public void ParseExotic() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TextFormat.Merge(ExoticText, builder); - - // Too lazy to check things individually. Don't try to debug this - // if testPrintExotic() is Assert.Failing. - Assert.AreEqual(ExoticText, builder.Build().ToString()); - } - - [Test] - public void ParseMessageSet() { - ExtensionRegistry extensionRegistry = ExtensionRegistry.CreateInstance(); - extensionRegistry.Add(TestMessageSetExtension1.MessageSetExtension); - extensionRegistry.Add(TestMessageSetExtension2.MessageSetExtension); - - TestMessageSet.Builder builder = TestMessageSet.CreateBuilder(); - TextFormat.Merge(MessageSetText, extensionRegistry, builder); - TestMessageSet messageSet = builder.Build(); - - Assert.IsTrue(messageSet.HasExtension(TestMessageSetExtension1.MessageSetExtension)); - Assert.AreEqual(123, messageSet.GetExtension(TestMessageSetExtension1.MessageSetExtension).I); - Assert.IsTrue(messageSet.HasExtension(TestMessageSetExtension2.MessageSetExtension)); - Assert.AreEqual("foo", messageSet.GetExtension(TestMessageSetExtension2.MessageSetExtension).Str); - } - - [Test] - public void ParseNumericEnum() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TextFormat.Merge("optional_nested_enum: 2", builder); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, builder.OptionalNestedEnum); - } - - [Test] - public void ParseAngleBrackets() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TextFormat.Merge("OptionalGroup: < a: 1 >", builder); - Assert.IsTrue(builder.HasOptionalGroup); - Assert.AreEqual(1, builder.OptionalGroup.A); - } - - [Test] - public void ParseComment() { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TextFormat.Merge( - "# this is a comment\n" + - "optional_int32: 1 # another comment\n" + - "optional_int64: 2\n" + - "# EOF comment", builder); - Assert.AreEqual(1, builder.OptionalInt32); - Assert.AreEqual(2, builder.OptionalInt64); - } - - - private static void AssertParseError(string error, string text) { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - try { - TextFormat.Merge(text, TestUtil.CreateExtensionRegistry(), builder); - Assert.Fail("Expected parse exception."); - } catch (FormatException e) { - Assert.AreEqual(error, e.Message); - } - } - - [Test] - public void ParseErrors() { - AssertParseError( - "1:16: Expected \":\".", - "optional_int32 123"); - AssertParseError( - "1:23: Expected identifier.", - "optional_nested_enum: ?"); - AssertParseError( - "1:18: Couldn't parse integer: Number must be positive: -1", - "optional_uint32: -1"); - AssertParseError( - "1:17: Couldn't parse integer: Number out of range for 32-bit signed " + - "integer: 82301481290849012385230157", - "optional_int32: 82301481290849012385230157"); - AssertParseError( - "1:16: Expected \"true\" or \"false\".", - "optional_bool: maybe"); - AssertParseError( - "1:18: Expected string.", - "optional_string: 123"); - AssertParseError( - "1:18: String missing ending quote.", - "optional_string: \"ueoauaoe"); - AssertParseError( - "1:18: String missing ending quote.", - "optional_string: \"ueoauaoe\n" + - "optional_int32: 123"); - AssertParseError( - "1:18: Invalid escape sequence: '\\z'", - "optional_string: \"\\z\""); - AssertParseError( - "1:18: String missing ending quote.", - "optional_string: \"ueoauaoe\n" + - "optional_int32: 123"); - AssertParseError( - "1:2: Extension \"nosuchext\" not found in the ExtensionRegistry.", - "[nosuchext]: 123"); - AssertParseError( - "1:20: Extension \"protobuf_unittest.optional_int32_extension\" does " + - "not extend message type \"protobuf_unittest.TestAllTypes\".", - "[protobuf_unittest.optional_int32_extension]: 123"); - AssertParseError( - "1:1: Message type \"protobuf_unittest.TestAllTypes\" has no field " + - "named \"nosuchfield\".", - "nosuchfield: 123"); - AssertParseError( - "1:21: Expected \">\".", - "OptionalGroup < a: 1"); - AssertParseError( - "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " + - "value named \"NO_SUCH_VALUE\".", - "optional_nested_enum: NO_SUCH_VALUE"); - AssertParseError( - "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " + - "value with number 123.", - "optional_nested_enum: 123"); - - // Delimiters must match. - AssertParseError( - "1:22: Expected identifier.", - "OptionalGroup < a: 1 }"); - AssertParseError( - "1:22: Expected identifier.", - "OptionalGroup { a: 1 >"); - } - - // ================================================================= - - private static ByteString Bytes(params byte[] bytes) { - return ByteString.CopyFrom(bytes); - } - - private delegate void FormattingAction(); - - private static void AssertFormatException(FormattingAction action) { - try { - action(); - Assert.Fail("Should have thrown an exception."); - } catch (FormatException) { - // success - } - } - - [Test] - public void Escape() { - // Escape sequences. - Assert.AreEqual("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"", - TextFormat.EscapeBytes(Bytes("\0\u0001\u0007\b\f\n\r\t\v\\\'\""))); - Assert.AreEqual("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"", - TextFormat.EscapeText("\0\u0001\u0007\b\f\n\r\t\v\\\'\"")); - Assert.AreEqual(Bytes("\0\u0001\u0007\b\f\n\r\t\v\\\'\""), - TextFormat.UnescapeBytes("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"")); - Assert.AreEqual("\0\u0001\u0007\b\f\n\r\t\v\\\'\"", - TextFormat.UnescapeText("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"")); - - // Unicode handling. - Assert.AreEqual("\\341\\210\\264", TextFormat.EscapeText("\u1234")); - Assert.AreEqual("\\341\\210\\264", TextFormat.EscapeBytes(Bytes(0xe1, 0x88, 0xb4))); - Assert.AreEqual("\u1234", TextFormat.UnescapeText("\\341\\210\\264")); - Assert.AreEqual(Bytes(0xe1, 0x88, 0xb4), TextFormat.UnescapeBytes("\\341\\210\\264")); - Assert.AreEqual("\u1234", TextFormat.UnescapeText("\\xe1\\x88\\xb4")); - Assert.AreEqual(Bytes(0xe1, 0x88, 0xb4), TextFormat.UnescapeBytes("\\xe1\\x88\\xb4")); - - // Errors. - AssertFormatException(() => TextFormat.UnescapeText("\\x")); - AssertFormatException(() => TextFormat.UnescapeText("\\z")); - AssertFormatException(() => TextFormat.UnescapeText("\\")); - } - - [Test] - public void ParseInteger() { - Assert.AreEqual( 0, TextFormat.ParseInt32( "0")); - Assert.AreEqual( 1, TextFormat.ParseInt32( "1")); - Assert.AreEqual( -1, TextFormat.ParseInt32( "-1")); - Assert.AreEqual( 12345, TextFormat.ParseInt32( "12345")); - Assert.AreEqual( -12345, TextFormat.ParseInt32( "-12345")); - Assert.AreEqual( 2147483647, TextFormat.ParseInt32( "2147483647")); - Assert.AreEqual(-2147483648, TextFormat.ParseInt32("-2147483648")); - - Assert.AreEqual( 0, TextFormat.ParseUInt32( "0")); - Assert.AreEqual( 1, TextFormat.ParseUInt32( "1")); - Assert.AreEqual( 12345, TextFormat.ParseUInt32( "12345")); - Assert.AreEqual( 2147483647, TextFormat.ParseUInt32("2147483647")); - Assert.AreEqual(2147483648U, TextFormat.ParseUInt32("2147483648")); - Assert.AreEqual(4294967295U, TextFormat.ParseUInt32("4294967295")); - - Assert.AreEqual( 0L, TextFormat.ParseInt64( "0")); - Assert.AreEqual( 1L, TextFormat.ParseInt64( "1")); - Assert.AreEqual( -1L, TextFormat.ParseInt64( "-1")); - Assert.AreEqual( 12345L, TextFormat.ParseInt64( "12345")); - Assert.AreEqual( -12345L, TextFormat.ParseInt64( "-12345")); - Assert.AreEqual( 2147483647L, TextFormat.ParseInt64( "2147483647")); - Assert.AreEqual(-2147483648L, TextFormat.ParseInt64("-2147483648")); - Assert.AreEqual( 4294967295L, TextFormat.ParseInt64( "4294967295")); - Assert.AreEqual( 4294967296L, TextFormat.ParseInt64( "4294967296")); - Assert.AreEqual(9223372036854775807L, TextFormat.ParseInt64("9223372036854775807")); - Assert.AreEqual(-9223372036854775808L, TextFormat.ParseInt64("-9223372036854775808")); - - Assert.AreEqual( 0L, TextFormat.ParseUInt64( "0")); - Assert.AreEqual( 1L, TextFormat.ParseUInt64( "1")); - Assert.AreEqual( 12345L, TextFormat.ParseUInt64( "12345")); - Assert.AreEqual( 2147483647L, TextFormat.ParseUInt64( "2147483647")); - Assert.AreEqual( 4294967295L, TextFormat.ParseUInt64( "4294967295")); - Assert.AreEqual( 4294967296L, TextFormat.ParseUInt64( "4294967296")); - Assert.AreEqual(9223372036854775807UL, TextFormat.ParseUInt64("9223372036854775807")); - Assert.AreEqual(9223372036854775808UL, TextFormat.ParseUInt64("9223372036854775808")); - Assert.AreEqual(18446744073709551615UL, TextFormat.ParseUInt64("18446744073709551615")); - - // Hex - Assert.AreEqual(0x1234abcd, TextFormat.ParseInt32("0x1234abcd")); - Assert.AreEqual(-0x1234abcd, TextFormat.ParseInt32("-0x1234abcd")); - Assert.AreEqual(0xffffffffffffffffUL, TextFormat.ParseUInt64("0xffffffffffffffff")); - Assert.AreEqual(0x7fffffffffffffffL, - TextFormat.ParseInt64("0x7fffffffffffffff")); - - // Octal - Assert.AreEqual(342391, TextFormat.ParseInt32("01234567")); - - // Out-of-range - AssertFormatException(() => TextFormat.ParseInt32("2147483648")); - AssertFormatException(() => TextFormat.ParseInt32("-2147483649")); - AssertFormatException(() => TextFormat.ParseUInt32("4294967296")); - AssertFormatException(() => TextFormat.ParseUInt32("-1")); - AssertFormatException(() => TextFormat.ParseInt64("9223372036854775808")); - AssertFormatException(() => TextFormat.ParseInt64("-9223372036854775809")); - AssertFormatException(() => TextFormat.ParseUInt64("18446744073709551616")); - AssertFormatException(() => TextFormat.ParseUInt64("-1")); - AssertFormatException(() => TextFormat.ParseInt32("abcd")); - } - - [Test] - public void ParseLongString() { - string longText = - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890" + - "123456789012345678901234567890123456789012345678901234567890"; - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TextFormat.Merge("optional_string: \"" + longText + "\"", builder); - Assert.AreEqual(longText, builder.OptionalString); - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System;
+using System.IO;
+using System.Text;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+using System.Globalization;
+using System.Threading;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class TextFormatTest
+ {
+ private static readonly string AllFieldsSetText = TestUtil.ReadTextFromFile("text_format_unittest_data.txt");
+
+ private static readonly string AllExtensionsSetText =
+ TestUtil.ReadTextFromFile("text_format_unittest_extensions_data.txt");
+
+ /// <summary>
+ /// Note that this is slightly different to the Java - 123.0 becomes 123, and 1.23E17 becomes 1.23E+17.
+ /// Both of these differences can be parsed by the Java and the C++, and we can parse their output too.
+ /// </summary>
+ private const string ExoticText =
+ "repeated_int32: -1\n" +
+ "repeated_int32: -2147483648\n" +
+ "repeated_int64: -1\n" +
+ "repeated_int64: -9223372036854775808\n" +
+ "repeated_uint32: 4294967295\n" +
+ "repeated_uint32: 2147483648\n" +
+ "repeated_uint64: 18446744073709551615\n" +
+ "repeated_uint64: 9223372036854775808\n" +
+ "repeated_double: 123\n" +
+ "repeated_double: 123.5\n" +
+ "repeated_double: 0.125\n" +
+ "repeated_double: 1.23E+17\n" +
+ "repeated_double: 1.235E+22\n" +
+ "repeated_double: 1.235E-18\n" +
+ "repeated_double: 123.456789\n" +
+ "repeated_double: Infinity\n" +
+ "repeated_double: -Infinity\n" +
+ "repeated_double: NaN\n" +
+ "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"" +
+ "\\341\\210\\264\"\n" +
+ "repeated_bytes: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\376\"\n";
+
+ private const string MessageSetText =
+ "[protobuf_unittest.TestMessageSetExtension1] {\n" +
+ " i: 123\n" +
+ "}\n" +
+ "[protobuf_unittest.TestMessageSetExtension2] {\n" +
+ " str: \"foo\"\n" +
+ "}\n";
+
+ /// <summary>
+ /// Print TestAllTypes and compare with golden file.
+ /// </summary>
+ [Test]
+ public void PrintMessage()
+ {
+ TestUtil.TestInMultipleCultures(() =>
+ {
+ string text = TextFormat.PrintToString(TestUtil.GetAllSet());
+ Assert.AreEqual(AllFieldsSetText.Replace("\r\n", "\n"),
+ text.Replace("\r\n", "\n"));
+ });
+ }
+
+ /// <summary>
+ /// Print TestAllExtensions and compare with golden file.
+ /// </summary>
+ [Test]
+ public void PrintExtensions()
+ {
+ string text = TextFormat.PrintToString(TestUtil.GetAllExtensionsSet());
+
+ Assert.AreEqual(AllExtensionsSetText.Replace("\r\n", "\n"), text.Replace("\r\n", "\n"));
+ }
+
+ /// <summary>
+ /// Test printing of unknown fields in a message.
+ /// </summary>
+ [Test]
+ public void PrintUnknownFields()
+ {
+ TestEmptyMessage message =
+ TestEmptyMessage.CreateBuilder()
+ .SetUnknownFields(
+ UnknownFieldSet.CreateBuilder()
+ .AddField(5,
+ UnknownField.CreateBuilder()
+ .AddVarint(1)
+ .AddFixed32(2)
+ .AddFixed64(3)
+ .AddLengthDelimited(ByteString.CopyFromUtf8("4"))
+ .AddGroup(
+ UnknownFieldSet.CreateBuilder()
+ .AddField(10,
+ UnknownField.CreateBuilder()
+ .AddVarint(5)
+ .Build())
+ .Build())
+ .Build())
+ .AddField(8,
+ UnknownField.CreateBuilder()
+ .AddVarint(1)
+ .AddVarint(2)
+ .AddVarint(3)
+ .Build())
+ .AddField(15,
+ UnknownField.CreateBuilder()
+ .AddVarint(0xABCDEF1234567890L)
+ .AddFixed32(0xABCD1234)
+ .AddFixed64(0xABCDEF1234567890L)
+ .Build())
+ .Build())
+ .Build();
+
+ Assert.AreEqual(
+ "5: 1\n" +
+ "5: 0x00000002\n" +
+ "5: 0x0000000000000003\n" +
+ "5: \"4\"\n" +
+ "5 {\n" +
+ " 10: 5\n" +
+ "}\n" +
+ "8: 1\n" +
+ "8: 2\n" +
+ "8: 3\n" +
+ "15: 12379813812177893520\n" +
+ "15: 0xabcd1234\n" +
+ "15: 0xabcdef1234567890\n",
+ TextFormat.PrintToString(message));
+ }
+
+ /// <summary>
+ /// Helper to construct a ByteString from a string containing only 8-bit
+ /// characters. The characters are converted directly to bytes, *not*
+ /// encoded using UTF-8.
+ /// </summary>
+ private static ByteString Bytes(string str)
+ {
+ return ByteString.CopyFrom(Encoding.GetEncoding(28591).GetBytes(str));
+ }
+
+ [Test]
+ public void PrintExotic()
+ {
+ IMessage message = TestAllTypes.CreateBuilder()
+ // Signed vs. unsigned numbers.
+ .AddRepeatedInt32(-1)
+ .AddRepeatedUint32(uint.MaxValue)
+ .AddRepeatedInt64(-1)
+ .AddRepeatedUint64(ulong.MaxValue)
+ .AddRepeatedInt32(1 << 31)
+ .AddRepeatedUint32(1U << 31)
+ .AddRepeatedInt64(1L << 63)
+ .AddRepeatedUint64(1UL << 63)
+
+ // Floats of various precisions and exponents.
+ .AddRepeatedDouble(123)
+ .AddRepeatedDouble(123.5)
+ .AddRepeatedDouble(0.125)
+ .AddRepeatedDouble(123e15)
+ .AddRepeatedDouble(123.5e20)
+ .AddRepeatedDouble(123.5e-20)
+ .AddRepeatedDouble(123.456789)
+ .AddRepeatedDouble(Double.PositiveInfinity)
+ .AddRepeatedDouble(Double.NegativeInfinity)
+ .AddRepeatedDouble(Double.NaN)
+
+ // Strings and bytes that needing escaping.
+ .AddRepeatedString("\0\u0001\u0007\b\f\n\r\t\v\\\'\"\u1234")
+ .AddRepeatedBytes(Bytes("\0\u0001\u0007\b\f\n\r\t\v\\\'\"\u00fe"))
+ .Build();
+
+ Assert.AreEqual(ExoticText, message.ToString());
+ }
+
+ [Test]
+ public void PrintMessageSet()
+ {
+ TestMessageSet messageSet =
+ TestMessageSet.CreateBuilder()
+ .SetExtension(
+ TestMessageSetExtension1.MessageSetExtension,
+ TestMessageSetExtension1.CreateBuilder().SetI(123).Build())
+ .SetExtension(
+ TestMessageSetExtension2.MessageSetExtension,
+ TestMessageSetExtension2.CreateBuilder().SetStr("foo").Build())
+ .Build();
+
+ Assert.AreEqual(MessageSetText, messageSet.ToString());
+ }
+
+ // =================================================================
+
+ [Test]
+ public void Parse()
+ {
+ TestUtil.TestInMultipleCultures(() =>
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TextFormat.Merge(AllFieldsSetText, builder);
+ TestUtil.AssertAllFieldsSet(builder.Build());
+ });
+ }
+
+ [Test]
+ public void ParseReader()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TextFormat.Merge(new StringReader(AllFieldsSetText), builder);
+ TestUtil.AssertAllFieldsSet(builder.Build());
+ }
+
+ [Test]
+ public void ParseExtensions()
+ {
+ TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
+ TextFormat.Merge(AllExtensionsSetText,
+ TestUtil.CreateExtensionRegistry(),
+ builder);
+ TestUtil.AssertAllExtensionsSet(builder.Build());
+ }
+
+ [Test]
+ public void ParseCompatibility()
+ {
+ string original = "repeated_float: inf\n" +
+ "repeated_float: -inf\n" +
+ "repeated_float: nan\n" +
+ "repeated_float: inff\n" +
+ "repeated_float: -inff\n" +
+ "repeated_float: nanf\n" +
+ "repeated_float: 1.0f\n" +
+ "repeated_float: infinityf\n" +
+ "repeated_float: -Infinityf\n" +
+ "repeated_double: infinity\n" +
+ "repeated_double: -infinity\n" +
+ "repeated_double: nan\n";
+ string canonical = "repeated_float: Infinity\n" +
+ "repeated_float: -Infinity\n" +
+ "repeated_float: NaN\n" +
+ "repeated_float: Infinity\n" +
+ "repeated_float: -Infinity\n" +
+ "repeated_float: NaN\n" +
+ "repeated_float: 1\n" + // Java has 1.0; this is fine
+ "repeated_float: Infinity\n" +
+ "repeated_float: -Infinity\n" +
+ "repeated_double: Infinity\n" +
+ "repeated_double: -Infinity\n" +
+ "repeated_double: NaN\n";
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TextFormat.Merge(original, builder);
+ Assert.AreEqual(canonical, builder.Build().ToString());
+ }
+
+ [Test]
+ public void ParseExotic()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TextFormat.Merge(ExoticText, builder);
+
+ // Too lazy to check things individually. Don't try to debug this
+ // if testPrintExotic() is Assert.Failing.
+ Assert.AreEqual(ExoticText, builder.Build().ToString());
+ }
+
+ [Test]
+ public void ParseMessageSet()
+ {
+ ExtensionRegistry extensionRegistry = ExtensionRegistry.CreateInstance();
+ extensionRegistry.Add(TestMessageSetExtension1.MessageSetExtension);
+ extensionRegistry.Add(TestMessageSetExtension2.MessageSetExtension);
+
+ TestMessageSet.Builder builder = TestMessageSet.CreateBuilder();
+ TextFormat.Merge(MessageSetText, extensionRegistry, builder);
+ TestMessageSet messageSet = builder.Build();
+
+ Assert.IsTrue(messageSet.HasExtension(TestMessageSetExtension1.MessageSetExtension));
+ Assert.AreEqual(123, messageSet.GetExtension(TestMessageSetExtension1.MessageSetExtension).I);
+ Assert.IsTrue(messageSet.HasExtension(TestMessageSetExtension2.MessageSetExtension));
+ Assert.AreEqual("foo", messageSet.GetExtension(TestMessageSetExtension2.MessageSetExtension).Str);
+ }
+
+ [Test]
+ public void ParseNumericEnum()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TextFormat.Merge("optional_nested_enum: 2", builder);
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, builder.OptionalNestedEnum);
+ }
+
+ [Test]
+ public void ParseAngleBrackets()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TextFormat.Merge("OptionalGroup: < a: 1 >", builder);
+ Assert.IsTrue(builder.HasOptionalGroup);
+ Assert.AreEqual(1, builder.OptionalGroup.A);
+ }
+
+ [Test]
+ public void ParseComment()
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TextFormat.Merge(
+ "# this is a comment\n" +
+ "optional_int32: 1 # another comment\n" +
+ "optional_int64: 2\n" +
+ "# EOF comment", builder);
+ Assert.AreEqual(1, builder.OptionalInt32);
+ Assert.AreEqual(2, builder.OptionalInt64);
+ }
+
+
+ private static void AssertParseError(string error, string text)
+ {
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ try
+ {
+ TextFormat.Merge(text, TestUtil.CreateExtensionRegistry(), builder);
+ Assert.Fail("Expected parse exception.");
+ }
+ catch (FormatException e)
+ {
+ Assert.AreEqual(error, e.Message);
+ }
+ }
+
+ [Test]
+ public void ParseErrors()
+ {
+ AssertParseError(
+ "1:16: Expected \":\".",
+ "optional_int32 123");
+ AssertParseError(
+ "1:23: Expected identifier.",
+ "optional_nested_enum: ?");
+ AssertParseError(
+ "1:18: Couldn't parse integer: Number must be positive: -1",
+ "optional_uint32: -1");
+ AssertParseError(
+ "1:17: Couldn't parse integer: Number out of range for 32-bit signed " +
+ "integer: 82301481290849012385230157",
+ "optional_int32: 82301481290849012385230157");
+ AssertParseError(
+ "1:16: Expected \"true\" or \"false\".",
+ "optional_bool: maybe");
+ AssertParseError(
+ "1:18: Expected string.",
+ "optional_string: 123");
+ AssertParseError(
+ "1:18: String missing ending quote.",
+ "optional_string: \"ueoauaoe");
+ AssertParseError(
+ "1:18: String missing ending quote.",
+ "optional_string: \"ueoauaoe\n" +
+ "optional_int32: 123");
+ AssertParseError(
+ "1:18: Invalid escape sequence: '\\z'",
+ "optional_string: \"\\z\"");
+ AssertParseError(
+ "1:18: String missing ending quote.",
+ "optional_string: \"ueoauaoe\n" +
+ "optional_int32: 123");
+ AssertParseError(
+ "1:2: Extension \"nosuchext\" not found in the ExtensionRegistry.",
+ "[nosuchext]: 123");
+ AssertParseError(
+ "1:20: Extension \"protobuf_unittest.optional_int32_extension\" does " +
+ "not extend message type \"protobuf_unittest.TestAllTypes\".",
+ "[protobuf_unittest.optional_int32_extension]: 123");
+ AssertParseError(
+ "1:1: Message type \"protobuf_unittest.TestAllTypes\" has no field " +
+ "named \"nosuchfield\".",
+ "nosuchfield: 123");
+ AssertParseError(
+ "1:21: Expected \">\".",
+ "OptionalGroup < a: 1");
+ AssertParseError(
+ "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " +
+ "value named \"NO_SUCH_VALUE\".",
+ "optional_nested_enum: NO_SUCH_VALUE");
+ AssertParseError(
+ "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " +
+ "value with number 123.",
+ "optional_nested_enum: 123");
+
+ // Delimiters must match.
+ AssertParseError(
+ "1:22: Expected identifier.",
+ "OptionalGroup < a: 1 }");
+ AssertParseError(
+ "1:22: Expected identifier.",
+ "OptionalGroup { a: 1 >");
+ }
+
+ // =================================================================
+
+ private static ByteString Bytes(params byte[] bytes)
+ {
+ return ByteString.CopyFrom(bytes);
+ }
+
+ private delegate void FormattingAction();
+
+ private static void AssertFormatException(FormattingAction action)
+ {
+ try
+ {
+ action();
+ Assert.Fail("Should have thrown an exception.");
+ }
+ catch (FormatException)
+ {
+ // success
+ }
+ }
+
+ [Test]
+ public void Escape()
+ {
+ // Escape sequences.
+ Assert.AreEqual("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"",
+ TextFormat.EscapeBytes(Bytes("\0\u0001\u0007\b\f\n\r\t\v\\\'\"")));
+ Assert.AreEqual("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"",
+ TextFormat.EscapeText("\0\u0001\u0007\b\f\n\r\t\v\\\'\""));
+ Assert.AreEqual(Bytes("\0\u0001\u0007\b\f\n\r\t\v\\\'\""),
+ TextFormat.UnescapeBytes("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));
+ Assert.AreEqual("\0\u0001\u0007\b\f\n\r\t\v\\\'\"",
+ TextFormat.UnescapeText("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));
+
+ // Unicode handling.
+ Assert.AreEqual("\\341\\210\\264", TextFormat.EscapeText("\u1234"));
+ Assert.AreEqual("\\341\\210\\264", TextFormat.EscapeBytes(Bytes(0xe1, 0x88, 0xb4)));
+ Assert.AreEqual("\u1234", TextFormat.UnescapeText("\\341\\210\\264"));
+ Assert.AreEqual(Bytes(0xe1, 0x88, 0xb4), TextFormat.UnescapeBytes("\\341\\210\\264"));
+ Assert.AreEqual("\u1234", TextFormat.UnescapeText("\\xe1\\x88\\xb4"));
+ Assert.AreEqual(Bytes(0xe1, 0x88, 0xb4), TextFormat.UnescapeBytes("\\xe1\\x88\\xb4"));
+
+ // Errors.
+ AssertFormatException(() => TextFormat.UnescapeText("\\x"));
+ AssertFormatException(() => TextFormat.UnescapeText("\\z"));
+ AssertFormatException(() => TextFormat.UnescapeText("\\"));
+ }
+
+ [Test]
+ public void ParseInteger()
+ {
+ Assert.AreEqual(0, TextFormat.ParseInt32("0"));
+ Assert.AreEqual(1, TextFormat.ParseInt32("1"));
+ Assert.AreEqual(-1, TextFormat.ParseInt32("-1"));
+ Assert.AreEqual(12345, TextFormat.ParseInt32("12345"));
+ Assert.AreEqual(-12345, TextFormat.ParseInt32("-12345"));
+ Assert.AreEqual(2147483647, TextFormat.ParseInt32("2147483647"));
+ Assert.AreEqual(-2147483648, TextFormat.ParseInt32("-2147483648"));
+
+ Assert.AreEqual(0, TextFormat.ParseUInt32("0"));
+ Assert.AreEqual(1, TextFormat.ParseUInt32("1"));
+ Assert.AreEqual(12345, TextFormat.ParseUInt32("12345"));
+ Assert.AreEqual(2147483647, TextFormat.ParseUInt32("2147483647"));
+ Assert.AreEqual(2147483648U, TextFormat.ParseUInt32("2147483648"));
+ Assert.AreEqual(4294967295U, TextFormat.ParseUInt32("4294967295"));
+
+ Assert.AreEqual(0L, TextFormat.ParseInt64("0"));
+ Assert.AreEqual(1L, TextFormat.ParseInt64("1"));
+ Assert.AreEqual(-1L, TextFormat.ParseInt64("-1"));
+ Assert.AreEqual(12345L, TextFormat.ParseInt64("12345"));
+ Assert.AreEqual(-12345L, TextFormat.ParseInt64("-12345"));
+ Assert.AreEqual(2147483647L, TextFormat.ParseInt64("2147483647"));
+ Assert.AreEqual(-2147483648L, TextFormat.ParseInt64("-2147483648"));
+ Assert.AreEqual(4294967295L, TextFormat.ParseInt64("4294967295"));
+ Assert.AreEqual(4294967296L, TextFormat.ParseInt64("4294967296"));
+ Assert.AreEqual(9223372036854775807L, TextFormat.ParseInt64("9223372036854775807"));
+ Assert.AreEqual(-9223372036854775808L, TextFormat.ParseInt64("-9223372036854775808"));
+
+ Assert.AreEqual(0L, TextFormat.ParseUInt64("0"));
+ Assert.AreEqual(1L, TextFormat.ParseUInt64("1"));
+ Assert.AreEqual(12345L, TextFormat.ParseUInt64("12345"));
+ Assert.AreEqual(2147483647L, TextFormat.ParseUInt64("2147483647"));
+ Assert.AreEqual(4294967295L, TextFormat.ParseUInt64("4294967295"));
+ Assert.AreEqual(4294967296L, TextFormat.ParseUInt64("4294967296"));
+ Assert.AreEqual(9223372036854775807UL, TextFormat.ParseUInt64("9223372036854775807"));
+ Assert.AreEqual(9223372036854775808UL, TextFormat.ParseUInt64("9223372036854775808"));
+ Assert.AreEqual(18446744073709551615UL, TextFormat.ParseUInt64("18446744073709551615"));
+
+ // Hex
+ Assert.AreEqual(0x1234abcd, TextFormat.ParseInt32("0x1234abcd"));
+ Assert.AreEqual(-0x1234abcd, TextFormat.ParseInt32("-0x1234abcd"));
+ Assert.AreEqual(0xffffffffffffffffUL, TextFormat.ParseUInt64("0xffffffffffffffff"));
+ Assert.AreEqual(0x7fffffffffffffffL,
+ TextFormat.ParseInt64("0x7fffffffffffffff"));
+
+ // Octal
+ Assert.AreEqual(342391, TextFormat.ParseInt32("01234567"));
+
+ // Out-of-range
+ AssertFormatException(() => TextFormat.ParseInt32("2147483648"));
+ AssertFormatException(() => TextFormat.ParseInt32("-2147483649"));
+ AssertFormatException(() => TextFormat.ParseUInt32("4294967296"));
+ AssertFormatException(() => TextFormat.ParseUInt32("-1"));
+ AssertFormatException(() => TextFormat.ParseInt64("9223372036854775808"));
+ AssertFormatException(() => TextFormat.ParseInt64("-9223372036854775809"));
+ AssertFormatException(() => TextFormat.ParseUInt64("18446744073709551616"));
+ AssertFormatException(() => TextFormat.ParseUInt64("-1"));
+ AssertFormatException(() => TextFormat.ParseInt32("abcd"));
+ }
+
+ [Test]
+ public void ParseLongString()
+ {
+ string longText =
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890" +
+ "123456789012345678901234567890123456789012345678901234567890";
+ TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
+ TextFormat.Merge("optional_string: \"" + longText + "\"", builder);
+ Assert.AreEqual(longText, builder.OptionalString);
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/UnknownFieldSetTest.cs b/src/ProtocolBuffers.Test/UnknownFieldSetTest.cs index 08de7fbf..bd3d950a 100644 --- a/src/ProtocolBuffers.Test/UnknownFieldSetTest.cs +++ b/src/ProtocolBuffers.Test/UnknownFieldSetTest.cs @@ -1,400 +1,433 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Collections.Generic; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class UnknownFieldSetTest { - - private MessageDescriptor descriptor; - private TestAllTypes allFields; - private ByteString allFieldsData; - - /// <summary> - /// An empty message that has been parsed from allFieldsData. So, it has - /// unknown fields of every type. - /// </summary> - private TestEmptyMessage emptyMessage; - private UnknownFieldSet unknownFields; - - [SetUp] - public void SetUp() { - descriptor = TestAllTypes.Descriptor; - allFields = TestUtil.GetAllSet(); - allFieldsData = allFields.ToByteString(); - emptyMessage = TestEmptyMessage.ParseFrom(allFieldsData); - unknownFields = emptyMessage.UnknownFields; - } - - private UnknownField GetField(String name) { - FieldDescriptor field = descriptor.FindDescriptor<FieldDescriptor>(name); - Assert.IsNotNull(field); - return unknownFields.FieldDictionary[field.FieldNumber]; - } - - /// <summary> - /// Constructs a protocol buffer which contains fields with all the same - /// numbers as allFieldsData except that each field is some other wire - /// type. - /// </summary> - private ByteString GetBizarroData() { - UnknownFieldSet.Builder bizarroFields = UnknownFieldSet.CreateBuilder(); - - UnknownField varintField = UnknownField.CreateBuilder().AddVarint(1).Build(); - UnknownField fixed32Field = UnknownField.CreateBuilder().AddFixed32(1).Build(); - - foreach (KeyValuePair<int, UnknownField> entry in unknownFields.FieldDictionary) { - if (entry.Value.VarintList.Count == 0) { - // Original field is not a varint, so use a varint. - bizarroFields.AddField(entry.Key, varintField); - } else { - // Original field *is* a varint, so use something else. - bizarroFields.AddField(entry.Key, fixed32Field); - } - } - - return bizarroFields.Build().ToByteString(); - } - - // ================================================================= - - [Test] - public void Varint() { - UnknownField field = GetField("optional_int32"); - Assert.AreEqual(1, field.VarintList.Count); - Assert.AreEqual(allFields.OptionalInt32, (long) field.VarintList[0]); - } - - [Test] - public void Fixed32() { - UnknownField field = GetField("optional_fixed32"); - Assert.AreEqual(1, field.Fixed32List.Count); - Assert.AreEqual(allFields.OptionalFixed32, (int) field.Fixed32List[0]); - } - - [Test] - public void Fixed64() { - UnknownField field = GetField("optional_fixed64"); - Assert.AreEqual(1, field.Fixed64List.Count); - Assert.AreEqual(allFields.OptionalFixed64, (long) field.Fixed64List[0]); - } - - [Test] - public void LengthDelimited() { - UnknownField field = GetField("optional_bytes"); - Assert.AreEqual(1, field.LengthDelimitedList.Count); - Assert.AreEqual(allFields.OptionalBytes, field.LengthDelimitedList[0]); - } - - [Test] - public void Group() { - FieldDescriptor nestedFieldDescriptor = - TestAllTypes.Types.OptionalGroup.Descriptor.FindDescriptor<FieldDescriptor>("a"); - Assert.IsNotNull(nestedFieldDescriptor); - - UnknownField field = GetField("optionalgroup"); - Assert.AreEqual(1, field.GroupList.Count); - - UnknownFieldSet group = field.GroupList[0]; - Assert.AreEqual(1, group.FieldDictionary.Count); - Assert.IsTrue(group.HasField(nestedFieldDescriptor.FieldNumber)); - - UnknownField nestedField = group[nestedFieldDescriptor.FieldNumber]; - Assert.AreEqual(1, nestedField.VarintList.Count); - Assert.AreEqual(allFields.OptionalGroup.A, (long) nestedField.VarintList[0]); - } - - [Test] - public void Serialize() { - // Check that serializing the UnknownFieldSet produces the original data again. - ByteString data = emptyMessage.ToByteString(); - Assert.AreEqual(allFieldsData, data); - } - - [Test] - public void CopyFrom() { - TestEmptyMessage message = - TestEmptyMessage.CreateBuilder().MergeFrom(emptyMessage).Build(); - - Assert.AreEqual(emptyMessage.ToString(), message.ToString()); - } - - [Test] - public void MergeFrom() { - TestEmptyMessage source = - TestEmptyMessage.CreateBuilder() - .SetUnknownFields( - UnknownFieldSet.CreateBuilder() - .AddField(2, - UnknownField.CreateBuilder() - .AddVarint(2).Build()) - .AddField(3, - UnknownField.CreateBuilder() - .AddVarint(4).Build()) - .Build()) - .Build(); - TestEmptyMessage destination = - TestEmptyMessage.CreateBuilder() - .SetUnknownFields( - UnknownFieldSet.CreateBuilder() - .AddField(1, - UnknownField.CreateBuilder() - .AddVarint(1).Build()) - .AddField(3, - UnknownField.CreateBuilder() - .AddVarint(3).Build()) - .Build()) - .MergeFrom(source) - .Build(); - - Assert.AreEqual( - "1: 1\n" + - "2: 2\n" + - "3: 3\n" + - "3: 4\n", - destination.ToString()); - } - - [Test] - public void Clear() { - UnknownFieldSet fields = - UnknownFieldSet.CreateBuilder().MergeFrom(unknownFields).Clear().Build(); - Assert.AreEqual(0, fields.FieldDictionary.Count); - } - - [Test] - public void ClearMessage() { - TestEmptyMessage message = - TestEmptyMessage.CreateBuilder().MergeFrom(emptyMessage).Clear().Build(); - Assert.AreEqual(0, message.SerializedSize); - } - - [Test] - public void ParseKnownAndUnknown() { - // Test mixing known and unknown fields when parsing. - - UnknownFieldSet fields = - UnknownFieldSet.CreateBuilder(unknownFields) - .AddField(123456, - UnknownField.CreateBuilder().AddVarint(654321).Build()) - .Build(); - - ByteString data = fields.ToByteString(); - TestAllTypes destination = TestAllTypes.ParseFrom(data); - - TestUtil.AssertAllFieldsSet(destination); - Assert.AreEqual(1, destination.UnknownFields.FieldDictionary.Count); - - UnknownField field = destination.UnknownFields[123456]; - Assert.AreEqual(1, field.VarintList.Count); - Assert.AreEqual(654321, (long) field.VarintList[0]); - } - - [Test] - public void WrongTypeTreatedAsUnknown() { - // Test that fields of the wrong wire type are treated like unknown fields - // when parsing. - - ByteString bizarroData = GetBizarroData(); - TestAllTypes allTypesMessage = TestAllTypes.ParseFrom(bizarroData); - TestEmptyMessage emptyMessage = TestEmptyMessage.ParseFrom(bizarroData); - - // All fields should have been interpreted as unknown, so the debug strings - // should be the same. - Assert.AreEqual(emptyMessage.ToString(), allTypesMessage.ToString()); - } - - [Test] - public void UnknownExtensions() { - // Make sure fields are properly parsed to the UnknownFieldSet even when - // they are declared as extension numbers. - - TestEmptyMessageWithExtensions message = - TestEmptyMessageWithExtensions.ParseFrom(allFieldsData); - - Assert.AreEqual(unknownFields.FieldDictionary.Count, - message.UnknownFields.FieldDictionary.Count); - Assert.AreEqual(allFieldsData, message.ToByteString()); - } - - [Test] - public void WrongExtensionTypeTreatedAsUnknown() { - // Test that fields of the wrong wire type are treated like unknown fields - // when parsing extensions. - - ByteString bizarroData = GetBizarroData(); - TestAllExtensions allExtensionsMessage = TestAllExtensions.ParseFrom(bizarroData); - TestEmptyMessage emptyMessage = TestEmptyMessage.ParseFrom(bizarroData); - - // All fields should have been interpreted as unknown, so the debug strings - // should be the same. - Assert.AreEqual(emptyMessage.ToString(), - allExtensionsMessage.ToString()); - } - - [Test] - public void ParseUnknownEnumValue() { - FieldDescriptor singularField = TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("optional_nested_enum"); - FieldDescriptor repeatedField = TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_nested_enum"); - Assert.IsNotNull(singularField); - Assert.IsNotNull(repeatedField); - - ByteString data = - UnknownFieldSet.CreateBuilder() - .AddField(singularField.FieldNumber, - UnknownField.CreateBuilder() - .AddVarint((int) TestAllTypes.Types.NestedEnum.BAR) - .AddVarint(5) // not valid - .Build()) - .AddField(repeatedField.FieldNumber, - UnknownField.CreateBuilder() - .AddVarint((int) TestAllTypes.Types.NestedEnum.FOO) - .AddVarint(4) // not valid - .AddVarint((int) TestAllTypes.Types.NestedEnum.BAZ) - .AddVarint(6) // not valid - .Build()) - .Build() - .ToByteString(); - - { - TestAllTypes message = TestAllTypes.ParseFrom(data); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, - message.OptionalNestedEnum); - TestUtil.AssertEqual(new [] {TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.BAZ}, - message.RepeatedNestedEnumList); - TestUtil.AssertEqual(new[] {5UL}, message.UnknownFields[singularField.FieldNumber].VarintList); - TestUtil.AssertEqual(new[] {4UL, 6UL}, message.UnknownFields[repeatedField.FieldNumber].VarintList); - } - - { - TestAllExtensions message = - TestAllExtensions.ParseFrom(data, TestUtil.CreateExtensionRegistry()); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, - message.GetExtension(UnitTestProtoFile.OptionalNestedEnumExtension)); - TestUtil.AssertEqual(new[] { TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.BAZ }, - message.GetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension)); - TestUtil.AssertEqual(new[] { 5UL }, message.UnknownFields[singularField.FieldNumber].VarintList); - TestUtil.AssertEqual(new[] { 4UL, 6UL }, message.UnknownFields[repeatedField.FieldNumber].VarintList); - } - } - - [Test] - public void LargeVarint() { - ByteString data = - UnknownFieldSet.CreateBuilder() - .AddField(1, - UnknownField.CreateBuilder() - .AddVarint(0x7FFFFFFFFFFFFFFFL) - .Build()) - .Build() - .ToByteString(); - UnknownFieldSet parsed = UnknownFieldSet.ParseFrom(data); - UnknownField field = parsed[1]; - Assert.AreEqual(1, field.VarintList.Count); - Assert.AreEqual(0x7FFFFFFFFFFFFFFFUL, field.VarintList[0]); - } - - [Test] - public void EqualsAndHashCode() { - UnknownField fixed32Field = UnknownField.CreateBuilder().AddFixed32(1).Build(); - UnknownField fixed64Field = UnknownField.CreateBuilder().AddFixed64(1).Build(); - UnknownField varIntField = UnknownField.CreateBuilder().AddVarint(1).Build(); - UnknownField lengthDelimitedField = UnknownField.CreateBuilder().AddLengthDelimited(ByteString.Empty).Build(); - UnknownField groupField = UnknownField.CreateBuilder().AddGroup(unknownFields).Build(); - - UnknownFieldSet a = UnknownFieldSet.CreateBuilder().AddField(1, fixed32Field).Build(); - UnknownFieldSet b = UnknownFieldSet.CreateBuilder().AddField(1, fixed64Field).Build(); - UnknownFieldSet c = UnknownFieldSet.CreateBuilder().AddField(1, varIntField).Build(); - UnknownFieldSet d = UnknownFieldSet.CreateBuilder().AddField(1, lengthDelimitedField).Build(); - UnknownFieldSet e = UnknownFieldSet.CreateBuilder().AddField(1, groupField).Build(); - - CheckEqualsIsConsistent(a); - CheckEqualsIsConsistent(b); - CheckEqualsIsConsistent(c); - CheckEqualsIsConsistent(d); - CheckEqualsIsConsistent(e); - - CheckNotEqual(a, b); - CheckNotEqual(a, c); - CheckNotEqual(a, d); - CheckNotEqual(a, e); - CheckNotEqual(b, c); - CheckNotEqual(b, d); - CheckNotEqual(b, e); - CheckNotEqual(c, d); - CheckNotEqual(c, e); - CheckNotEqual(d, e); - } - - /// <summary> - /// Asserts that the given field sets are not equal and have different - /// hash codes. - /// </summary> - /// <remarks> - /// It's valid for non-equal objects to have the same hash code, so - /// this test is stricter than it needs to be. However, this should happen - /// relatively rarely. - /// </remarks> - /// <param name="s1"></param> - /// <param name="s2"></param> - private static void CheckNotEqual(UnknownFieldSet s1, UnknownFieldSet s2) { - String equalsError = string.Format("{0} should not be equal to {1}", s1, s2); - Assert.IsFalse(s1.Equals(s2), equalsError); - Assert.IsFalse(s2.Equals(s1), equalsError); - - Assert.IsFalse(s1.GetHashCode() == s2.GetHashCode(), - string.Format("{0} should have a different hash code from {1}", s1, s2)); - - } - - /** - * Asserts that the given field sets are equal and have identical hash codes. - */ - private static void CheckEqualsIsConsistent(UnknownFieldSet set) { - // Object should be equal to itself. - Assert.AreEqual(set, set); - - // Object should be equal to a copy of itself. - UnknownFieldSet copy = UnknownFieldSet.CreateBuilder(set).Build(); - Assert.AreEqual(set, copy); - Assert.AreEqual(copy, set); - Assert.AreEqual(set.GetHashCode(), copy.GetHashCode()); - } - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System;
+using System.Collections.Generic;
+using Google.ProtocolBuffers.Descriptors;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class UnknownFieldSetTest
+ {
+ private MessageDescriptor descriptor;
+ private TestAllTypes allFields;
+ private ByteString allFieldsData;
+
+ /// <summary>
+ /// An empty message that has been parsed from allFieldsData. So, it has
+ /// unknown fields of every type.
+ /// </summary>
+ private TestEmptyMessage emptyMessage;
+
+ private UnknownFieldSet unknownFields;
+
+ [SetUp]
+ public void SetUp()
+ {
+ descriptor = TestAllTypes.Descriptor;
+ allFields = TestUtil.GetAllSet();
+ allFieldsData = allFields.ToByteString();
+ emptyMessage = TestEmptyMessage.ParseFrom(allFieldsData);
+ unknownFields = emptyMessage.UnknownFields;
+ }
+
+ private UnknownField GetField(String name)
+ {
+ FieldDescriptor field = descriptor.FindDescriptor<FieldDescriptor>(name);
+ Assert.IsNotNull(field);
+ return unknownFields.FieldDictionary[field.FieldNumber];
+ }
+
+ /// <summary>
+ /// Constructs a protocol buffer which contains fields with all the same
+ /// numbers as allFieldsData except that each field is some other wire
+ /// type.
+ /// </summary>
+ private ByteString GetBizarroData()
+ {
+ UnknownFieldSet.Builder bizarroFields = UnknownFieldSet.CreateBuilder();
+
+ UnknownField varintField = UnknownField.CreateBuilder().AddVarint(1).Build();
+ UnknownField fixed32Field = UnknownField.CreateBuilder().AddFixed32(1).Build();
+
+ foreach (KeyValuePair<int, UnknownField> entry in unknownFields.FieldDictionary)
+ {
+ if (entry.Value.VarintList.Count == 0)
+ {
+ // Original field is not a varint, so use a varint.
+ bizarroFields.AddField(entry.Key, varintField);
+ }
+ else
+ {
+ // Original field *is* a varint, so use something else.
+ bizarroFields.AddField(entry.Key, fixed32Field);
+ }
+ }
+
+ return bizarroFields.Build().ToByteString();
+ }
+
+ // =================================================================
+
+ [Test]
+ public void Varint()
+ {
+ UnknownField field = GetField("optional_int32");
+ Assert.AreEqual(1, field.VarintList.Count);
+ Assert.AreEqual(allFields.OptionalInt32, (long) field.VarintList[0]);
+ }
+
+ [Test]
+ public void Fixed32()
+ {
+ UnknownField field = GetField("optional_fixed32");
+ Assert.AreEqual(1, field.Fixed32List.Count);
+ Assert.AreEqual(allFields.OptionalFixed32, (int) field.Fixed32List[0]);
+ }
+
+ [Test]
+ public void Fixed64()
+ {
+ UnknownField field = GetField("optional_fixed64");
+ Assert.AreEqual(1, field.Fixed64List.Count);
+ Assert.AreEqual(allFields.OptionalFixed64, (long) field.Fixed64List[0]);
+ }
+
+ [Test]
+ public void LengthDelimited()
+ {
+ UnknownField field = GetField("optional_bytes");
+ Assert.AreEqual(1, field.LengthDelimitedList.Count);
+ Assert.AreEqual(allFields.OptionalBytes, field.LengthDelimitedList[0]);
+ }
+
+ [Test]
+ public void Group()
+ {
+ FieldDescriptor nestedFieldDescriptor =
+ TestAllTypes.Types.OptionalGroup.Descriptor.FindDescriptor<FieldDescriptor>("a");
+ Assert.IsNotNull(nestedFieldDescriptor);
+
+ UnknownField field = GetField("optionalgroup");
+ Assert.AreEqual(1, field.GroupList.Count);
+
+ UnknownFieldSet group = field.GroupList[0];
+ Assert.AreEqual(1, group.FieldDictionary.Count);
+ Assert.IsTrue(group.HasField(nestedFieldDescriptor.FieldNumber));
+
+ UnknownField nestedField = group[nestedFieldDescriptor.FieldNumber];
+ Assert.AreEqual(1, nestedField.VarintList.Count);
+ Assert.AreEqual(allFields.OptionalGroup.A, (long) nestedField.VarintList[0]);
+ }
+
+ [Test]
+ public void Serialize()
+ {
+ // Check that serializing the UnknownFieldSet produces the original data again.
+ ByteString data = emptyMessage.ToByteString();
+ Assert.AreEqual(allFieldsData, data);
+ }
+
+ [Test]
+ public void CopyFrom()
+ {
+ TestEmptyMessage message =
+ TestEmptyMessage.CreateBuilder().MergeFrom(emptyMessage).Build();
+
+ Assert.AreEqual(emptyMessage.ToString(), message.ToString());
+ }
+
+ [Test]
+ public void MergeFrom()
+ {
+ TestEmptyMessage source =
+ TestEmptyMessage.CreateBuilder()
+ .SetUnknownFields(
+ UnknownFieldSet.CreateBuilder()
+ .AddField(2,
+ UnknownField.CreateBuilder()
+ .AddVarint(2).Build())
+ .AddField(3,
+ UnknownField.CreateBuilder()
+ .AddVarint(4).Build())
+ .Build())
+ .Build();
+ TestEmptyMessage destination =
+ TestEmptyMessage.CreateBuilder()
+ .SetUnknownFields(
+ UnknownFieldSet.CreateBuilder()
+ .AddField(1,
+ UnknownField.CreateBuilder()
+ .AddVarint(1).Build())
+ .AddField(3,
+ UnknownField.CreateBuilder()
+ .AddVarint(3).Build())
+ .Build())
+ .MergeFrom(source)
+ .Build();
+
+ Assert.AreEqual(
+ "1: 1\n" +
+ "2: 2\n" +
+ "3: 3\n" +
+ "3: 4\n",
+ destination.ToString());
+ }
+
+ [Test]
+ public void Clear()
+ {
+ UnknownFieldSet fields =
+ UnknownFieldSet.CreateBuilder().MergeFrom(unknownFields).Clear().Build();
+ Assert.AreEqual(0, fields.FieldDictionary.Count);
+ }
+
+ [Test]
+ public void ClearMessage()
+ {
+ TestEmptyMessage message =
+ TestEmptyMessage.CreateBuilder().MergeFrom(emptyMessage).Clear().Build();
+ Assert.AreEqual(0, message.SerializedSize);
+ }
+
+ [Test]
+ public void ParseKnownAndUnknown()
+ {
+ // Test mixing known and unknown fields when parsing.
+
+ UnknownFieldSet fields =
+ UnknownFieldSet.CreateBuilder(unknownFields)
+ .AddField(123456,
+ UnknownField.CreateBuilder().AddVarint(654321).Build())
+ .Build();
+
+ ByteString data = fields.ToByteString();
+ TestAllTypes destination = TestAllTypes.ParseFrom(data);
+
+ TestUtil.AssertAllFieldsSet(destination);
+ Assert.AreEqual(1, destination.UnknownFields.FieldDictionary.Count);
+
+ UnknownField field = destination.UnknownFields[123456];
+ Assert.AreEqual(1, field.VarintList.Count);
+ Assert.AreEqual(654321, (long) field.VarintList[0]);
+ }
+
+ [Test]
+ public void WrongTypeTreatedAsUnknown()
+ {
+ // Test that fields of the wrong wire type are treated like unknown fields
+ // when parsing.
+
+ ByteString bizarroData = GetBizarroData();
+ TestAllTypes allTypesMessage = TestAllTypes.ParseFrom(bizarroData);
+ TestEmptyMessage emptyMessage = TestEmptyMessage.ParseFrom(bizarroData);
+
+ // All fields should have been interpreted as unknown, so the debug strings
+ // should be the same.
+ Assert.AreEqual(emptyMessage.ToString(), allTypesMessage.ToString());
+ }
+
+ [Test]
+ public void UnknownExtensions()
+ {
+ // Make sure fields are properly parsed to the UnknownFieldSet even when
+ // they are declared as extension numbers.
+
+ TestEmptyMessageWithExtensions message =
+ TestEmptyMessageWithExtensions.ParseFrom(allFieldsData);
+
+ Assert.AreEqual(unknownFields.FieldDictionary.Count,
+ message.UnknownFields.FieldDictionary.Count);
+ Assert.AreEqual(allFieldsData, message.ToByteString());
+ }
+
+ [Test]
+ public void WrongExtensionTypeTreatedAsUnknown()
+ {
+ // Test that fields of the wrong wire type are treated like unknown fields
+ // when parsing extensions.
+
+ ByteString bizarroData = GetBizarroData();
+ TestAllExtensions allExtensionsMessage = TestAllExtensions.ParseFrom(bizarroData);
+ TestEmptyMessage emptyMessage = TestEmptyMessage.ParseFrom(bizarroData);
+
+ // All fields should have been interpreted as unknown, so the debug strings
+ // should be the same.
+ Assert.AreEqual(emptyMessage.ToString(),
+ allExtensionsMessage.ToString());
+ }
+
+ [Test]
+ public void ParseUnknownEnumValue()
+ {
+ FieldDescriptor singularField =
+ TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("optional_nested_enum");
+ FieldDescriptor repeatedField =
+ TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_nested_enum");
+ Assert.IsNotNull(singularField);
+ Assert.IsNotNull(repeatedField);
+
+ ByteString data =
+ UnknownFieldSet.CreateBuilder()
+ .AddField(singularField.FieldNumber,
+ UnknownField.CreateBuilder()
+ .AddVarint((int) TestAllTypes.Types.NestedEnum.BAR)
+ .AddVarint(5) // not valid
+ .Build())
+ .AddField(repeatedField.FieldNumber,
+ UnknownField.CreateBuilder()
+ .AddVarint((int) TestAllTypes.Types.NestedEnum.FOO)
+ .AddVarint(4) // not valid
+ .AddVarint((int) TestAllTypes.Types.NestedEnum.BAZ)
+ .AddVarint(6) // not valid
+ .Build())
+ .Build()
+ .ToByteString();
+
+ {
+ TestAllTypes message = TestAllTypes.ParseFrom(data);
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR,
+ message.OptionalNestedEnum);
+ TestUtil.AssertEqual(new[] {TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.BAZ},
+ message.RepeatedNestedEnumList);
+ TestUtil.AssertEqual(new[] {5UL}, message.UnknownFields[singularField.FieldNumber].VarintList);
+ TestUtil.AssertEqual(new[] {4UL, 6UL}, message.UnknownFields[repeatedField.FieldNumber].VarintList);
+ }
+
+ {
+ TestAllExtensions message =
+ TestAllExtensions.ParseFrom(data, TestUtil.CreateExtensionRegistry());
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR,
+ message.GetExtension(UnitTestProtoFile.OptionalNestedEnumExtension));
+ TestUtil.AssertEqual(new[] {TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.BAZ},
+ message.GetExtension(UnitTestProtoFile.RepeatedNestedEnumExtension));
+ TestUtil.AssertEqual(new[] {5UL}, message.UnknownFields[singularField.FieldNumber].VarintList);
+ TestUtil.AssertEqual(new[] {4UL, 6UL}, message.UnknownFields[repeatedField.FieldNumber].VarintList);
+ }
+ }
+
+ [Test]
+ public void LargeVarint()
+ {
+ ByteString data =
+ UnknownFieldSet.CreateBuilder()
+ .AddField(1,
+ UnknownField.CreateBuilder()
+ .AddVarint(0x7FFFFFFFFFFFFFFFL)
+ .Build())
+ .Build()
+ .ToByteString();
+ UnknownFieldSet parsed = UnknownFieldSet.ParseFrom(data);
+ UnknownField field = parsed[1];
+ Assert.AreEqual(1, field.VarintList.Count);
+ Assert.AreEqual(0x7FFFFFFFFFFFFFFFUL, field.VarintList[0]);
+ }
+
+ [Test]
+ public void EqualsAndHashCode()
+ {
+ UnknownField fixed32Field = UnknownField.CreateBuilder().AddFixed32(1).Build();
+ UnknownField fixed64Field = UnknownField.CreateBuilder().AddFixed64(1).Build();
+ UnknownField varIntField = UnknownField.CreateBuilder().AddVarint(1).Build();
+ UnknownField lengthDelimitedField =
+ UnknownField.CreateBuilder().AddLengthDelimited(ByteString.Empty).Build();
+ UnknownField groupField = UnknownField.CreateBuilder().AddGroup(unknownFields).Build();
+
+ UnknownFieldSet a = UnknownFieldSet.CreateBuilder().AddField(1, fixed32Field).Build();
+ UnknownFieldSet b = UnknownFieldSet.CreateBuilder().AddField(1, fixed64Field).Build();
+ UnknownFieldSet c = UnknownFieldSet.CreateBuilder().AddField(1, varIntField).Build();
+ UnknownFieldSet d = UnknownFieldSet.CreateBuilder().AddField(1, lengthDelimitedField).Build();
+ UnknownFieldSet e = UnknownFieldSet.CreateBuilder().AddField(1, groupField).Build();
+
+ CheckEqualsIsConsistent(a);
+ CheckEqualsIsConsistent(b);
+ CheckEqualsIsConsistent(c);
+ CheckEqualsIsConsistent(d);
+ CheckEqualsIsConsistent(e);
+
+ CheckNotEqual(a, b);
+ CheckNotEqual(a, c);
+ CheckNotEqual(a, d);
+ CheckNotEqual(a, e);
+ CheckNotEqual(b, c);
+ CheckNotEqual(b, d);
+ CheckNotEqual(b, e);
+ CheckNotEqual(c, d);
+ CheckNotEqual(c, e);
+ CheckNotEqual(d, e);
+ }
+
+ /// <summary>
+ /// Asserts that the given field sets are not equal and have different
+ /// hash codes.
+ /// </summary>
+ /// <remarks>
+ /// It's valid for non-equal objects to have the same hash code, so
+ /// this test is stricter than it needs to be. However, this should happen
+ /// relatively rarely.
+ /// </remarks>
+ /// <param name="s1"></param>
+ /// <param name="s2"></param>
+ private static void CheckNotEqual(UnknownFieldSet s1, UnknownFieldSet s2)
+ {
+ String equalsError = string.Format("{0} should not be equal to {1}", s1, s2);
+ Assert.IsFalse(s1.Equals(s2), equalsError);
+ Assert.IsFalse(s2.Equals(s1), equalsError);
+
+ Assert.IsFalse(s1.GetHashCode() == s2.GetHashCode(),
+ string.Format("{0} should have a different hash code from {1}", s1, s2));
+ }
+
+ /**
+ * Asserts that the given field sets are equal and have identical hash codes.
+ */
+
+ private static void CheckEqualsIsConsistent(UnknownFieldSet set)
+ {
+ // Object should be equal to itself.
+ Assert.AreEqual(set, set);
+
+ // Object should be equal to a copy of itself.
+ UnknownFieldSet copy = UnknownFieldSet.CreateBuilder(set).Build();
+ Assert.AreEqual(set, copy);
+ Assert.AreEqual(copy, set);
+ Assert.AreEqual(set.GetHashCode(), copy.GetHashCode());
+ }
+ }
+}
\ No newline at end of file diff --git a/src/ProtocolBuffers.Test/WireFormatTest.cs b/src/ProtocolBuffers.Test/WireFormatTest.cs index e61f4cca..f7ad864e 100644 --- a/src/ProtocolBuffers.Test/WireFormatTest.cs +++ b/src/ProtocolBuffers.Test/WireFormatTest.cs @@ -1,297 +1,316 @@ -#region Copyright notice and license -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System.IO; -using System.Reflection; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers { - [TestFixture] - public class WireFormatTest { - - /// <summary> - /// Keeps the attributes on FieldType and the switch statement in WireFormat in sync. - /// </summary> - [Test] - public void FieldTypeToWireTypeMapping() { - foreach (FieldInfo field in typeof(FieldType).GetFields(BindingFlags.Static | BindingFlags.Public)) { - FieldType fieldType = (FieldType)field.GetValue(null); - FieldMappingAttribute mapping = (FieldMappingAttribute)field.GetCustomAttributes(typeof(FieldMappingAttribute), false)[0]; - Assert.AreEqual(mapping.WireType, WireFormat.GetWireType(fieldType)); - } - } - - [Test] - public void Serialization() { - TestAllTypes message = TestUtil.GetAllSet(); - - ByteString rawBytes = message.ToByteString(); - Assert.AreEqual(rawBytes.Length, message.SerializedSize); - - TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes); - - TestUtil.AssertAllFieldsSet(message2); - } - - [Test] - public void SerializationPacked() { - TestPackedTypes message = TestUtil.GetPackedSet(); - ByteString rawBytes = message.ToByteString(); - Assert.AreEqual(rawBytes.Length, message.SerializedSize); - TestPackedTypes message2 = TestPackedTypes.ParseFrom(rawBytes); - TestUtil.AssertPackedFieldsSet(message2); - } - - [Test] - public void SerializeExtensions() { - // TestAllTypes and TestAllExtensions should have compatible wire formats, - // so if we serialize a TestAllExtensions then parse it as TestAllTypes - // it should work. - TestAllExtensions message = TestUtil.GetAllExtensionsSet(); - ByteString rawBytes = message.ToByteString(); - Assert.AreEqual(rawBytes.Length, message.SerializedSize); - - TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes); - - TestUtil.AssertAllFieldsSet(message2); - } - - [Test] - public void SerializePackedExtensions() { - // TestPackedTypes and TestPackedExtensions should have compatible wire - // formats; check that they serialize to the same string. - TestPackedExtensions message = TestUtil.GetPackedExtensionsSet(); - ByteString rawBytes = message.ToByteString(); - - TestPackedTypes message2 = TestUtil.GetPackedSet(); - ByteString rawBytes2 = message2.ToByteString(); - - Assert.AreEqual(rawBytes, rawBytes2); - } - - [Test] - public void SerializeDelimited() { - MemoryStream stream = new MemoryStream(); - TestUtil.GetAllSet().WriteDelimitedTo(stream); - stream.WriteByte(12); - TestUtil.GetPackedSet().WriteDelimitedTo(stream); - stream.WriteByte(34); - - stream.Position = 0; - - TestUtil.AssertAllFieldsSet(TestAllTypes.ParseDelimitedFrom(stream)); - Assert.AreEqual(12, stream.ReadByte()); - TestUtil.AssertPackedFieldsSet(TestPackedTypes.ParseDelimitedFrom(stream)); - Assert.AreEqual(34, stream.ReadByte()); - Assert.AreEqual(-1, stream.ReadByte()); - } - - [Test] - public void ParseExtensions() { - // TestAllTypes and TestAllExtensions should have compatible wire formats, - // so if we serealize a TestAllTypes then parse it as TestAllExtensions - // it should work. - - TestAllTypes message = TestUtil.GetAllSet(); - ByteString rawBytes = message.ToByteString(); - - ExtensionRegistry registry = ExtensionRegistry.CreateInstance(); - TestUtil.RegisterAllExtensions(registry); - registry = registry.AsReadOnly(); - - TestAllExtensions message2 = TestAllExtensions.ParseFrom(rawBytes, registry); - - TestUtil.AssertAllExtensionsSet(message2); - } - - [Test] - public void ParsePackedExtensions() { - // Ensure that packed extensions can be properly parsed. - TestPackedExtensions message = TestUtil.GetPackedExtensionsSet(); - ByteString rawBytes = message.ToByteString(); - - ExtensionRegistry registry = TestUtil.CreateExtensionRegistry(); - - TestPackedExtensions message2 = TestPackedExtensions.ParseFrom(rawBytes, registry); - TestUtil.AssertPackedExtensionsSet(message2); - } - - [Test] - public void ExtensionsSerializedSize() { - Assert.AreEqual(TestUtil.GetAllSet().SerializedSize, TestUtil.GetAllExtensionsSet().SerializedSize); - } - - private static void AssertFieldsInOrder(ByteString data) { - CodedInputStream input = data.CreateCodedInput(); - uint previousTag = 0; - - while (true) { - uint tag = input.ReadTag(); - if (tag == 0) { - break; - } - - Assert.IsTrue(tag > previousTag); - previousTag = tag; - input.SkipField(tag); - } - } - - [Test] - public void InterleavedFieldsAndExtensions() { - // Tests that fields are written in order even when extension ranges - // are interleaved with field numbers. - ByteString data = - TestFieldOrderings.CreateBuilder() - .SetMyInt(1) - .SetMyString("foo") - .SetMyFloat(1.0F) - .SetExtension(UnitTestProtoFile.MyExtensionInt, 23) - .SetExtension(UnitTestProtoFile.MyExtensionString, "bar") - .Build().ToByteString(); - AssertFieldsInOrder(data); - - MessageDescriptor descriptor = TestFieldOrderings.Descriptor; - ByteString dynamic_data = - DynamicMessage.CreateBuilder(TestFieldOrderings.Descriptor) - .SetField(descriptor.FindDescriptor<FieldDescriptor>("my_int"), 1L) - .SetField(descriptor.FindDescriptor<FieldDescriptor>("my_string"), "foo") - .SetField(descriptor.FindDescriptor<FieldDescriptor>("my_float"), 1.0F) - .SetField(UnitTestProtoFile.MyExtensionInt.Descriptor, 23) - .SetField(UnitTestProtoFile.MyExtensionString.Descriptor, "bar") - .WeakBuild().ToByteString(); - AssertFieldsInOrder(dynamic_data); - } - - private const int UnknownTypeId = 1550055; - private static readonly int TypeId1 = TestMessageSetExtension1.Descriptor.Extensions[0].FieldNumber; - private static readonly int TypeId2 = TestMessageSetExtension2.Descriptor.Extensions[0].FieldNumber; - - [Test] - public void SerializeMessageSet() { - // Set up a TestMessageSet with two known messages and an unknown one. - TestMessageSet messageSet = - TestMessageSet.CreateBuilder() - .SetExtension( - TestMessageSetExtension1.MessageSetExtension, - TestMessageSetExtension1.CreateBuilder().SetI(123).Build()) - .SetExtension( - TestMessageSetExtension2.MessageSetExtension, - TestMessageSetExtension2.CreateBuilder().SetStr("foo").Build()) - .SetUnknownFields( - UnknownFieldSet.CreateBuilder() - .AddField(UnknownTypeId, - UnknownField.CreateBuilder() - .AddLengthDelimited(ByteString.CopyFromUtf8("bar")) - .Build()) - .Build()) - .Build(); - - ByteString data = messageSet.ToByteString(); - - // Parse back using RawMessageSet and check the contents. - RawMessageSet raw = RawMessageSet.ParseFrom(data); - - Assert.AreEqual(0, raw.UnknownFields.FieldDictionary.Count); - - Assert.AreEqual(3, raw.ItemCount); - Assert.AreEqual(TypeId1, raw.ItemList[0].TypeId); - Assert.AreEqual(TypeId2, raw.ItemList[1].TypeId); - Assert.AreEqual(UnknownTypeId, raw.ItemList[2].TypeId); - - TestMessageSetExtension1 message1 = TestMessageSetExtension1.ParseFrom(raw.GetItem(0).Message.ToByteArray()); - Assert.AreEqual(123, message1.I); - - TestMessageSetExtension2 message2 = TestMessageSetExtension2.ParseFrom(raw.GetItem(1).Message.ToByteArray()); - Assert.AreEqual("foo", message2.Str); - - Assert.AreEqual("bar", raw.GetItem(2).Message.ToStringUtf8()); - } - - [Test] - public void ParseMessageSet() { - ExtensionRegistry extensionRegistry = ExtensionRegistry.CreateInstance(); - extensionRegistry.Add(TestMessageSetExtension1.MessageSetExtension); - extensionRegistry.Add(TestMessageSetExtension2.MessageSetExtension); - - // Set up a RawMessageSet with two known messages and an unknown one. - RawMessageSet raw = - RawMessageSet.CreateBuilder() - .AddItem( - RawMessageSet.Types.Item.CreateBuilder() - .SetTypeId(TypeId1) - .SetMessage( - TestMessageSetExtension1.CreateBuilder() - .SetI(123) - .Build().ToByteString()) - .Build()) - .AddItem( - RawMessageSet.Types.Item.CreateBuilder() - .SetTypeId(TypeId2) - .SetMessage( - TestMessageSetExtension2.CreateBuilder() - .SetStr("foo") - .Build().ToByteString()) - .Build()) - .AddItem( - RawMessageSet.Types.Item.CreateBuilder() - .SetTypeId(UnknownTypeId) - .SetMessage(ByteString.CopyFromUtf8("bar")) - .Build()) - .Build(); - - ByteString data = raw.ToByteString(); - - // Parse as a TestMessageSet and check the contents. - TestMessageSet messageSet = - TestMessageSet.ParseFrom(data, extensionRegistry); - - Assert.AreEqual(123, messageSet.GetExtension(TestMessageSetExtension1.MessageSetExtension).I); - Assert.AreEqual("foo", messageSet.GetExtension(TestMessageSetExtension2.MessageSetExtension).Str); - - // Check for unknown field with type LENGTH_DELIMITED, - // number UNKNOWN_TYPE_ID, and contents "bar". - UnknownFieldSet unknownFields = messageSet.UnknownFields; - Assert.AreEqual(1, unknownFields.FieldDictionary.Count); - Assert.IsTrue(unknownFields.HasField(UnknownTypeId)); - - UnknownField field = unknownFields[UnknownTypeId]; - Assert.AreEqual(1, field.LengthDelimitedList.Count); - Assert.AreEqual("bar", field.LengthDelimitedList[0].ToStringUtf8()); - } - - } -} +#region Copyright notice and license
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// http://github.com/jskeet/dotnet-protobufs/
+// Original C++/Java/Python code:
+// http://code.google.com/p/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#endregion
+
+using System.IO;
+using System.Reflection;
+using Google.ProtocolBuffers.Descriptors;
+using Google.ProtocolBuffers.TestProtos;
+using NUnit.Framework;
+
+namespace Google.ProtocolBuffers
+{
+ [TestFixture]
+ public class WireFormatTest
+ {
+ /// <summary>
+ /// Keeps the attributes on FieldType and the switch statement in WireFormat in sync.
+ /// </summary>
+ [Test]
+ public void FieldTypeToWireTypeMapping()
+ {
+ foreach (FieldInfo field in typeof (FieldType).GetFields(BindingFlags.Static | BindingFlags.Public))
+ {
+ FieldType fieldType = (FieldType) field.GetValue(null);
+ FieldMappingAttribute mapping =
+ (FieldMappingAttribute) field.GetCustomAttributes(typeof (FieldMappingAttribute), false)[0];
+ Assert.AreEqual(mapping.WireType, WireFormat.GetWireType(fieldType));
+ }
+ }
+
+ [Test]
+ public void Serialization()
+ {
+ TestAllTypes message = TestUtil.GetAllSet();
+
+ ByteString rawBytes = message.ToByteString();
+ Assert.AreEqual(rawBytes.Length, message.SerializedSize);
+
+ TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
+
+ TestUtil.AssertAllFieldsSet(message2);
+ }
+
+ [Test]
+ public void SerializationPacked()
+ {
+ TestPackedTypes message = TestUtil.GetPackedSet();
+ ByteString rawBytes = message.ToByteString();
+ Assert.AreEqual(rawBytes.Length, message.SerializedSize);
+ TestPackedTypes message2 = TestPackedTypes.ParseFrom(rawBytes);
+ TestUtil.AssertPackedFieldsSet(message2);
+ }
+
+ [Test]
+ public void SerializeExtensions()
+ {
+ // TestAllTypes and TestAllExtensions should have compatible wire formats,
+ // so if we serialize a TestAllExtensions then parse it as TestAllTypes
+ // it should work.
+ TestAllExtensions message = TestUtil.GetAllExtensionsSet();
+ ByteString rawBytes = message.ToByteString();
+ Assert.AreEqual(rawBytes.Length, message.SerializedSize);
+
+ TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
+
+ TestUtil.AssertAllFieldsSet(message2);
+ }
+
+ [Test]
+ public void SerializePackedExtensions()
+ {
+ // TestPackedTypes and TestPackedExtensions should have compatible wire
+ // formats; check that they serialize to the same string.
+ TestPackedExtensions message = TestUtil.GetPackedExtensionsSet();
+ ByteString rawBytes = message.ToByteString();
+
+ TestPackedTypes message2 = TestUtil.GetPackedSet();
+ ByteString rawBytes2 = message2.ToByteString();
+
+ Assert.AreEqual(rawBytes, rawBytes2);
+ }
+
+ [Test]
+ public void SerializeDelimited()
+ {
+ MemoryStream stream = new MemoryStream();
+ TestUtil.GetAllSet().WriteDelimitedTo(stream);
+ stream.WriteByte(12);
+ TestUtil.GetPackedSet().WriteDelimitedTo(stream);
+ stream.WriteByte(34);
+
+ stream.Position = 0;
+
+ TestUtil.AssertAllFieldsSet(TestAllTypes.ParseDelimitedFrom(stream));
+ Assert.AreEqual(12, stream.ReadByte());
+ TestUtil.AssertPackedFieldsSet(TestPackedTypes.ParseDelimitedFrom(stream));
+ Assert.AreEqual(34, stream.ReadByte());
+ Assert.AreEqual(-1, stream.ReadByte());
+ }
+
+ [Test]
+ public void ParseExtensions()
+ {
+ // TestAllTypes and TestAllExtensions should have compatible wire formats,
+ // so if we serealize a TestAllTypes then parse it as TestAllExtensions
+ // it should work.
+
+ TestAllTypes message = TestUtil.GetAllSet();
+ ByteString rawBytes = message.ToByteString();
+
+ ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
+ TestUtil.RegisterAllExtensions(registry);
+ registry = registry.AsReadOnly();
+
+ TestAllExtensions message2 = TestAllExtensions.ParseFrom(rawBytes, registry);
+
+ TestUtil.AssertAllExtensionsSet(message2);
+ }
+
+ [Test]
+ public void ParsePackedExtensions()
+ {
+ // Ensure that packed extensions can be properly parsed.
+ TestPackedExtensions message = TestUtil.GetPackedExtensionsSet();
+ ByteString rawBytes = message.ToByteString();
+
+ ExtensionRegistry registry = TestUtil.CreateExtensionRegistry();
+
+ TestPackedExtensions message2 = TestPackedExtensions.ParseFrom(rawBytes, registry);
+ TestUtil.AssertPackedExtensionsSet(message2);
+ }
+
+ [Test]
+ public void ExtensionsSerializedSize()
+ {
+ Assert.AreEqual(TestUtil.GetAllSet().SerializedSize, TestUtil.GetAllExtensionsSet().SerializedSize);
+ }
+
+ private static void AssertFieldsInOrder(ByteString data)
+ {
+ CodedInputStream input = data.CreateCodedInput();
+ uint previousTag = 0;
+
+ while (true)
+ {
+ uint tag = input.ReadTag();
+ if (tag == 0)
+ {
+ break;
+ }
+
+ Assert.IsTrue(tag > previousTag);
+ previousTag = tag;
+ input.SkipField(tag);
+ }
+ }
+
+ [Test]
+ public void InterleavedFieldsAndExtensions()
+ {
+ // Tests that fields are written in order even when extension ranges
+ // are interleaved with field numbers.
+ ByteString data =
+ TestFieldOrderings.CreateBuilder()
+ .SetMyInt(1)
+ .SetMyString("foo")
+ .SetMyFloat(1.0F)
+ .SetExtension(UnitTestProtoFile.MyExtensionInt, 23)
+ .SetExtension(UnitTestProtoFile.MyExtensionString, "bar")
+ .Build().ToByteString();
+ AssertFieldsInOrder(data);
+
+ MessageDescriptor descriptor = TestFieldOrderings.Descriptor;
+ ByteString dynamic_data =
+ DynamicMessage.CreateBuilder(TestFieldOrderings.Descriptor)
+ .SetField(descriptor.FindDescriptor<FieldDescriptor>("my_int"), 1L)
+ .SetField(descriptor.FindDescriptor<FieldDescriptor>("my_string"), "foo")
+ .SetField(descriptor.FindDescriptor<FieldDescriptor>("my_float"), 1.0F)
+ .SetField(UnitTestProtoFile.MyExtensionInt.Descriptor, 23)
+ .SetField(UnitTestProtoFile.MyExtensionString.Descriptor, "bar")
+ .WeakBuild().ToByteString();
+ AssertFieldsInOrder(dynamic_data);
+ }
+
+ private const int UnknownTypeId = 1550055;
+ private static readonly int TypeId1 = TestMessageSetExtension1.Descriptor.Extensions[0].FieldNumber;
+ private static readonly int TypeId2 = TestMessageSetExtension2.Descriptor.Extensions[0].FieldNumber;
+
+ [Test]
+ public void SerializeMessageSet()
+ {
+ // Set up a TestMessageSet with two known messages and an unknown one.
+ TestMessageSet messageSet =
+ TestMessageSet.CreateBuilder()
+ .SetExtension(
+ TestMessageSetExtension1.MessageSetExtension,
+ TestMessageSetExtension1.CreateBuilder().SetI(123).Build())
+ .SetExtension(
+ TestMessageSetExtension2.MessageSetExtension,
+ TestMessageSetExtension2.CreateBuilder().SetStr("foo").Build())
+ .SetUnknownFields(
+ UnknownFieldSet.CreateBuilder()
+ .AddField(UnknownTypeId,
+ UnknownField.CreateBuilder()
+ .AddLengthDelimited(ByteString.CopyFromUtf8("bar"))
+ .Build())
+ .Build())
+ .Build();
+
+ ByteString data = messageSet.ToByteString();
+
+ // Parse back using RawMessageSet and check the contents.
+ RawMessageSet raw = RawMessageSet.ParseFrom(data);
+
+ Assert.AreEqual(0, raw.UnknownFields.FieldDictionary.Count);
+
+ Assert.AreEqual(3, raw.ItemCount);
+ Assert.AreEqual(TypeId1, raw.ItemList[0].TypeId);
+ Assert.AreEqual(TypeId2, raw.ItemList[1].TypeId);
+ Assert.AreEqual(UnknownTypeId, raw.ItemList[2].TypeId);
+
+ TestMessageSetExtension1 message1 = TestMessageSetExtension1.ParseFrom(raw.GetItem(0).Message.ToByteArray());
+ Assert.AreEqual(123, message1.I);
+
+ TestMessageSetExtension2 message2 = TestMessageSetExtension2.ParseFrom(raw.GetItem(1).Message.ToByteArray());
+ Assert.AreEqual("foo", message2.Str);
+
+ Assert.AreEqual("bar", raw.GetItem(2).Message.ToStringUtf8());
+ }
+
+ [Test]
+ public void ParseMessageSet()
+ {
+ ExtensionRegistry extensionRegistry = ExtensionRegistry.CreateInstance();
+ extensionRegistry.Add(TestMessageSetExtension1.MessageSetExtension);
+ extensionRegistry.Add(TestMessageSetExtension2.MessageSetExtension);
+
+ // Set up a RawMessageSet with two known messages and an unknown one.
+ RawMessageSet raw =
+ RawMessageSet.CreateBuilder()
+ .AddItem(
+ RawMessageSet.Types.Item.CreateBuilder()
+ .SetTypeId(TypeId1)
+ .SetMessage(
+ TestMessageSetExtension1.CreateBuilder()
+ .SetI(123)
+ .Build().ToByteString())
+ .Build())
+ .AddItem(
+ RawMessageSet.Types.Item.CreateBuilder()
+ .SetTypeId(TypeId2)
+ .SetMessage(
+ TestMessageSetExtension2.CreateBuilder()
+ .SetStr("foo")
+ .Build().ToByteString())
+ .Build())
+ .AddItem(
+ RawMessageSet.Types.Item.CreateBuilder()
+ .SetTypeId(UnknownTypeId)
+ .SetMessage(ByteString.CopyFromUtf8("bar"))
+ .Build())
+ .Build();
+
+ ByteString data = raw.ToByteString();
+
+ // Parse as a TestMessageSet and check the contents.
+ TestMessageSet messageSet =
+ TestMessageSet.ParseFrom(data, extensionRegistry);
+
+ Assert.AreEqual(123, messageSet.GetExtension(TestMessageSetExtension1.MessageSetExtension).I);
+ Assert.AreEqual("foo", messageSet.GetExtension(TestMessageSetExtension2.MessageSetExtension).Str);
+
+ // Check for unknown field with type LENGTH_DELIMITED,
+ // number UNKNOWN_TYPE_ID, and contents "bar".
+ UnknownFieldSet unknownFields = messageSet.UnknownFields;
+ Assert.AreEqual(1, unknownFields.FieldDictionary.Count);
+ Assert.IsTrue(unknownFields.HasField(UnknownTypeId));
+
+ UnknownField field = unknownFields[UnknownTypeId];
+ Assert.AreEqual(1, field.LengthDelimitedList.Count);
+ Assert.AreEqual("bar", field.LengthDelimitedList[0].ToStringUtf8());
+ }
+ }
+}
\ No newline at end of file |