diff options
Diffstat (limited to 'csharp/src/Google.Protobuf.Test')
27 files changed, 2646 insertions, 470 deletions
diff --git a/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs index 54c44e47..c0a9ffd1 100644 --- a/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs +++ b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs @@ -284,7 +284,7 @@ namespace Google.Protobuf Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
}
- private static TestRecursiveMessage MakeRecursiveMessage(int depth)
+ internal static TestRecursiveMessage MakeRecursiveMessage(int depth)
{
if (depth == 0)
{
@@ -296,7 +296,7 @@ namespace Google.Protobuf }
}
- private static void AssertMessageDepth(TestRecursiveMessage message, int depth)
+ internal static void AssertMessageDepth(TestRecursiveMessage message, int depth)
{
if (depth == 0)
{
@@ -470,6 +470,52 @@ namespace Google.Protobuf }
[Test]
+ public void SkipGroup_WrongEndGroupTag()
+ {
+ // Create an output stream with:
+ // Field 1: string "field 1"
+ // Start group 2
+ // Field 3: fixed int32
+ // End group 4 (should give an error)
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ output.WriteTag(1, WireFormat.WireType.LengthDelimited);
+ output.WriteString("field 1");
+
+ // The outer group...
+ output.WriteTag(2, WireFormat.WireType.StartGroup);
+ output.WriteTag(3, WireFormat.WireType.Fixed32);
+ output.WriteFixed32(100);
+ output.WriteTag(4, WireFormat.WireType.EndGroup);
+ output.Flush();
+ stream.Position = 0;
+
+ // Now act like a generated client
+ var input = new CodedInputStream(stream);
+ Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
+ Assert.AreEqual("field 1", input.ReadString());
+ Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
+ Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
+ }
+
+ [Test]
+ public void RogueEndGroupTag()
+ {
+ // If we have an end-group tag without a leading start-group tag, generated
+ // code will just call SkipLastField... so that should fail.
+
+ var stream = new MemoryStream();
+ var output = new CodedOutputStream(stream);
+ output.WriteTag(1, WireFormat.WireType.EndGroup);
+ output.Flush();
+ stream.Position = 0;
+
+ var input = new CodedInputStream(stream);
+ Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag());
+ Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
+ }
+
+ [Test]
public void EndOfStreamReachedWhileSkippingGroup()
{
var stream = new MemoryStream();
@@ -484,7 +530,7 @@ namespace Google.Protobuf // Now act like a generated client
var input = new CodedInputStream(stream);
input.ReadTag();
- Assert.Throws<InvalidProtocolBufferException>(() => input.SkipLastField());
+ Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
}
[Test]
@@ -506,7 +552,7 @@ namespace Google.Protobuf // Now act like a generated client
var input = new CodedInputStream(stream);
Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag());
- Assert.Throws<InvalidProtocolBufferException>(() => input.SkipLastField());
+ Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
}
[Test]
@@ -526,5 +572,27 @@ namespace Google.Protobuf Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1));
Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0));
}
+
+ [Test]
+ public void Dispose_DisposesUnderlyingStream()
+ {
+ var memoryStream = new MemoryStream();
+ Assert.IsTrue(memoryStream.CanRead);
+ using (var cis = new CodedInputStream(memoryStream))
+ {
+ }
+ Assert.IsFalse(memoryStream.CanRead); // Disposed
+ }
+
+ [Test]
+ public void Dispose_WithLeaveOpen()
+ {
+ var memoryStream = new MemoryStream();
+ Assert.IsTrue(memoryStream.CanRead);
+ using (var cis = new CodedInputStream(memoryStream, true))
+ {
+ }
+ Assert.IsTrue(memoryStream.CanRead); // We left the stream open
+ }
}
}
\ No newline at end of file diff --git a/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs index 3297fe87..48bf6d60 100644 --- a/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs +++ b/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs @@ -387,5 +387,33 @@ namespace Google.Protobuf Assert.IsTrue(cin.IsAtEnd);
}
}
+
+ [Test]
+ public void Dispose_DisposesUnderlyingStream()
+ {
+ var memoryStream = new MemoryStream();
+ Assert.IsTrue(memoryStream.CanWrite);
+ using (var cos = new CodedOutputStream(memoryStream))
+ {
+ cos.WriteRawByte(0);
+ Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
+ }
+ Assert.AreEqual(1, memoryStream.ToArray().Length); // Flushed data from CodedOutputStream to MemoryStream
+ Assert.IsFalse(memoryStream.CanWrite); // Disposed
+ }
+
+ [Test]
+ public void Dispose_WithLeaveOpen()
+ {
+ var memoryStream = new MemoryStream();
+ Assert.IsTrue(memoryStream.CanWrite);
+ using (var cos = new CodedOutputStream(memoryStream, true))
+ {
+ cos.WriteRawByte(0);
+ Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
+ }
+ Assert.AreEqual(1, memoryStream.Position); // Flushed data from CodedOutputStream to MemoryStream
+ Assert.IsTrue(memoryStream.CanWrite); // We left the stream open
+ }
}
}
\ No newline at end of file diff --git a/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs b/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs index ba82c0e8..9c845907 100644 --- a/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs +++ b/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs @@ -56,7 +56,7 @@ namespace Google.Protobuf.Collections } [Test] - public void NullValues() + public void NullValuesProhibited() { TestNullValues<int?>(0); TestNullValues(""); @@ -65,19 +65,12 @@ namespace Google.Protobuf.Collections private void TestNullValues<T>(T nonNullValue) { - var map = new MapField<int, T>(false); + var map = new MapField<int, T>(); var nullValue = (T) (object) null; Assert.Throws<ArgumentNullException>(() => map.Add(0, nullValue)); Assert.Throws<ArgumentNullException>(() => map[0] = nullValue); map.Add(1, nonNullValue); map[1] = nonNullValue; - - // Doesn't throw... - map = new MapField<int, T>(true); - map.Add(0, nullValue); - map[0] = nullValue; - map.Add(1, nonNullValue); - map[1] = nonNullValue; } [Test] @@ -161,27 +154,6 @@ namespace Google.Protobuf.Collections } [Test] - public void EqualityHandlesNullValues() - { - var map1 = new MapField<string, ForeignMessage>(); - map1.Add("a", new ForeignMessage { C = 10 }); - map1.Add("b", null); - - var map2 = new MapField<string, ForeignMessage>(); - map2.Add("a", new ForeignMessage { C = 10 }); - map2.Add("b", null); - - EqualityTester.AssertEquality(map1, map2); - // Check the null value isn't ignored entirely... - Assert.IsTrue(map1.Remove("b")); - EqualityTester.AssertInequality(map1, map2); - map1.Add("b", new ForeignMessage()); - EqualityTester.AssertInequality(map1, map2); - map1["b"] = null; - EqualityTester.AssertEquality(map1, map2); - } - - [Test] public void Add_Dictionary() { var map1 = new MapField<string, string> @@ -454,30 +426,6 @@ namespace Google.Protobuf.Collections } [Test] - public void AllowNullValues_Property() - { - // Non-message reference type values are non-nullable by default, but can be overridden - Assert.IsFalse(new MapField<int, string>().AllowsNullValues); - Assert.IsFalse(new MapField<int, string>(false).AllowsNullValues); - Assert.IsTrue(new MapField<int, string>(true).AllowsNullValues); - - // Non-nullable value type values are never nullable - Assert.IsFalse(new MapField<int, int>().AllowsNullValues); - Assert.IsFalse(new MapField<int, int>(false).AllowsNullValues); - Assert.Throws<ArgumentException>(() => new MapField<int, int>(true)); - - // Message type values are nullable by default, but can be overridden - Assert.IsTrue(new MapField<int, TestAllTypes>().AllowsNullValues); - Assert.IsFalse(new MapField<int, TestAllTypes>(false).AllowsNullValues); - Assert.IsTrue(new MapField<int, TestAllTypes>(true).AllowsNullValues); - - // Nullable value type values are nullable by default, but can be overridden - Assert.IsTrue(new MapField<int, int?>().AllowsNullValues); - Assert.IsFalse(new MapField<int, int?>(false).AllowsNullValues); - Assert.IsTrue(new MapField<int, int?>(true).AllowsNullValues); - } - - [Test] public void KeysReturnsLiveView() { var map = new MapField<string, string>(); diff --git a/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs b/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs index 38ba227f..c616470e 100644 --- a/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs +++ b/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs @@ -58,7 +58,7 @@ namespace Google.Protobuf new FieldCodecTestData<float>(FieldCodec.ForFloat(100), 1234.5f, "Float"), new FieldCodecTestData<double>(FieldCodec.ForDouble(100), 1234567890.5d, "Double"), new FieldCodecTestData<ForeignEnum>( - FieldCodec.ForEnum(100, t => (int) t, t => (ForeignEnum) t), ForeignEnum.FOREIGN_BAZ, "Enum"), + FieldCodec.ForEnum(100, t => (int) t, t => (ForeignEnum) t), ForeignEnum.ForeignBaz, "Enum"), new FieldCodecTestData<ForeignMessage>( FieldCodec.ForMessage(100, ForeignMessage.Parser), new ForeignMessage { C = 10 }, "Message"), }; diff --git a/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs b/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs index 575d4586..8b153d69 100644 --- a/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs +++ b/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs @@ -66,13 +66,13 @@ namespace Google.Protobuf Assert.AreEqual(0, message.SingleFixed32);
Assert.AreEqual(0L, message.SingleFixed64);
Assert.AreEqual(0.0f, message.SingleFloat);
- Assert.AreEqual(ForeignEnum.FOREIGN_UNSPECIFIED, message.SingleForeignEnum);
+ Assert.AreEqual(ForeignEnum.ForeignUnspecified, message.SingleForeignEnum);
Assert.IsNull(message.SingleForeignMessage);
- Assert.AreEqual(ImportEnum.IMPORT_ENUM_UNSPECIFIED, message.SingleImportEnum);
+ Assert.AreEqual(ImportEnum.Unspecified, message.SingleImportEnum);
Assert.IsNull(message.SingleImportMessage);
Assert.AreEqual(0, message.SingleInt32);
Assert.AreEqual(0L, message.SingleInt64);
- Assert.AreEqual(TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED, message.SingleNestedEnum);
+ Assert.AreEqual(TestAllTypes.Types.NestedEnum.Unspecified, message.SingleNestedEnum);
Assert.IsNull(message.SingleNestedMessage);
Assert.IsNull(message.SinglePublicImportMessage);
Assert.AreEqual(0, message.SingleSfixed32);
@@ -145,13 +145,13 @@ namespace Google.Protobuf SingleFixed32 = 23,
SingleFixed64 = 1234567890123,
SingleFloat = 12.25f,
- SingleForeignEnum = ForeignEnum.FOREIGN_BAR,
+ SingleForeignEnum = ForeignEnum.ForeignBar,
SingleForeignMessage = new ForeignMessage { C = 10 },
- SingleImportEnum = ImportEnum.IMPORT_BAZ,
+ SingleImportEnum = ImportEnum.ImportBaz,
SingleImportMessage = new ImportMessage { D = 20 },
SingleInt32 = 100,
SingleInt64 = 3210987654321,
- SingleNestedEnum = TestAllTypes.Types.NestedEnum.FOO,
+ SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo,
SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 },
SinglePublicImportMessage = new PublicImportMessage { E = 54 },
SingleSfixed32 = -123,
@@ -179,13 +179,13 @@ namespace Google.Protobuf RepeatedFixed32 = { uint.MaxValue, 23 },
RepeatedFixed64 = { ulong.MaxValue, 1234567890123 },
RepeatedFloat = { 100f, 12.25f },
- RepeatedForeignEnum = { ForeignEnum.FOREIGN_FOO, ForeignEnum.FOREIGN_BAR },
+ RepeatedForeignEnum = { ForeignEnum.ForeignFoo, ForeignEnum.ForeignBar },
RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } },
- RepeatedImportEnum = { ImportEnum.IMPORT_BAZ, ImportEnum.IMPORT_ENUM_UNSPECIFIED },
+ RepeatedImportEnum = { ImportEnum.ImportBaz, ImportEnum.Unspecified },
RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } },
RepeatedInt32 = { 100, 200 },
RepeatedInt64 = { 3210987654321, long.MaxValue },
- RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.NEG },
+ RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg },
RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 35 }, new TestAllTypes.Types.NestedMessage { Bb = 10 } },
RepeatedPublicImportMessage = { new PublicImportMessage { E = 54 }, new PublicImportMessage { E = -1 } },
RepeatedSfixed32 = { -123, 123 },
@@ -221,11 +221,11 @@ namespace Google.Protobuf },
MapInt32ForeignMessage = {
{ 0, new ForeignMessage { C = 10 } },
- { 5, null },
+ { 5, new ForeignMessage() },
},
MapInt32Enum = {
- { 1, MapEnum.MAP_ENUM_BAR },
- { 2000, MapEnum.MAP_ENUM_FOO }
+ { 1, MapEnum.Bar },
+ { 2000, MapEnum.Foo }
}
};
@@ -249,7 +249,7 @@ namespace Google.Protobuf Assert.AreEqual(1, parsed.MapInt32Bytes.Count);
Assert.AreEqual(ByteString.Empty, parsed.MapInt32Bytes[0]);
}
-
+
[Test]
public void MapWithOnlyValue()
{
@@ -269,6 +269,40 @@ namespace Google.Protobuf }
[Test]
+ public void MapWithOnlyKey_PrimitiveValue()
+ {
+ // Hand-craft the stream to contain a single entry with just a key.
+ var memoryStream = new MemoryStream();
+ var output = new CodedOutputStream(memoryStream);
+ output.WriteTag(TestMap.MapInt32DoubleFieldNumber, WireFormat.WireType.LengthDelimited);
+ int key = 10;
+ output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key));
+ output.WriteTag(1, WireFormat.WireType.Varint);
+ output.WriteInt32(key);
+ output.Flush();
+
+ var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
+ Assert.AreEqual(0.0, parsed.MapInt32Double[key]);
+ }
+
+ [Test]
+ public void MapWithOnlyKey_MessageValue()
+ {
+ // Hand-craft the stream to contain a single entry with just a key.
+ var memoryStream = new MemoryStream();
+ var output = new CodedOutputStream(memoryStream);
+ output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited);
+ int key = 10;
+ output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key));
+ output.WriteTag(1, WireFormat.WireType.Varint);
+ output.WriteInt32(key);
+ output.Flush();
+
+ var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
+ Assert.AreEqual(new ForeignMessage(), parsed.MapInt32ForeignMessage[key]);
+ }
+
+ [Test]
public void MapIgnoresExtraFieldsWithinEntryMessages()
{
// Hand-craft the stream to contain a single entry with three fields
@@ -415,7 +449,7 @@ namespace Google.Protobuf SingleFloat = 12.25f,
SingleInt32 = 100,
SingleInt64 = 3210987654321,
- SingleNestedEnum = TestAllTypes.Types.NestedEnum.FOO,
+ SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo,
SingleSfixed32 = -123,
SingleSfixed64 = -12345678901234,
SingleSint32 = -456,
@@ -445,7 +479,7 @@ namespace Google.Protobuf RepeatedFloat = { 100f, 12.25f },
RepeatedInt32 = { 100, 200 },
RepeatedInt64 = { 3210987654321, long.MaxValue },
- RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.NEG },
+ RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg },
RepeatedSfixed32 = { -123, 123 },
RepeatedSfixed64 = { -12345678901234, 12345678901234 },
RepeatedSint32 = { -456, 100 },
@@ -566,6 +600,16 @@ namespace Google.Protobuf }
[Test]
+ public void Oneof_DefaultValuesNotEqual()
+ {
+ var message1 = new TestAllTypes { OneofString = "" };
+ var message2 = new TestAllTypes { OneofUint32 = 0 };
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message1.OneofFieldCase);
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase);
+ Assert.AreNotEqual(message1, message2);
+ }
+
+ [Test]
public void OneofSerialization_NonDefaultValue()
{
var message = new TestAllTypes();
@@ -626,7 +670,7 @@ namespace Google.Protobuf {
// 130, 3 is the message tag
// 1 is the data length - but there's no data.
- var data = new byte[] { 130, 3, 1 };
+ var data = new byte[] { 130, 3, 1 };
Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(data));
}
@@ -635,21 +679,45 @@ namespace Google.Protobuf /// for details; we may want to change this.
/// </summary>
[Test]
- public void ExtraEndGroupSkipped()
+ public void ExtraEndGroupThrows()
{
var message = SampleMessages.CreateFullTestAllTypes();
var stream = new MemoryStream();
var output = new CodedOutputStream(stream);
- output.WriteTag(100, WireFormat.WireType.EndGroup);
output.WriteTag(TestAllTypes.SingleFixed32FieldNumber, WireFormat.WireType.Fixed32);
output.WriteFixed32(123);
+ output.WriteTag(100, WireFormat.WireType.EndGroup);
output.Flush();
stream.Position = 0;
- var parsed = TestAllTypes.Parser.ParseFrom(stream);
- Assert.AreEqual(new TestAllTypes { SingleFixed32 = 123 }, parsed);
+ Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream));
+ }
+
+ [Test]
+ public void CustomDiagnosticMessage_DirectToStringCall()
+ {
+ var message = new ForeignMessage { C = 31 };
+ Assert.AreEqual("{ \"c\": 31, \"@cInHex\": \"1f\" }", message.ToString());
+ Assert.AreEqual("{ \"c\": 31 }", JsonFormatter.Default.Format(message));
+ }
+
+ [Test]
+ public void CustomDiagnosticMessage_Nested()
+ {
+ var message = new TestAllTypes { SingleForeignMessage = new ForeignMessage { C = 16 } };
+ Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16, \"@cInHex\": \"10\" } }", message.ToString());
+ Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16 } }", JsonFormatter.Default.Format(message));
+ }
+
+ [Test]
+ public void CustomDiagnosticMessage_DirectToTextWriterCall()
+ {
+ var message = new ForeignMessage { C = 31 };
+ var writer = new StringWriter();
+ JsonFormatter.Default.Format(message, writer);
+ Assert.AreEqual("{ \"c\": 31 }", writer.ToString());
}
}
-}
+}
\ No newline at end of file diff --git a/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj b/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj index 33be5dae..4f37c5e2 100644 --- a/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj +++ b/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj @@ -55,7 +55,7 @@ <GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
<Prefer32Bit>false</Prefer32Bit>
<SignAssembly>True</SignAssembly>
- <AssemblyOriginatorKeyFile>C:\keys\Google.Protobuf.snk</AssemblyOriginatorKeyFile>
+ <AssemblyOriginatorKeyFile>..\..\keys\Google.Protobuf.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="mscorlib" />
@@ -95,10 +95,14 @@ <Compile Include="Collections\MapFieldTest.cs" />
<Compile Include="Collections\RepeatedFieldTest.cs" />
<Compile Include="JsonFormatterTest.cs" />
+ <Compile Include="JsonParserTest.cs" />
+ <Compile Include="JsonTokenizerTest.cs" />
<Compile Include="Reflection\DescriptorsTest.cs" />
<Compile Include="Reflection\FieldAccessTest.cs" />
+ <Compile Include="Reflection\TypeRegistryTest.cs" />
<Compile Include="SampleEnum.cs" />
<Compile Include="SampleMessages.cs" />
+ <Compile Include="TestProtos\ForeignMessagePartial.cs" />
<Compile Include="TestProtos\MapUnittestProto3.cs" />
<Compile Include="TestProtos\UnittestImportProto3.cs" />
<Compile Include="TestProtos\UnittestImportPublicProto3.cs" />
@@ -111,6 +115,7 @@ <Compile Include="TestProtos\UnittestWellKnownTypes.cs" />
<Compile Include="WellKnownTypes\AnyTest.cs" />
<Compile Include="WellKnownTypes\DurationTest.cs" />
+ <Compile Include="WellKnownTypes\FieldMaskTest.cs" />
<Compile Include="WellKnownTypes\TimestampTest.cs" />
<Compile Include="WellKnownTypes\WrappersTest.cs" />
</ItemGroup>
diff --git a/csharp/src/Google.Protobuf.Test/IssuesTest.cs b/csharp/src/Google.Protobuf.Test/IssuesTest.cs index a0350035..a38d6b08 100644 --- a/csharp/src/Google.Protobuf.Test/IssuesTest.cs +++ b/csharp/src/Google.Protobuf.Test/IssuesTest.cs @@ -59,5 +59,24 @@ namespace Google.Protobuf // Underscores aren't reflected in the JSON.
Assert.AreEqual("{ \"types\": 10, \"descriptor\": 20 }", message.ToString());
}
+
+ [Test]
+ public void JsonNameParseTest()
+ {
+ var settings = new JsonParser.Settings(10, TypeRegistry.FromFiles(UnittestIssuesReflection.Descriptor));
+ var parser = new JsonParser(settings);
+
+ // It is safe to use either original field name or explicitly specified json_name
+ Assert.AreEqual(new TestJsonName { Name = "test", Description = "test2", Guid = "test3" },
+ parser.Parse<TestJsonName>("{ \"name\": \"test\", \"desc\": \"test2\", \"guid\": \"test3\" }"));
+ }
+
+ [Test]
+ public void JsonNameFormatTest()
+ {
+ var message = new TestJsonName { Name = "test", Description = "test2", Guid = "test3" };
+ Assert.AreEqual("{ \"name\": \"test\", \"desc\": \"test2\", \"exid\": \"test3\" }",
+ JsonFormatter.Default.Format(message));
+ }
}
}
diff --git a/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs b/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs index 3e7a3d2e..827a7595 100644 --- a/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs +++ b/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs @@ -35,6 +35,9 @@ using Google.Protobuf.TestProtos; using NUnit.Framework; using UnitTest.Issues.TestProtos; using Google.Protobuf.WellKnownTypes; +using Google.Protobuf.Reflection; + +using static Google.Protobuf.JsonParserTest; // For WrapInQuotes namespace Google.Protobuf { @@ -72,13 +75,13 @@ namespace Google.Protobuf SingleFixed32 = 23, SingleFixed64 = 1234567890123, SingleFloat = 12.25f, - SingleForeignEnum = ForeignEnum.FOREIGN_BAR, + SingleForeignEnum = ForeignEnum.ForeignBar, SingleForeignMessage = new ForeignMessage { C = 10 }, - SingleImportEnum = ImportEnum.IMPORT_BAZ, + SingleImportEnum = ImportEnum.ImportBaz, SingleImportMessage = new ImportMessage { D = 20 }, SingleInt32 = 100, SingleInt64 = 3210987654321, - SingleNestedEnum = TestAllTypes.Types.NestedEnum.FOO, + SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 }, SinglePublicImportMessage = new PublicImportMessage { E = 54 }, SingleSfixed32 = -123, @@ -162,41 +165,31 @@ namespace Google.Protobuf } [Test] - public void UnknownEnumValueOmitted_SingleField() + public void UnknownEnumValueNumeric_SingleField() { var message = new TestAllTypes { SingleForeignEnum = (ForeignEnum) 100 }; - AssertJson("{ }", JsonFormatter.Default.Format(message)); + AssertJson("{ 'singleForeignEnum': 100 }", JsonFormatter.Default.Format(message)); } [Test] - public void UnknownEnumValueOmitted_RepeatedField() + public void UnknownEnumValueNumeric_RepeatedField() { - var message = new TestAllTypes { RepeatedForeignEnum = { ForeignEnum.FOREIGN_BAZ, (ForeignEnum) 100, ForeignEnum.FOREIGN_FOO } }; - AssertJson("{ 'repeatedForeignEnum': [ 'FOREIGN_BAZ', 'FOREIGN_FOO' ] }", JsonFormatter.Default.Format(message)); + var message = new TestAllTypes { RepeatedForeignEnum = { ForeignEnum.ForeignBaz, (ForeignEnum) 100, ForeignEnum.ForeignFoo } }; + AssertJson("{ 'repeatedForeignEnum': [ 'FOREIGN_BAZ', 100, 'FOREIGN_FOO' ] }", JsonFormatter.Default.Format(message)); } [Test] - public void UnknownEnumValueOmitted_MapField() + public void UnknownEnumValueNumeric_MapField() { - // This matches the C++ behaviour. - var message = new TestMap { MapInt32Enum = { { 1, MapEnum.MAP_ENUM_FOO }, { 2, (MapEnum) 100 }, { 3, MapEnum.MAP_ENUM_BAR } } }; - AssertJson("{ 'mapInt32Enum': { '1': 'MAP_ENUM_FOO', '3': 'MAP_ENUM_BAR' } }", JsonFormatter.Default.Format(message)); + var message = new TestMap { MapInt32Enum = { { 1, MapEnum.Foo }, { 2, (MapEnum) 100 }, { 3, MapEnum.Bar } } }; + AssertJson("{ 'mapInt32Enum': { '1': 'MAP_ENUM_FOO', '2': 100, '3': 'MAP_ENUM_BAR' } }", JsonFormatter.Default.Format(message)); } [Test] - public void UnknownEnumValueOmitted_RepeatedField_AllEntriesUnknown() + public void UnknownEnumValue_RepeatedField_AllEntriesUnknown() { - // *Maybe* we should hold off on writing the "[" until we find that we've got at least one value to write... - // but this is what happens at the moment, and it doesn't seem too awful. var message = new TestAllTypes { RepeatedForeignEnum = { (ForeignEnum) 200, (ForeignEnum) 100 } }; - AssertJson("{ 'repeatedForeignEnum': [ ] }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void NullValueForMessage() - { - var message = new TestMap { MapInt32ForeignMessage = { { 10, null } } }; - AssertJson("{ 'mapInt32ForeignMessage': { '10': null } }", JsonFormatter.Default.Format(message)); + AssertJson("{ 'repeatedForeignEnum': [ 200, 100 ] }", JsonFormatter.Default.Format(message)); } [Test] @@ -276,6 +269,13 @@ namespace Google.Protobuf } [Test] + public void WrapperFormatting_Message() + { + Assert.AreEqual("\"\"", JsonFormatter.Default.Format(new StringValue())); + Assert.AreEqual("0", JsonFormatter.Default.Format(new Int32Value())); + } + + [Test] public void WrapperFormatting_IncludeNull() { // The actual JSON here is very large because there are lots of fields. Just test a couple of them. @@ -311,27 +311,51 @@ namespace Google.Protobuf } [Test] - public void TimestampStandalone() + [TestCase("1970-01-01T00:00:00Z", 0)] + [TestCase("1970-01-01T00:00:00.000000001Z", 1)] + [TestCase("1970-01-01T00:00:00.000000010Z", 10)] + [TestCase("1970-01-01T00:00:00.000000100Z", 100)] + [TestCase("1970-01-01T00:00:00.000001Z", 1000)] + [TestCase("1970-01-01T00:00:00.000010Z", 10000)] + [TestCase("1970-01-01T00:00:00.000100Z", 100000)] + [TestCase("1970-01-01T00:00:00.001Z", 1000000)] + [TestCase("1970-01-01T00:00:00.010Z", 10000000)] + [TestCase("1970-01-01T00:00:00.100Z", 100000000)] + [TestCase("1970-01-01T00:00:00.120Z", 120000000)] + [TestCase("1970-01-01T00:00:00.123Z", 123000000)] + [TestCase("1970-01-01T00:00:00.123400Z", 123400000)] + [TestCase("1970-01-01T00:00:00.123450Z", 123450000)] + [TestCase("1970-01-01T00:00:00.123456Z", 123456000)] + [TestCase("1970-01-01T00:00:00.123456700Z", 123456700)] + [TestCase("1970-01-01T00:00:00.123456780Z", 123456780)] + [TestCase("1970-01-01T00:00:00.123456789Z", 123456789)] + public void TimestampStandalone(string expected, int nanos) { - Assert.AreEqual("1970-01-01T00:00:00Z", new Timestamp().ToString()); - Assert.AreEqual("1970-01-01T00:00:00.100Z", new Timestamp { Nanos = 100000000 }.ToString()); - Assert.AreEqual("1970-01-01T00:00:00.120Z", new Timestamp { Nanos = 120000000 }.ToString()); - Assert.AreEqual("1970-01-01T00:00:00.123Z", new Timestamp { Nanos = 123000000 }.ToString()); - Assert.AreEqual("1970-01-01T00:00:00.123400Z", new Timestamp { Nanos = 123400000 }.ToString()); - Assert.AreEqual("1970-01-01T00:00:00.123450Z", new Timestamp { Nanos = 123450000 }.ToString()); - Assert.AreEqual("1970-01-01T00:00:00.123456Z", new Timestamp { Nanos = 123456000 }.ToString()); - Assert.AreEqual("1970-01-01T00:00:00.123456700Z", new Timestamp { Nanos = 123456700 }.ToString()); - Assert.AreEqual("1970-01-01T00:00:00.123456780Z", new Timestamp { Nanos = 123456780 }.ToString()); - Assert.AreEqual("1970-01-01T00:00:00.123456789Z", new Timestamp { Nanos = 123456789 }.ToString()); + Assert.AreEqual(WrapInQuotes(expected), new Timestamp { Nanos = nanos }.ToString()); + } - // One before and one after the Unix epoch - Assert.AreEqual("1673-06-19T12:34:56Z", + [Test] + public void TimestampStandalone_FromDateTime() + { + // One before and one after the Unix epoch, more easily represented via DateTime. + Assert.AreEqual("\"1673-06-19T12:34:56Z\"", new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp().ToString()); - Assert.AreEqual("2015-07-31T10:29:34Z", + Assert.AreEqual("\"2015-07-31T10:29:34Z\"", new DateTime(2015, 7, 31, 10, 29, 34, DateTimeKind.Utc).ToTimestamp().ToString()); } [Test] + [TestCase(-1, -1)] // Would be valid as duration + [TestCase(1, Timestamp.MaxNanos + 1)] + [TestCase(Timestamp.UnixSecondsAtBclMaxValue + 1, 0)] + [TestCase(Timestamp.UnixSecondsAtBclMinValue - 1, 0)] + public void TimestampStandalone_NonNormalized(long seconds, int nanoseconds) + { + var timestamp = new Timestamp { Seconds = seconds, Nanos = nanoseconds }; + Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(timestamp)); + } + + [Test] public void TimestampField() { var message = new TestWellKnownTypes { TimestampField = new Timestamp() }; @@ -342,6 +366,14 @@ namespace Google.Protobuf [TestCase(0, 0, "0s")] [TestCase(1, 0, "1s")] [TestCase(-1, 0, "-1s")] + [TestCase(0, 1, "0.000000001s")] + [TestCase(0, 10, "0.000000010s")] + [TestCase(0, 100, "0.000000100s")] + [TestCase(0, 1000, "0.000001s")] + [TestCase(0, 10000, "0.000010s")] + [TestCase(0, 100000, "0.000100s")] + [TestCase(0, 1000000, "0.001s")] + [TestCase(0, 10000000, "0.010s")] [TestCase(0, 100000000, "0.100s")] [TestCase(0, 120000000, "0.120s")] [TestCase(0, 123000000, "0.123s")] @@ -354,12 +386,19 @@ namespace Google.Protobuf [TestCase(0, -100000000, "-0.100s")] [TestCase(1, 100000000, "1.100s")] [TestCase(-1, -100000000, "-1.100s")] - // Non-normalized examples - [TestCase(1, 2123456789, "3.123456789s")] - [TestCase(1, -100000000, "0.900s")] public void DurationStandalone(long seconds, int nanoseconds, string expected) { - Assert.AreEqual(expected, new Duration { Seconds = seconds, Nanos = nanoseconds }.ToString()); + var json = JsonFormatter.Default.Format(new Duration { Seconds = seconds, Nanos = nanoseconds }); + Assert.AreEqual(WrapInQuotes(expected), json); + } + + [Test] + [TestCase(1, 2123456789)] + [TestCase(1, -100000000)] + public void DurationStandalone_NonNormalized(long seconds, int nanoseconds) + { + var duration = new Duration { Seconds = seconds, Nanos = nanoseconds }; + Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(duration)); } [Test] @@ -376,26 +415,36 @@ namespace Google.Protobuf { Fields = { - { "a", new Value { NullValue = new NullValue() } }, - { "b", new Value { BoolValue = false } }, - { "c", new Value { NumberValue = 10.5 } }, - { "d", new Value { StringValue = "text" } }, - { "e", new Value { ListValue = new ListValue { Values = { new Value { StringValue = "t1" }, new Value { NumberValue = 5 } } } } }, - { "f", new Value { StructValue = new Struct { Fields = { { "nested", new Value { StringValue = "value" } } } } } } + { "a", Value.ForNull() }, + { "b", Value.ForBool(false) }, + { "c", Value.ForNumber(10.5) }, + { "d", Value.ForString("text") }, + { "e", Value.ForList(Value.ForString("t1"), Value.ForNumber(5)) }, + { "f", Value.ForStruct(new Struct { Fields = { { "nested", Value.ForString("value") } } }) } } }; AssertJson("{ 'a': null, 'b': false, 'c': 10.5, 'd': 'text', 'e': [ 't1', 5 ], 'f': { 'nested': 'value' } }", message.ToString()); } [Test] + [TestCase("foo__bar")] + [TestCase("foo_3_ar")] + [TestCase("fooBar")] + public void FieldMaskInvalid(string input) + { + var mask = new FieldMask { Paths = { input } }; + Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(mask)); + } + + [Test] public void FieldMaskStandalone() { var fieldMask = new FieldMask { Paths = { "", "single", "with_underscore", "nested.field.name", "nested..double_dot" } }; - Assert.AreEqual(",single,withUnderscore,nested.field.name,nested..doubleDot", fieldMask.ToString()); + Assert.AreEqual("\",single,withUnderscore,nested.field.name,nested..doubleDot\"", fieldMask.ToString()); // Invalid, but we shouldn't create broken JSON... fieldMask = new FieldMask { Paths = { "x\\y" } }; - Assert.AreEqual(@"x\\y", fieldMask.ToString()); + Assert.AreEqual(@"""x\\y""", fieldMask.ToString()); } [Test] @@ -405,6 +454,64 @@ namespace Google.Protobuf AssertJson("{ 'fieldMaskField': 'user.displayName,photo' }", JsonFormatter.Default.Format(message)); } + // SourceContext is an example of a well-known type with no special JSON handling + [Test] + public void SourceContextStandalone() + { + var message = new SourceContext { FileName = "foo.proto" }; + AssertJson("{ 'fileName': 'foo.proto' }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void AnyWellKnownType() + { + var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(Timestamp.Descriptor))); + var timestamp = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp(); + var any = Any.Pack(timestamp); + AssertJson("{ '@type': 'type.googleapis.com/google.protobuf.Timestamp', 'value': '1673-06-19T12:34:56Z' }", formatter.Format(any)); + } + + [Test] + public void AnyMessageType() + { + var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(TestAllTypes.Descriptor))); + var message = new TestAllTypes { SingleInt32 = 10, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } }; + var any = Any.Pack(message); + AssertJson("{ '@type': 'type.googleapis.com/protobuf_unittest.TestAllTypes', 'singleInt32': 10, 'singleNestedMessage': { 'bb': 20 } }", formatter.Format(any)); + } + + [Test] + public void AnyMessageType_CustomPrefix() + { + var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(TestAllTypes.Descriptor))); + var message = new TestAllTypes { SingleInt32 = 10 }; + var any = Any.Pack(message, "foo.bar/baz"); + AssertJson("{ '@type': 'foo.bar/baz/protobuf_unittest.TestAllTypes', 'singleInt32': 10 }", formatter.Format(any)); + } + + [Test] + public void AnyNested() + { + var registry = TypeRegistry.FromMessages(TestWellKnownTypes.Descriptor, TestAllTypes.Descriptor); + var formatter = new JsonFormatter(new JsonFormatter.Settings(false, registry)); + + // Nest an Any as the value of an Any. + var doubleNestedMessage = new TestAllTypes { SingleInt32 = 20 }; + var nestedMessage = Any.Pack(doubleNestedMessage); + var message = new TestWellKnownTypes { AnyField = Any.Pack(nestedMessage) }; + AssertJson("{ 'anyField': { '@type': 'type.googleapis.com/google.protobuf.Any', 'value': { '@type': 'type.googleapis.com/protobuf_unittest.TestAllTypes', 'singleInt32': 20 } } }", + formatter.Format(message)); + } + + [Test] + public void AnyUnknownType() + { + // The default type registry doesn't have any types in it. + var message = new TestAllTypes(); + var any = Any.Pack(message); + Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(any)); + } + /// <summary> /// Checks that the actual JSON is the same as the expected JSON - but after replacing /// all apostrophes in the expected JSON with double quotes. This basically makes the tests easier diff --git a/csharp/src/Google.Protobuf.Test/JsonParserTest.cs b/csharp/src/Google.Protobuf.Test/JsonParserTest.cs new file mode 100644 index 00000000..c3ad851b --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/JsonParserTest.cs @@ -0,0 +1,936 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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.Protobuf.Reflection; +using Google.Protobuf.TestProtos; +using Google.Protobuf.WellKnownTypes; +using NUnit.Framework; +using System; + +namespace Google.Protobuf +{ + /// <summary> + /// Unit tests for JSON parsing. + /// </summary> + public class JsonParserTest + { + // Sanity smoke test + [Test] + public void AllTypesRoundtrip() + { + AssertRoundtrip(SampleMessages.CreateFullTestAllTypes()); + } + + [Test] + public void Maps() + { + AssertRoundtrip(new TestMap { MapStringString = { { "with spaces", "bar" }, { "a", "b" } } }); + AssertRoundtrip(new TestMap { MapInt32Int32 = { { 0, 1 }, { 2, 3 } } }); + AssertRoundtrip(new TestMap { MapBoolBool = { { false, true }, { true, false } } }); + } + + [Test] + [TestCase(" 1 ")] + [TestCase("+1")] + [TestCase("1,000")] + [TestCase("1.5")] + public void IntegerMapKeysAreStrict(string keyText) + { + // Test that integer parsing is strict. We assume that if this is correct for int32, + // it's correct for other numeric key types. + var json = "{ \"mapInt32Int32\": { \"" + keyText + "\" : \"1\" } }"; + Assert.Throws<InvalidProtocolBufferException>(() => JsonParser.Default.Parse<TestMap>(json)); + } + + [Test] + public void OriginalFieldNameAccepted() + { + var json = "{ \"single_int32\": 10 }"; + var expected = new TestAllTypes { SingleInt32 = 10 }; + Assert.AreEqual(expected, TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + public void SourceContextRoundtrip() + { + AssertRoundtrip(new SourceContext { FileName = "foo.proto" }); + } + + [Test] + public void SingularWrappers_DefaultNonNullValues() + { + var message = new TestWellKnownTypes + { + StringField = "", + BytesField = ByteString.Empty, + BoolField = false, + FloatField = 0f, + DoubleField = 0d, + Int32Field = 0, + Int64Field = 0, + Uint32Field = 0, + Uint64Field = 0 + }; + AssertRoundtrip(message); + } + + [Test] + public void SingularWrappers_NonDefaultValues() + { + var message = new TestWellKnownTypes + { + StringField = "x", + BytesField = ByteString.CopyFrom(1, 2, 3), + BoolField = true, + FloatField = 12.5f, + DoubleField = 12.25d, + Int32Field = 1, + Int64Field = 2, + Uint32Field = 3, + Uint64Field = 4 + }; + AssertRoundtrip(message); + } + + [Test] + public void SingularWrappers_ExplicitNulls() + { + // When we parse the "valueField": null part, we remember it... basically, it's one case + // where explicit default values don't fully roundtrip. + var message = new TestWellKnownTypes { ValueField = Value.ForNull() }; + var json = new JsonFormatter(new JsonFormatter.Settings(true)).Format(message); + var parsed = JsonParser.Default.Parse<TestWellKnownTypes>(json); + Assert.AreEqual(message, parsed); + } + + [Test] + [TestCase(typeof(Int32Value), "32", 32)] + [TestCase(typeof(Int64Value), "32", 32L)] + [TestCase(typeof(UInt32Value), "32", 32U)] + [TestCase(typeof(UInt64Value), "32", 32UL)] + [TestCase(typeof(StringValue), "\"foo\"", "foo")] + [TestCase(typeof(FloatValue), "1.5", 1.5f)] + [TestCase(typeof(DoubleValue), "1.5", 1.5d)] + public void Wrappers_Standalone(System.Type wrapperType, string json, object expectedValue) + { + IMessage parsed = (IMessage)Activator.CreateInstance(wrapperType); + IMessage expected = (IMessage)Activator.CreateInstance(wrapperType); + JsonParser.Default.Merge(parsed, "null"); + Assert.AreEqual(expected, parsed); + + JsonParser.Default.Merge(parsed, json); + expected.Descriptor.Fields[WrappersReflection.WrapperValueFieldNumber].Accessor.SetValue(expected, expectedValue); + Assert.AreEqual(expected, parsed); + } + + [Test] + public void ExplicitNullValue() + { + string json = "{\"valueField\": null}"; + var message = JsonParser.Default.Parse<TestWellKnownTypes>(json); + Assert.AreEqual(new TestWellKnownTypes { ValueField = Value.ForNull() }, message); + } + + [Test] + public void BytesWrapper_Standalone() + { + ByteString data = ByteString.CopyFrom(1, 2, 3); + // Can't do this with attributes... + var parsed = JsonParser.Default.Parse<BytesValue>(WrapInQuotes(data.ToBase64())); + var expected = new BytesValue { Value = data }; + Assert.AreEqual(expected, parsed); + } + + [Test] + public void RepeatedWrappers() + { + var message = new RepeatedWellKnownTypes + { + BoolField = { true, false }, + BytesField = { ByteString.CopyFrom(1, 2, 3), ByteString.CopyFrom(4, 5, 6), ByteString.Empty }, + DoubleField = { 12.5, -1.5, 0d }, + FloatField = { 123.25f, -20f, 0f }, + Int32Field = { int.MaxValue, int.MinValue, 0 }, + Int64Field = { long.MaxValue, long.MinValue, 0L }, + StringField = { "First", "Second", "" }, + Uint32Field = { uint.MaxValue, uint.MinValue, 0U }, + Uint64Field = { ulong.MaxValue, ulong.MinValue, 0UL }, + }; + AssertRoundtrip(message); + } + + [Test] + public void RepeatedField_NullElementProhibited() + { + string json = "{ \"repeated_foreign_message\": [null] }"; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + public void RepeatedField_NullOverallValueAllowed() + { + string json = "{ \"repeated_foreign_message\": null }"; + Assert.AreEqual(new TestAllTypes(), TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("{ \"mapInt32Int32\": { \"10\": null }")] + [TestCase("{ \"mapStringString\": { \"abc\": null }")] + [TestCase("{ \"mapInt32ForeignMessage\": { \"10\": null }")] + public void MapField_NullValueProhibited(string json) + { + Assert.Throws<InvalidProtocolBufferException>(() => TestMap.Parser.ParseJson(json)); + } + + [Test] + public void MapField_NullOverallValueAllowed() + { + string json = "{ \"mapInt32Int32\": null }"; + Assert.AreEqual(new TestMap(), TestMap.Parser.ParseJson(json)); + } + + [Test] + public void IndividualWrapperTypes() + { + Assert.AreEqual(new StringValue { Value = "foo" }, StringValue.Parser.ParseJson("\"foo\"")); + Assert.AreEqual(new Int32Value { Value = 1 }, Int32Value.Parser.ParseJson("1")); + // Can parse strings directly too + Assert.AreEqual(new Int32Value { Value = 1 }, Int32Value.Parser.ParseJson("\"1\"")); + } + + private static void AssertRoundtrip<T>(T message) where T : IMessage<T>, new() + { + var clone = message.Clone(); + var json = JsonFormatter.Default.Format(message); + var parsed = JsonParser.Default.Parse<T>(json); + Assert.AreEqual(clone, parsed); + } + + [Test] + [TestCase("0", 0)] + [TestCase("-0", 0)] // Not entirely clear whether we intend to allow this... + [TestCase("1", 1)] + [TestCase("-1", -1)] + [TestCase("2147483647", 2147483647)] + [TestCase("-2147483648", -2147483648)] + public void StringToInt32_Valid(string jsonValue, int expectedParsedValue) + { + string json = "{ \"singleInt32\": \"" + jsonValue + "\"}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleInt32); + } + + [Test] + [TestCase("+0")] + [TestCase(" 1")] + [TestCase("1 ")] + [TestCase("00")] + [TestCase("-00")] + [TestCase("--1")] + [TestCase("+1")] + [TestCase("1.5")] + [TestCase("1e10")] + [TestCase("2147483648")] + [TestCase("-2147483649")] + public void StringToInt32_Invalid(string jsonValue) + { + string json = "{ \"singleInt32\": \"" + jsonValue + "\"}"; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0U)] + [TestCase("1", 1U)] + [TestCase("4294967295", 4294967295U)] + public void StringToUInt32_Valid(string jsonValue, uint expectedParsedValue) + { + string json = "{ \"singleUint32\": \"" + jsonValue + "\"}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleUint32); + } + + // Assume that anything non-bounds-related is covered in the Int32 case + [Test] + [TestCase("-1")] + [TestCase("4294967296")] + public void StringToUInt32_Invalid(string jsonValue) + { + string json = "{ \"singleUint32\": \"" + jsonValue + "\"}"; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0L)] + [TestCase("1", 1L)] + [TestCase("-1", -1L)] + [TestCase("9223372036854775807", 9223372036854775807)] + [TestCase("-9223372036854775808", -9223372036854775808)] + public void StringToInt64_Valid(string jsonValue, long expectedParsedValue) + { + string json = "{ \"singleInt64\": \"" + jsonValue + "\"}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleInt64); + } + + // Assume that anything non-bounds-related is covered in the Int32 case + [Test] + [TestCase("-9223372036854775809")] + [TestCase("9223372036854775808")] + public void StringToInt64_Invalid(string jsonValue) + { + string json = "{ \"singleInt64\": \"" + jsonValue + "\"}"; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0UL)] + [TestCase("1", 1UL)] + [TestCase("18446744073709551615", 18446744073709551615)] + public void StringToUInt64_Valid(string jsonValue, ulong expectedParsedValue) + { + string json = "{ \"singleUint64\": \"" + jsonValue + "\"}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleUint64); + } + + // Assume that anything non-bounds-related is covered in the Int32 case + [Test] + [TestCase("-1")] + [TestCase("18446744073709551616")] + public void StringToUInt64_Invalid(string jsonValue) + { + string json = "{ \"singleUint64\": \"" + jsonValue + "\"}"; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0d)] + [TestCase("1", 1d)] + [TestCase("1.000000", 1d)] + [TestCase("1.0000000000000000000000001", 1d)] // We don't notice that we haven't preserved the exact value + [TestCase("-1", -1d)] + [TestCase("1e1", 10d)] + [TestCase("1e01", 10d)] // Leading decimals are allowed in exponents + [TestCase("1E1", 10d)] // Either case is fine + [TestCase("-1e1", -10d)] + [TestCase("1.5e1", 15d)] + [TestCase("-1.5e1", -15d)] + [TestCase("15e-1", 1.5d)] + [TestCase("-15e-1", -1.5d)] + [TestCase("1.79769e308", 1.79769e308)] + [TestCase("-1.79769e308", -1.79769e308)] + [TestCase("Infinity", double.PositiveInfinity)] + [TestCase("-Infinity", double.NegativeInfinity)] + [TestCase("NaN", double.NaN)] + public void StringToDouble_Valid(string jsonValue, double expectedParsedValue) + { + string json = "{ \"singleDouble\": \"" + jsonValue + "\"}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleDouble); + } + + [Test] + [TestCase("1.7977e308")] + [TestCase("-1.7977e308")] + [TestCase("1e309")] + [TestCase("1,0")] + [TestCase("1.0.0")] + [TestCase("+1")] + [TestCase("00")] + [TestCase("01")] + [TestCase("-00")] + [TestCase("-01")] + [TestCase("--1")] + [TestCase(" Infinity")] + [TestCase(" -Infinity")] + [TestCase("NaN ")] + [TestCase("Infinity ")] + [TestCase("-Infinity ")] + [TestCase(" NaN")] + [TestCase("INFINITY")] + [TestCase("nan")] + [TestCase("\u00BD")] // 1/2 as a single Unicode character. Just sanity checking... + public void StringToDouble_Invalid(string jsonValue) + { + string json = "{ \"singleDouble\": \"" + jsonValue + "\"}"; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0f)] + [TestCase("1", 1f)] + [TestCase("1.000000", 1f)] + [TestCase("-1", -1f)] + [TestCase("3.402823e38", 3.402823e38f)] + [TestCase("-3.402823e38", -3.402823e38f)] + [TestCase("1.5e1", 15f)] + [TestCase("15e-1", 1.5f)] + public void StringToFloat_Valid(string jsonValue, float expectedParsedValue) + { + string json = "{ \"singleFloat\": \"" + jsonValue + "\"}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleFloat); + } + + [Test] + [TestCase("3.402824e38")] + [TestCase("-3.402824e38")] + [TestCase("1,0")] + [TestCase("1.0.0")] + [TestCase("+1")] + [TestCase("00")] + [TestCase("--1")] + public void StringToFloat_Invalid(string jsonValue) + { + string json = "{ \"singleFloat\": \"" + jsonValue + "\"}"; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0)] + [TestCase("-0", 0)] // Not entirely clear whether we intend to allow this... + [TestCase("1", 1)] + [TestCase("-1", -1)] + [TestCase("2147483647", 2147483647)] + [TestCase("-2147483648", -2147483648)] + [TestCase("1e1", 10)] + [TestCase("-1e1", -10)] + [TestCase("10.00", 10)] + [TestCase("-10.00", -10)] + public void NumberToInt32_Valid(string jsonValue, int expectedParsedValue) + { + string json = "{ \"singleInt32\": " + jsonValue + "}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleInt32); + } + + [Test] + [TestCase("+0", typeof(InvalidJsonException))] + [TestCase("00", typeof(InvalidJsonException))] + [TestCase("-00", typeof(InvalidJsonException))] + [TestCase("--1", typeof(InvalidJsonException))] + [TestCase("+1", typeof(InvalidJsonException))] + [TestCase("1.5", typeof(InvalidProtocolBufferException))] + // Value is out of range + [TestCase("1e10", typeof(InvalidProtocolBufferException))] + [TestCase("2147483648", typeof(InvalidProtocolBufferException))] + [TestCase("-2147483649", typeof(InvalidProtocolBufferException))] + public void NumberToInt32_Invalid(string jsonValue, System.Type expectedExceptionType) + { + string json = "{ \"singleInt32\": " + jsonValue + "}"; + Assert.Throws(expectedExceptionType, () => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0U)] + [TestCase("1", 1U)] + [TestCase("4294967295", 4294967295U)] + public void NumberToUInt32_Valid(string jsonValue, uint expectedParsedValue) + { + string json = "{ \"singleUint32\": " + jsonValue + "}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleUint32); + } + + // Assume that anything non-bounds-related is covered in the Int32 case + [Test] + [TestCase("-1")] + [TestCase("4294967296")] + public void NumberToUInt32_Invalid(string jsonValue) + { + string json = "{ \"singleUint32\": " + jsonValue + "}"; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0L)] + [TestCase("1", 1L)] + [TestCase("-1", -1L)] + // long.MaxValue isn't actually representable as a double. This string value is the highest + // representable value which isn't greater than long.MaxValue. + [TestCase("9223372036854774784", 9223372036854774784)] + [TestCase("-9223372036854775808", -9223372036854775808)] + public void NumberToInt64_Valid(string jsonValue, long expectedParsedValue) + { + string json = "{ \"singleInt64\": " + jsonValue + "}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleInt64); + } + + // Assume that anything non-bounds-related is covered in the Int32 case + [Test] + [TestCase("9223372036854775808")] + // Theoretical bound would be -9223372036854775809, but when that is parsed to a double + // we end up with the exact value of long.MinValue due to lack of precision. The value here + // is the "next double down". + [TestCase("-9223372036854780000")] + public void NumberToInt64_Invalid(string jsonValue) + { + string json = "{ \"singleInt64\": " + jsonValue + "}"; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0UL)] + [TestCase("1", 1UL)] + // ulong.MaxValue isn't representable as a double. This value is the largest double within + // the range of ulong. + [TestCase("18446744073709549568", 18446744073709549568UL)] + public void NumberToUInt64_Valid(string jsonValue, ulong expectedParsedValue) + { + string json = "{ \"singleUint64\": " + jsonValue + "}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleUint64); + } + + // Assume that anything non-bounds-related is covered in the Int32 case + [Test] + [TestCase("-1")] + [TestCase("18446744073709551616")] + public void NumberToUInt64_Invalid(string jsonValue) + { + string json = "{ \"singleUint64\": " + jsonValue + "}"; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0d)] + [TestCase("1", 1d)] + [TestCase("1.000000", 1d)] + [TestCase("1.0000000000000000000000001", 1d)] // We don't notice that we haven't preserved the exact value + [TestCase("-1", -1d)] + [TestCase("1e1", 10d)] + [TestCase("1e01", 10d)] // Leading decimals are allowed in exponents + [TestCase("1E1", 10d)] // Either case is fine + [TestCase("-1e1", -10d)] + [TestCase("1.5e1", 15d)] + [TestCase("-1.5e1", -15d)] + [TestCase("15e-1", 1.5d)] + [TestCase("-15e-1", -1.5d)] + [TestCase("1.79769e308", 1.79769e308)] + [TestCase("-1.79769e308", -1.79769e308)] + public void NumberToDouble_Valid(string jsonValue, double expectedParsedValue) + { + string json = "{ \"singleDouble\": " + jsonValue + "}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleDouble); + } + + [Test] + [TestCase("1.7977e308")] + [TestCase("-1.7977e308")] + [TestCase("1e309")] + [TestCase("1,0")] + [TestCase("1.0.0")] + [TestCase("+1")] + [TestCase("00")] + [TestCase("--1")] + [TestCase("\u00BD")] // 1/2 as a single Unicode character. Just sanity checking... + public void NumberToDouble_Invalid(string jsonValue) + { + string json = "{ \"singleDouble\": " + jsonValue + "}"; + Assert.Throws<InvalidJsonException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0f)] + [TestCase("1", 1f)] + [TestCase("1.000000", 1f)] + [TestCase("-1", -1f)] + [TestCase("3.402823e38", 3.402823e38f)] + [TestCase("-3.402823e38", -3.402823e38f)] + [TestCase("1.5e1", 15f)] + [TestCase("15e-1", 1.5f)] + public void NumberToFloat_Valid(string jsonValue, float expectedParsedValue) + { + string json = "{ \"singleFloat\": " + jsonValue + "}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleFloat); + } + + [Test] + [TestCase("3.402824e38", typeof(InvalidProtocolBufferException))] + [TestCase("-3.402824e38", typeof(InvalidProtocolBufferException))] + [TestCase("1,0", typeof(InvalidJsonException))] + [TestCase("1.0.0", typeof(InvalidJsonException))] + [TestCase("+1", typeof(InvalidJsonException))] + [TestCase("00", typeof(InvalidJsonException))] + [TestCase("--1", typeof(InvalidJsonException))] + public void NumberToFloat_Invalid(string jsonValue, System.Type expectedExceptionType) + { + string json = "{ \"singleFloat\": " + jsonValue + "}"; + Assert.Throws(expectedExceptionType, () => TestAllTypes.Parser.ParseJson(json)); + } + + // The simplest way of testing that the value has parsed correctly is to reformat it, + // as we trust the formatting. In many cases that will give the same result as the input, + // so in those cases we accept an expectedFormatted value of null. Sometimes the results + // will be different though, due to a different number of digits being provided. + [Test] + // Z offset + [TestCase("2015-10-09T14:46:23.123456789Z", null)] + [TestCase("2015-10-09T14:46:23.123456Z", null)] + [TestCase("2015-10-09T14:46:23.123Z", null)] + [TestCase("2015-10-09T14:46:23Z", null)] + [TestCase("2015-10-09T14:46:23.123456000Z", "2015-10-09T14:46:23.123456Z")] + [TestCase("2015-10-09T14:46:23.1234560Z", "2015-10-09T14:46:23.123456Z")] + [TestCase("2015-10-09T14:46:23.123000000Z", "2015-10-09T14:46:23.123Z")] + [TestCase("2015-10-09T14:46:23.1230Z", "2015-10-09T14:46:23.123Z")] + [TestCase("2015-10-09T14:46:23.00Z", "2015-10-09T14:46:23Z")] + + // +00:00 offset + [TestCase("2015-10-09T14:46:23.123456789+00:00", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-09T14:46:23.123456+00:00", "2015-10-09T14:46:23.123456Z")] + [TestCase("2015-10-09T14:46:23.123+00:00", "2015-10-09T14:46:23.123Z")] + [TestCase("2015-10-09T14:46:23+00:00", "2015-10-09T14:46:23Z")] + [TestCase("2015-10-09T14:46:23.123456000+00:00", "2015-10-09T14:46:23.123456Z")] + [TestCase("2015-10-09T14:46:23.1234560+00:00", "2015-10-09T14:46:23.123456Z")] + [TestCase("2015-10-09T14:46:23.123000000+00:00", "2015-10-09T14:46:23.123Z")] + [TestCase("2015-10-09T14:46:23.1230+00:00", "2015-10-09T14:46:23.123Z")] + [TestCase("2015-10-09T14:46:23.00+00:00", "2015-10-09T14:46:23Z")] + + // Other offsets (assume by now that the subsecond handling is okay) + [TestCase("2015-10-09T15:46:23.123456789+01:00", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-09T13:46:23.123456789-01:00", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-09T15:16:23.123456789+00:30", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-09T14:16:23.123456789-00:30", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-09T16:31:23.123456789+01:45", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-09T13:01:23.123456789-01:45", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-10T08:46:23.123456789+18:00", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-08T20:46:23.123456789-18:00", "2015-10-09T14:46:23.123456789Z")] + + // Leap years and min/max + [TestCase("2016-02-29T14:46:23.123456789Z", null)] + [TestCase("2000-02-29T14:46:23.123456789Z", null)] + [TestCase("0001-01-01T00:00:00Z", null)] + [TestCase("9999-12-31T23:59:59.999999999Z", null)] + public void Timestamp_Valid(string jsonValue, string expectedFormatted) + { + expectedFormatted = expectedFormatted ?? jsonValue; + string json = WrapInQuotes(jsonValue); + var parsed = Timestamp.Parser.ParseJson(json); + Assert.AreEqual(WrapInQuotes(expectedFormatted), parsed.ToString()); + } + + [Test] + [TestCase("2015-10-09 14:46:23.123456789Z", Description = "No T between date and time")] + [TestCase("2015/10/09T14:46:23.123456789Z", Description = "Wrong date separators")] + [TestCase("2015-10-09T14.46.23.123456789Z", Description = "Wrong time separators")] + [TestCase("2015-10-09T14:46:23,123456789Z", Description = "Wrong fractional second separators (valid ISO-8601 though)")] + [TestCase(" 2015-10-09T14:46:23.123456789Z", Description = "Whitespace at start")] + [TestCase("2015-10-09T14:46:23.123456789Z ", Description = "Whitespace at end")] + [TestCase("2015-10-09T14:46:23.1234567890", Description = "Too many digits")] + [TestCase("2015-10-09T14:46:23.123456789", Description = "No offset")] + [TestCase("2015-13-09T14:46:23.123456789Z", Description = "Invalid month")] + [TestCase("2015-10-32T14:46:23.123456789Z", Description = "Invalid day")] + [TestCase("2015-10-09T24:00:00.000000000Z", Description = "Invalid hour (valid ISO-8601 though)")] + [TestCase("2015-10-09T14:60:23.123456789Z", Description = "Invalid minutes")] + [TestCase("2015-10-09T14:46:60.123456789Z", Description = "Invalid seconds")] + [TestCase("2015-10-09T14:46:23.123456789+18:01", Description = "Offset too large (positive)")] + [TestCase("2015-10-09T14:46:23.123456789-18:01", Description = "Offset too large (negative)")] + [TestCase("2015-10-09T14:46:23.123456789-00:00", Description = "Local offset (-00:00) makes no sense here")] + [TestCase("0001-01-01T00:00:00+00:01", Description = "Value before earliest when offset applied")] + [TestCase("9999-12-31T23:59:59.999999999-00:01", Description = "Value after latest when offset applied")] + [TestCase("2100-02-29T14:46:23.123456789Z", Description = "Feb 29th on a non-leap-year")] + public void Timestamp_Invalid(string jsonValue) + { + string json = WrapInQuotes(jsonValue); + Assert.Throws<InvalidProtocolBufferException>(() => Timestamp.Parser.ParseJson(json)); + } + + [Test] + public void StructValue_Null() + { + Assert.AreEqual(new Value { NullValue = 0 }, Value.Parser.ParseJson("null")); + } + + [Test] + public void StructValue_String() + { + Assert.AreEqual(new Value { StringValue = "hi" }, Value.Parser.ParseJson("\"hi\"")); + } + + [Test] + public void StructValue_Bool() + { + Assert.AreEqual(new Value { BoolValue = true }, Value.Parser.ParseJson("true")); + Assert.AreEqual(new Value { BoolValue = false }, Value.Parser.ParseJson("false")); + } + + [Test] + public void StructValue_List() + { + Assert.AreEqual(Value.ForList(Value.ForNumber(1), Value.ForString("x")), Value.Parser.ParseJson("[1, \"x\"]")); + } + + [Test] + public void ParseListValue() + { + Assert.AreEqual(new ListValue { Values = { Value.ForNumber(1), Value.ForString("x") } }, ListValue.Parser.ParseJson("[1, \"x\"]")); + } + + [Test] + public void StructValue_Struct() + { + Assert.AreEqual( + Value.ForStruct(new Struct { Fields = { { "x", Value.ForNumber(1) }, { "y", Value.ForString("z") } } }), + Value.Parser.ParseJson("{ \"x\": 1, \"y\": \"z\" }")); + } + + [Test] + public void ParseStruct() + { + Assert.AreEqual(new Struct { Fields = { { "x", Value.ForNumber(1) }, { "y", Value.ForString("z") } } }, + Struct.Parser.ParseJson("{ \"x\": 1, \"y\": \"z\" }")); + } + + // TODO for duration parsing: upper and lower bounds. + // +/- 315576000000 seconds + + [Test] + [TestCase("1.123456789s", null)] + [TestCase("1.123456s", null)] + [TestCase("1.123s", null)] + [TestCase("1.12300s", "1.123s")] + [TestCase("1.12345s", "1.123450s")] + [TestCase("1s", null)] + [TestCase("-1.123456789s", null)] + [TestCase("-1.123456s", null)] + [TestCase("-1.123s", null)] + [TestCase("-1s", null)] + [TestCase("0.123s", null)] + [TestCase("-0.123s", null)] + [TestCase("123456.123s", null)] + [TestCase("-123456.123s", null)] + // Upper and lower bounds + [TestCase("315576000000s", null)] + [TestCase("-315576000000s", null)] + public void Duration_Valid(string jsonValue, string expectedFormatted) + { + expectedFormatted = expectedFormatted ?? jsonValue; + string json = WrapInQuotes(jsonValue); + var parsed = Duration.Parser.ParseJson(json); + Assert.AreEqual(WrapInQuotes(expectedFormatted), parsed.ToString()); + } + + // The simplest way of testing that the value has parsed correctly is to reformat it, + // as we trust the formatting. In many cases that will give the same result as the input, + // so in those cases we accept an expectedFormatted value of null. Sometimes the results + // will be different though, due to a different number of digits being provided. + [Test] + [TestCase("1.1234567890s", Description = "Too many digits")] + [TestCase("1.123456789", Description = "No suffix")] + [TestCase("1.123456789ss", Description = "Too much suffix")] + [TestCase("1.123456789S", Description = "Upper case suffix")] + [TestCase("+1.123456789s", Description = "Leading +")] + [TestCase(".123456789s", Description = "No integer before the fraction")] + [TestCase("1,123456789s", Description = "Comma as decimal separator")] + [TestCase("1x1.123456789s", Description = "Non-digit in integer part")] + [TestCase("1.1x3456789s", Description = "Non-digit in fractional part")] + [TestCase(" 1.123456789s", Description = "Whitespace before fraction")] + [TestCase("1.123456789s ", Description = "Whitespace after value")] + [TestCase("01.123456789s", Description = "Leading zero (positive)")] + [TestCase("-01.123456789s", Description = "Leading zero (negative)")] + [TestCase("--0.123456789s", Description = "Double minus sign")] + // Violate upper/lower bounds in various ways + [TestCase("315576000001s", Description = "Integer part too large")] + [TestCase("3155760000000s", Description = "Integer part too long (positive)")] + [TestCase("-3155760000000s", Description = "Integer part too long (negative)")] + public void Duration_Invalid(string jsonValue) + { + string json = WrapInQuotes(jsonValue); + Assert.Throws<InvalidProtocolBufferException>(() => Duration.Parser.ParseJson(json)); + } + + // Not as many tests for field masks as I'd like; more to be added when we have more + // detailed specifications. + + [Test] + [TestCase("")] + [TestCase("foo", "foo")] + [TestCase("foo,bar", "foo", "bar")] + [TestCase("foo.bar", "foo.bar")] + [TestCase("fooBar", "foo_bar")] + [TestCase("fooBar.bazQux", "foo_bar.baz_qux")] + public void FieldMask_Valid(string jsonValue, params string[] expectedPaths) + { + string json = WrapInQuotes(jsonValue); + var parsed = FieldMask.Parser.ParseJson(json); + CollectionAssert.AreEqual(expectedPaths, parsed.Paths); + } + + [Test] + [TestCase("foo_bar")] + public void FieldMask_Invalid(string jsonValue) + { + string json = WrapInQuotes(jsonValue); + Assert.Throws<InvalidProtocolBufferException>(() => FieldMask.Parser.ParseJson(json)); + } + + [Test] + public void Any_RegularMessage() + { + var registry = TypeRegistry.FromMessages(TestAllTypes.Descriptor); + var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(TestAllTypes.Descriptor))); + var message = new TestAllTypes { SingleInt32 = 10, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } }; + var original = Any.Pack(message); + var json = formatter.Format(original); // This is tested in JsonFormatterTest + var parser = new JsonParser(new JsonParser.Settings(10, registry)); + Assert.AreEqual(original, parser.Parse<Any>(json)); + string valueFirstJson = "{ \"singleInt32\": 10, \"singleNestedMessage\": { \"bb\": 20 }, \"@type\": \"type.googleapis.com/protobuf_unittest.TestAllTypes\" }"; + Assert.AreEqual(original, parser.Parse<Any>(valueFirstJson)); + } + + [Test] + public void Any_CustomPrefix() + { + var registry = TypeRegistry.FromMessages(TestAllTypes.Descriptor); + var message = new TestAllTypes { SingleInt32 = 10 }; + var original = Any.Pack(message, "custom.prefix/middle-part"); + var parser = new JsonParser(new JsonParser.Settings(10, registry)); + string json = "{ \"@type\": \"custom.prefix/middle-part/protobuf_unittest.TestAllTypes\", \"singleInt32\": 10 }"; + Assert.AreEqual(original, parser.Parse<Any>(json)); + } + + [Test] + public void Any_UnknownType() + { + string json = "{ \"@type\": \"type.googleapis.com/bogus\" }"; + Assert.Throws<InvalidOperationException>(() => Any.Parser.ParseJson(json)); + } + + [Test] + public void Any_NoTypeUrl() + { + string json = "{ \"foo\": \"bar\" }"; + Assert.Throws<InvalidProtocolBufferException>(() => Any.Parser.ParseJson(json)); + } + + [Test] + public void Any_WellKnownType() + { + var registry = TypeRegistry.FromMessages(Timestamp.Descriptor); + var formatter = new JsonFormatter(new JsonFormatter.Settings(false, registry)); + var timestamp = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp(); + var original = Any.Pack(timestamp); + var json = formatter.Format(original); // This is tested in JsonFormatterTest + var parser = new JsonParser(new JsonParser.Settings(10, registry)); + Assert.AreEqual(original, parser.Parse<Any>(json)); + string valueFirstJson = "{ \"value\": \"1673-06-19T12:34:56Z\", \"@type\": \"type.googleapis.com/google.protobuf.Timestamp\" }"; + Assert.AreEqual(original, parser.Parse<Any>(valueFirstJson)); + } + + [Test] + public void Any_Nested() + { + var registry = TypeRegistry.FromMessages(TestWellKnownTypes.Descriptor, TestAllTypes.Descriptor); + var formatter = new JsonFormatter(new JsonFormatter.Settings(false, registry)); + var parser = new JsonParser(new JsonParser.Settings(10, registry)); + var doubleNestedMessage = new TestAllTypes { SingleInt32 = 20 }; + var nestedMessage = Any.Pack(doubleNestedMessage); + var message = new TestWellKnownTypes { AnyField = Any.Pack(nestedMessage) }; + var json = formatter.Format(message); + // Use the descriptor-based parser just for a change. + Assert.AreEqual(message, parser.Parse(json, TestWellKnownTypes.Descriptor)); + } + + [Test] + public void DataAfterObject() + { + string json = "{} 10"; + Assert.Throws<InvalidJsonException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + /// <summary> + /// JSON equivalent to <see cref="CodedInputStreamTest.MaliciousRecursion"/> + /// </summary> + [Test] + public void MaliciousRecursion() + { + string data64 = CodedInputStreamTest.MakeRecursiveMessage(64).ToString(); + string data65 = CodedInputStreamTest.MakeRecursiveMessage(65).ToString(); + + var parser64 = new JsonParser(new JsonParser.Settings(64)); + CodedInputStreamTest.AssertMessageDepth(parser64.Parse<TestRecursiveMessage>(data64), 64); + Assert.Throws<InvalidProtocolBufferException>(() => parser64.Parse<TestRecursiveMessage>(data65)); + + var parser63 = new JsonParser(new JsonParser.Settings(63)); + Assert.Throws<InvalidProtocolBufferException>(() => parser63.Parse<TestRecursiveMessage>(data64)); + } + + [Test] + [TestCase("AQI")] + [TestCase("_-==")] + public void Bytes_InvalidBase64(string badBase64) + { + string json = "{ \"singleBytes\": \"" + badBase64 + "\" }"; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("\"FOREIGN_BAR\"", ForeignEnum.ForeignBar)] + [TestCase("5", ForeignEnum.ForeignBar)] + [TestCase("100", (ForeignEnum)100)] + public void EnumValid(string value, ForeignEnum expectedValue) + { + string json = "{ \"singleForeignEnum\": " + value + " }"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(new TestAllTypes { SingleForeignEnum = expectedValue }, parsed); + } + + [Test] + [TestCase("\"NOT_A_VALID_VALUE\"")] + [TestCase("5.5")] + public void Enum_Invalid(string value) + { + string json = "{ \"singleForeignEnum\": " + value + " }"; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + public void OneofDuplicate_Invalid() + { + string json = "{ \"oneofString\": \"x\", \"oneofUint32\": 10 }"; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json)); + } + + /// <summary> + /// Various tests use strings which have quotes round them for parsing or as the result + /// of formatting, but without those quotes being specified in the tests (for the sake of readability). + /// This method simply returns the input, wrapped in double quotes. + /// </summary> + internal static string WrapInQuotes(string text) + { + return '"' + text + '"'; + } + } +}
\ No newline at end of file diff --git a/csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs b/csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs new file mode 100644 index 00000000..527ab336 --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs @@ -0,0 +1,408 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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 System; +using System.IO; + +namespace Google.Protobuf +{ + public class JsonTokenizerTest + { + [Test] + public void EmptyObjectValue() + { + AssertTokens("{}", JsonToken.StartObject, JsonToken.EndObject); + } + + [Test] + public void EmptyArrayValue() + { + AssertTokens("[]", JsonToken.StartArray, JsonToken.EndArray); + } + + [Test] + [TestCase("foo", "foo")] + [TestCase("tab\\t", "tab\t")] + [TestCase("line\\nfeed", "line\nfeed")] + [TestCase("carriage\\rreturn", "carriage\rreturn")] + [TestCase("back\\bspace", "back\bspace")] + [TestCase("form\\ffeed", "form\ffeed")] + [TestCase("escaped\\/slash", "escaped/slash")] + [TestCase("escaped\\\\backslash", "escaped\\backslash")] + [TestCase("escaped\\\"quote", "escaped\"quote")] + [TestCase("foo {}[] bar", "foo {}[] bar")] + [TestCase("foo\\u09aFbar", "foo\u09afbar")] // Digits, upper hex, lower hex + [TestCase("ab\ud800\udc00cd", "ab\ud800\udc00cd")] + [TestCase("ab\\ud800\\udc00cd", "ab\ud800\udc00cd")] + public void StringValue(string json, string expectedValue) + { + AssertTokensNoReplacement("\"" + json + "\"", JsonToken.Value(expectedValue)); + } + + // Valid surrogate pairs, with mixed escaping. These test cases can't be expressed + // using TestCase as they have no valid UTF-8 representation. + // It's unclear exactly how we should handle a mixture of escaped or not: that can't + // come from UTF-8 text, but could come from a .NET string. For the moment, + // treat it as valid in the obvious way. + [Test] + public void MixedSurrogatePairs() + { + string expected = "\ud800\udc00"; + AssertTokens("'\\ud800\udc00'", JsonToken.Value(expected)); + AssertTokens("'\ud800\\udc00'", JsonToken.Value(expected)); + } + + [Test] + public void ObjectDepth() + { + string json = "{ \"foo\": { \"x\": 1, \"y\": [ 0 ] } }"; + var tokenizer = JsonTokenizer.FromTextReader(new StringReader(json)); + // If we had more tests like this, I'd introduce a helper method... but for one test, it's not worth it. + Assert.AreEqual(0, tokenizer.ObjectDepth); + Assert.AreEqual(JsonToken.StartObject, tokenizer.Next()); + Assert.AreEqual(1, tokenizer.ObjectDepth); + Assert.AreEqual(JsonToken.Name("foo"), tokenizer.Next()); + Assert.AreEqual(1, tokenizer.ObjectDepth); + Assert.AreEqual(JsonToken.StartObject, tokenizer.Next()); + Assert.AreEqual(2, tokenizer.ObjectDepth); + Assert.AreEqual(JsonToken.Name("x"), tokenizer.Next()); + Assert.AreEqual(2, tokenizer.ObjectDepth); + Assert.AreEqual(JsonToken.Value(1), tokenizer.Next()); + Assert.AreEqual(2, tokenizer.ObjectDepth); + Assert.AreEqual(JsonToken.Name("y"), tokenizer.Next()); + Assert.AreEqual(2, tokenizer.ObjectDepth); + Assert.AreEqual(JsonToken.StartArray, tokenizer.Next()); + Assert.AreEqual(2, tokenizer.ObjectDepth); // Depth hasn't changed in array + Assert.AreEqual(JsonToken.Value(0), tokenizer.Next()); + Assert.AreEqual(2, tokenizer.ObjectDepth); + Assert.AreEqual(JsonToken.EndArray, tokenizer.Next()); + Assert.AreEqual(2, tokenizer.ObjectDepth); + Assert.AreEqual(JsonToken.EndObject, tokenizer.Next()); + Assert.AreEqual(1, tokenizer.ObjectDepth); + Assert.AreEqual(JsonToken.EndObject, tokenizer.Next()); + Assert.AreEqual(0, tokenizer.ObjectDepth); + Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next()); + Assert.AreEqual(0, tokenizer.ObjectDepth); + } + + [Test] + public void ObjectDepth_WithPushBack() + { + string json = "{}"; + var tokenizer = JsonTokenizer.FromTextReader(new StringReader(json)); + Assert.AreEqual(0, tokenizer.ObjectDepth); + var token = tokenizer.Next(); + Assert.AreEqual(1, tokenizer.ObjectDepth); + // When we push back a "start object", we should effectively be back to the previous depth. + tokenizer.PushBack(token); + Assert.AreEqual(0, tokenizer.ObjectDepth); + // Read the same token again, and get back to depth 1 + token = tokenizer.Next(); + Assert.AreEqual(1, tokenizer.ObjectDepth); + + // Now the same in reverse, with EndObject + token = tokenizer.Next(); + Assert.AreEqual(0, tokenizer.ObjectDepth); + tokenizer.PushBack(token); + Assert.AreEqual(1, tokenizer.ObjectDepth); + tokenizer.Next(); + Assert.AreEqual(0, tokenizer.ObjectDepth); + } + + [Test] + [TestCase("embedded tab\t")] + [TestCase("embedded CR\r")] + [TestCase("embedded LF\n")] + [TestCase("embedded bell\u0007")] + [TestCase("bad escape\\a")] + [TestCase("incomplete escape\\")] + [TestCase("incomplete Unicode escape\\u000")] + [TestCase("invalid Unicode escape\\u000H")] + // Surrogate pair handling, both in raw .NET strings and escaped. We only need + // to detect this in strings, as non-ASCII characters anywhere other than in strings + // will already lead to parsing errors. + [TestCase("\\ud800")] + [TestCase("\\udc00")] + [TestCase("\\ud800x")] + [TestCase("\\udc00x")] + [TestCase("\\udc00\\ud800y")] + public void InvalidStringValue(string json) + { + AssertThrowsAfter("\"" + json + "\""); + } + + // Tests for invalid strings that can't be expressed in attributes, + // as the constants can't be expressed as UTF-8 strings. + [Test] + public void InvalidSurrogatePairs() + { + AssertThrowsAfter("\"\ud800x\""); + AssertThrowsAfter("\"\udc00y\""); + AssertThrowsAfter("\"\udc00\ud800y\""); + } + + [Test] + [TestCase("0", 0)] + [TestCase("-0", 0)] // We don't distinguish between positive and negative 0 + [TestCase("1", 1)] + [TestCase("-1", -1)] + // From here on, assume leading sign is okay... + [TestCase("1.125", 1.125)] + [TestCase("1.0", 1)] + [TestCase("1e5", 100000)] + [TestCase("1e000000", 1)] // Weird, but not prohibited by the spec + [TestCase("1E5", 100000)] + [TestCase("1e+5", 100000)] + [TestCase("1E-5", 0.00001)] + [TestCase("123E-2", 1.23)] + [TestCase("123.45E3", 123450)] + [TestCase(" 1 ", 1)] + public void NumberValue(string json, double expectedValue) + { + AssertTokens(json, JsonToken.Value(expectedValue)); + } + + [Test] + [TestCase("00")] + [TestCase(".5")] + [TestCase("1.")] + [TestCase("1e")] + [TestCase("1e-")] + [TestCase("--")] + [TestCase("--1")] + [TestCase("-1.7977e308")] + [TestCase("1.7977e308")] + public void InvalidNumberValue(string json) + { + AssertThrowsAfter(json); + } + + [Test] + [TestCase("nul")] + [TestCase("nothing")] + [TestCase("truth")] + [TestCase("fALSEhood")] + public void InvalidLiterals(string json) + { + AssertThrowsAfter(json); + } + + [Test] + public void NullValue() + { + AssertTokens("null", JsonToken.Null); + } + + [Test] + public void TrueValue() + { + AssertTokens("true", JsonToken.True); + } + + [Test] + public void FalseValue() + { + AssertTokens("false", JsonToken.False); + } + + [Test] + public void SimpleObject() + { + AssertTokens("{'x': 'y'}", + JsonToken.StartObject, JsonToken.Name("x"), JsonToken.Value("y"), JsonToken.EndObject); + } + + [Test] + [TestCase("[10, 20", 3)] + [TestCase("[10,", 2)] + [TestCase("[10:20]", 2)] + [TestCase("[", 1)] + [TestCase("[,", 1)] + [TestCase("{", 1)] + [TestCase("{,", 1)] + [TestCase("{[", 1)] + [TestCase("{{", 1)] + [TestCase("{0", 1)] + [TestCase("{null", 1)] + [TestCase("{false", 1)] + [TestCase("{true", 1)] + [TestCase("}", 0)] + [TestCase("]", 0)] + [TestCase(",", 0)] + [TestCase("'foo' 'bar'", 1)] + [TestCase(":", 0)] + [TestCase("'foo", 0)] // Incomplete string + [TestCase("{ 'foo' }", 2)] + [TestCase("{ x:1", 1)] // Property names must be quoted + [TestCase("{]", 1)] + [TestCase("[}", 1)] + [TestCase("[1,", 2)] + [TestCase("{'x':0]", 3)] + [TestCase("{ 'foo': }", 2)] + [TestCase("{ 'foo':'bar', }", 3)] + public void InvalidStructure(string json, int expectedValidTokens) + { + // Note: we don't test that the earlier tokens are exactly as expected, + // partly because that's hard to parameterize. + var reader = new StringReader(json.Replace('\'', '"')); + var tokenizer = JsonTokenizer.FromTextReader(reader); + for (int i = 0; i < expectedValidTokens; i++) + { + Assert.IsNotNull(tokenizer.Next()); + } + Assert.Throws<InvalidJsonException>(() => tokenizer.Next()); + } + + [Test] + public void ArrayMixedType() + { + AssertTokens("[1, 'foo', null, false, true, [2], {'x':'y' }]", + JsonToken.StartArray, + JsonToken.Value(1), + JsonToken.Value("foo"), + JsonToken.Null, + JsonToken.False, + JsonToken.True, + JsonToken.StartArray, + JsonToken.Value(2), + JsonToken.EndArray, + JsonToken.StartObject, + JsonToken.Name("x"), + JsonToken.Value("y"), + JsonToken.EndObject, + JsonToken.EndArray); + } + + [Test] + public void ObjectMixedType() + { + AssertTokens(@"{'a': 1, 'b': 'bar', 'c': null, 'd': false, 'e': true, + 'f': [2], 'g': {'x':'y' }}", + JsonToken.StartObject, + JsonToken.Name("a"), + JsonToken.Value(1), + JsonToken.Name("b"), + JsonToken.Value("bar"), + JsonToken.Name("c"), + JsonToken.Null, + JsonToken.Name("d"), + JsonToken.False, + JsonToken.Name("e"), + JsonToken.True, + JsonToken.Name("f"), + JsonToken.StartArray, + JsonToken.Value(2), + JsonToken.EndArray, + JsonToken.Name("g"), + JsonToken.StartObject, + JsonToken.Name("x"), + JsonToken.Value("y"), + JsonToken.EndObject, + JsonToken.EndObject); + } + + [Test] + public void NextAfterEndDocumentThrows() + { + var tokenizer = JsonTokenizer.FromTextReader(new StringReader("null")); + Assert.AreEqual(JsonToken.Null, tokenizer.Next()); + Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next()); + Assert.Throws<InvalidOperationException>(() => tokenizer.Next()); + } + + [Test] + public void CanPushBackEndDocument() + { + var tokenizer = JsonTokenizer.FromTextReader(new StringReader("null")); + Assert.AreEqual(JsonToken.Null, tokenizer.Next()); + Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next()); + tokenizer.PushBack(JsonToken.EndDocument); + Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next()); + Assert.Throws<InvalidOperationException>(() => tokenizer.Next()); + } + + /// <summary> + /// Asserts that the specified JSON is tokenized into the given sequence of tokens. + /// All apostrophes are first converted to double quotes, allowing any tests + /// that don't need to check actual apostrophe handling to use apostrophes in the JSON, avoiding + /// messy string literal escaping. The "end document" token is not specified in the list of + /// expected tokens, but is implicit. + /// </summary> + private static void AssertTokens(string json, params JsonToken[] expectedTokens) + { + AssertTokensNoReplacement(json.Replace('\'', '"'), expectedTokens); + } + + /// <summary> + /// Asserts that the specified JSON is tokenized into the given sequence of tokens. + /// Unlike <see cref="AssertTokens(string, JsonToken[])"/>, this does not perform any character + /// replacement on the specified JSON, and should be used when the text contains apostrophes which + /// are expected to be used *as* apostrophes. The "end document" token is not specified in the list of + /// expected tokens, but is implicit. + /// </summary> + private static void AssertTokensNoReplacement(string json, params JsonToken[] expectedTokens) + { + var reader = new StringReader(json); + var tokenizer = JsonTokenizer.FromTextReader(reader); + for (int i = 0; i < expectedTokens.Length; i++) + { + var actualToken = tokenizer.Next(); + if (actualToken == JsonToken.EndDocument) + { + Assert.Fail("Expected {0} but reached end of token stream", expectedTokens[i]); + } + Assert.AreEqual(expectedTokens[i], actualToken); + } + var finalToken = tokenizer.Next(); + if (finalToken != JsonToken.EndDocument) + { + Assert.Fail("Expected token stream to be exhausted; received {0}", finalToken); + } + } + + private static void AssertThrowsAfter(string json, params JsonToken[] expectedTokens) + { + var reader = new StringReader(json); + var tokenizer = JsonTokenizer.FromTextReader(reader); + for (int i = 0; i < expectedTokens.Length; i++) + { + var actualToken = tokenizer.Next(); + if (actualToken == JsonToken.EndDocument) + { + Assert.Fail("Expected {0} but reached end of document", expectedTokens[i]); + } + Assert.AreEqual(expectedTokens[i], actualToken); + } + Assert.Throws<InvalidJsonException>(() => tokenizer.Next()); + } + } +} diff --git a/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs b/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs index 5f3aba1a..52d5a676 100644 --- a/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs +++ b/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs @@ -46,7 +46,7 @@ namespace Google.Protobuf.Reflection [Test] public void FileDescriptor() { - FileDescriptor file = UnittestProto3.Descriptor; + FileDescriptor file = UnittestProto3Reflection.Descriptor; Assert.AreEqual("google/protobuf/unittest_proto3.proto", file.Name); Assert.AreEqual("protobuf_unittest", file.Package); @@ -56,14 +56,15 @@ namespace Google.Protobuf.Reflection // unittest.proto doesn't have any public imports, but unittest_import.proto does. Assert.AreEqual(0, file.PublicDependencies.Count); - Assert.AreEqual(1, UnittestImportProto3.Descriptor.PublicDependencies.Count); - Assert.AreEqual(UnittestImportPublicProto3.Descriptor, UnittestImportProto3.Descriptor.PublicDependencies[0]); + Assert.AreEqual(1, UnittestImportProto3Reflection.Descriptor.PublicDependencies.Count); + Assert.AreEqual(UnittestImportPublicProto3Reflection.Descriptor, UnittestImportProto3Reflection.Descriptor.PublicDependencies[0]); Assert.AreEqual(1, file.Dependencies.Count); - Assert.AreEqual(UnittestImportProto3.Descriptor, file.Dependencies[0]); + Assert.AreEqual(UnittestImportProto3Reflection.Descriptor, file.Dependencies[0]); MessageDescriptor messageType = TestAllTypes.Descriptor; - Assert.AreSame(typeof(TestAllTypes), messageType.GeneratedType); + Assert.AreSame(typeof(TestAllTypes), messageType.ClrType); + Assert.AreSame(TestAllTypes.Parser, messageType.Parser); Assert.AreEqual(messageType, file.MessageTypes[0]); Assert.AreEqual(messageType, file.FindTypeByName<MessageDescriptor>("TestAllTypes")); Assert.Null(file.FindTypeByName<MessageDescriptor>("NoSuchType")); @@ -76,8 +77,8 @@ namespace Google.Protobuf.Reflection Assert.AreEqual(file.EnumTypes[0], file.FindTypeByName<EnumDescriptor>("ForeignEnum")); Assert.Null(file.FindTypeByName<EnumDescriptor>("NoSuchType")); Assert.Null(file.FindTypeByName<EnumDescriptor>("protobuf_unittest.ForeignEnum")); - Assert.AreEqual(1, UnittestImportProto3.Descriptor.EnumTypes.Count); - Assert.AreEqual("ImportEnum", UnittestImportProto3.Descriptor.EnumTypes[0].Name); + Assert.AreEqual(1, UnittestImportProto3Reflection.Descriptor.EnumTypes.Count); + Assert.AreEqual("ImportEnum", UnittestImportProto3Reflection.Descriptor.EnumTypes[0].Name); for (int i = 0; i < file.EnumTypes.Count; i++) { Assert.AreEqual(i, file.EnumTypes[i].Index); @@ -94,7 +95,7 @@ namespace Google.Protobuf.Reflection Assert.AreEqual("TestAllTypes", messageType.Name); Assert.AreEqual("protobuf_unittest.TestAllTypes", messageType.FullName); - Assert.AreEqual(UnittestProto3.Descriptor, messageType.File); + Assert.AreEqual(UnittestProto3Reflection.Descriptor, messageType.File); Assert.IsNull(messageType.ContainingType); Assert.IsNull(messageType.Proto.Options); @@ -102,7 +103,7 @@ namespace Google.Protobuf.Reflection Assert.AreEqual("NestedMessage", nestedType.Name); Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedMessage", nestedType.FullName); - Assert.AreEqual(UnittestProto3.Descriptor, nestedType.File); + Assert.AreEqual(UnittestProto3Reflection.Descriptor, nestedType.File); Assert.AreEqual(messageType, nestedType.ContainingType); FieldDescriptor field = messageType.Fields.InDeclarationOrder()[0]; @@ -146,7 +147,7 @@ namespace Google.Protobuf.Reflection primitiveField.FullName); Assert.AreEqual(1, primitiveField.FieldNumber); Assert.AreEqual(messageType, primitiveField.ContainingType); - Assert.AreEqual(UnittestProto3.Descriptor, primitiveField.File); + Assert.AreEqual(UnittestProto3Reflection.Descriptor, primitiveField.File); Assert.AreEqual(FieldType.Int32, primitiveField.FieldType); Assert.IsNull(primitiveField.Proto.Options); @@ -175,26 +176,26 @@ namespace Google.Protobuf.Reflection 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 = UnittestProto3.Descriptor.FindTypeByName<EnumDescriptor>("ForeignEnum"); + EnumDescriptor enumType = UnittestProto3Reflection.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(UnittestProto3.Descriptor, enumType.File); + Assert.AreEqual(UnittestProto3Reflection.Descriptor, enumType.File); Assert.Null(enumType.ContainingType); Assert.Null(enumType.Proto.Options); Assert.AreEqual("NestedEnum", nestedType.Name); Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedEnum", nestedType.FullName); - Assert.AreEqual(UnittestProto3.Descriptor, nestedType.File); + Assert.AreEqual(UnittestProto3Reflection.Descriptor, nestedType.File); Assert.AreEqual(TestAllTypes.Descriptor, nestedType.ContainingType); EnumValueDescriptor value = enumType.FindValueByName("FOREIGN_FOO"); Assert.AreEqual(value, enumType.Values[1]); Assert.AreEqual("FOREIGN_FOO", value.Name); Assert.AreEqual(4, value.Number); - Assert.AreEqual((int) ForeignEnum.FOREIGN_FOO, value.Number); + Assert.AreEqual((int) ForeignEnum.ForeignFoo, value.Number); Assert.AreEqual(value, enumType.FindValueByNumber(4)); Assert.Null(enumType.FindValueByName("NO_SUCH_VALUE")); for (int i = 0; i < enumType.Values.Count; i++) @@ -226,17 +227,12 @@ namespace Google.Protobuf.Reflection } [Test] - public void ConstructionWithoutGeneratedCodeInfo() + public void MapEntryMessageDescriptor() { - var data = UnittestIssues.Descriptor.Proto.ToByteArray(); - var newDescriptor = Google.Protobuf.Reflection.FileDescriptor.InternalBuildGeneratedFileFrom(data, new Reflection.FileDescriptor[] { }, null); - - // We should still be able to get at a field... - var messageDescriptor = newDescriptor.FindTypeByName<MessageDescriptor>("ItemField"); - var fieldDescriptor = messageDescriptor.FindFieldByName("item"); - // But there shouldn't be an accessor (or a generated type for the message) - Assert.IsNull(fieldDescriptor.Accessor); - Assert.IsNull(messageDescriptor.GeneratedType); + var descriptor = MapWellKnownTypes.Descriptor.NestedTypes[0]; + Assert.IsNull(descriptor.Parser); + Assert.IsNull(descriptor.ClrType); + Assert.IsNull(descriptor.Fields[1].Accessor); } // From TestFieldOrdering: @@ -257,6 +253,7 @@ namespace Google.Protobuf.Reflection public void DescriptorProtoFileDescriptor() { var descriptor = Google.Protobuf.Reflection.FileDescriptor.DescriptorProtoFileDescriptor; + Assert.AreEqual("google/protobuf/descriptor.proto", descriptor.Name); } } } diff --git a/csharp/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs b/csharp/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs index 936e41c6..a488af30 100644 --- a/csharp/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs +++ b/csharp/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs @@ -128,7 +128,7 @@ namespace Google.Protobuf.Reflection fields[TestAllTypes.SingleInt32FieldNumber].Accessor.SetValue(message, 500); fields[TestAllTypes.SingleStringFieldNumber].Accessor.SetValue(message, "It's a string"); fields[TestAllTypes.SingleBytesFieldNumber].Accessor.SetValue(message, ByteString.CopyFrom(99, 98, 97)); - fields[TestAllTypes.SingleForeignEnumFieldNumber].Accessor.SetValue(message, ForeignEnum.FOREIGN_FOO); + fields[TestAllTypes.SingleForeignEnumFieldNumber].Accessor.SetValue(message, ForeignEnum.ForeignFoo); fields[TestAllTypes.SingleForeignMessageFieldNumber].Accessor.SetValue(message, new ForeignMessage { C = 12345 }); fields[TestAllTypes.SingleDoubleFieldNumber].Accessor.SetValue(message, 20150701.5); @@ -138,7 +138,7 @@ namespace Google.Protobuf.Reflection SingleInt32 = 500, SingleString = "It's a string", SingleBytes = ByteString.CopyFrom(99, 98, 97), - SingleForeignEnum = ForeignEnum.FOREIGN_FOO, + SingleForeignEnum = ForeignEnum.ForeignFoo, SingleForeignMessage = new ForeignMessage { C = 12345 }, SingleDouble = 20150701.5 }; diff --git a/csharp/src/Google.Protobuf.Test/Reflection/TypeRegistryTest.cs b/csharp/src/Google.Protobuf.Test/Reflection/TypeRegistryTest.cs new file mode 100644 index 00000000..5be7ca23 --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/Reflection/TypeRegistryTest.cs @@ -0,0 +1,94 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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.Protobuf.TestProtos; +using Google.Protobuf.WellKnownTypes; +using NUnit.Framework; + +namespace Google.Protobuf.Reflection +{ + public class TypeRegistryTest + { + // Most of our tests use messages. Simple test that we really can use files... + [Test] + public void CreateWithFileDescriptor() + { + var registry = TypeRegistry.FromFiles(DurationReflection.Descriptor, StructReflection.Descriptor); + AssertDescriptorPresent(registry, Duration.Descriptor); + AssertDescriptorPresent(registry, ListValue.Descriptor); + AssertDescriptorAbsent(registry, Timestamp.Descriptor); + } + + [Test] + public void TypesFromSameFile() + { + // Just for kicks, let's start with a nested type + var registry = TypeRegistry.FromMessages(TestAllTypes.Types.NestedMessage.Descriptor); + // Top-level... + AssertDescriptorPresent(registry, TestFieldOrderings.Descriptor); + // ... and nested (not the same as the original NestedMessage!) + AssertDescriptorPresent(registry, TestFieldOrderings.Types.NestedMessage.Descriptor); + } + + [Test] + public void DependenciesAreIncluded() + { + var registry = TypeRegistry.FromMessages(TestAllTypes.Descriptor); + // Direct dependencies + AssertDescriptorPresent(registry, ImportMessage.Descriptor); + // Public dependencies + AssertDescriptorPresent(registry, PublicImportMessage.Descriptor); + } + + [Test] + public void DuplicateFiles() + { + // Duplicates via dependencies and simply via repetition + var registry = TypeRegistry.FromFiles( + UnittestProto3Reflection.Descriptor, UnittestImportProto3Reflection.Descriptor, + TimestampReflection.Descriptor, TimestampReflection.Descriptor); + AssertDescriptorPresent(registry, TestAllTypes.Descriptor); + AssertDescriptorPresent(registry, ImportMessage.Descriptor); + AssertDescriptorPresent(registry, Timestamp.Descriptor); + } + + private static void AssertDescriptorPresent(TypeRegistry registry, MessageDescriptor descriptor) + { + Assert.AreSame(descriptor, registry.Find(descriptor.FullName)); + } + + private static void AssertDescriptorAbsent(TypeRegistry registry, MessageDescriptor descriptor) + { + Assert.IsNull(registry.Find(descriptor.FullName)); + } + } +} diff --git a/csharp/src/Google.Protobuf.Test/SampleMessages.cs b/csharp/src/Google.Protobuf.Test/SampleMessages.cs index 8a9c7f86..ffa4e2a7 100644 --- a/csharp/src/Google.Protobuf.Test/SampleMessages.cs +++ b/csharp/src/Google.Protobuf.Test/SampleMessages.cs @@ -54,13 +54,13 @@ namespace Google.Protobuf SingleFixed32 = 23, SingleFixed64 = 1234567890123, SingleFloat = 12.25f, - SingleForeignEnum = ForeignEnum.FOREIGN_BAR, + SingleForeignEnum = ForeignEnum.ForeignBar, SingleForeignMessage = new ForeignMessage { C = 10 }, - SingleImportEnum = ImportEnum.IMPORT_BAZ, + SingleImportEnum = ImportEnum.ImportBaz, SingleImportMessage = new ImportMessage { D = 20 }, SingleInt32 = 100, SingleInt64 = 3210987654321, - SingleNestedEnum = TestAllTypes.Types.NestedEnum.FOO, + SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 }, SinglePublicImportMessage = new PublicImportMessage { E = 54 }, SingleSfixed32 = -123, @@ -76,13 +76,13 @@ namespace Google.Protobuf RepeatedFixed32 = { UInt32.MaxValue, 23 }, RepeatedFixed64 = { UInt64.MaxValue, 1234567890123 }, RepeatedFloat = { 100f, 12.25f }, - RepeatedForeignEnum = { ForeignEnum.FOREIGN_FOO, ForeignEnum.FOREIGN_BAR }, + RepeatedForeignEnum = { ForeignEnum.ForeignFoo, ForeignEnum.ForeignBar }, RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } }, - RepeatedImportEnum = { ImportEnum.IMPORT_BAZ, ImportEnum.IMPORT_ENUM_UNSPECIFIED }, + RepeatedImportEnum = { ImportEnum.ImportBaz, ImportEnum.Unspecified }, RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } }, RepeatedInt32 = { 100, 200 }, RepeatedInt64 = { 3210987654321, Int64.MaxValue }, - RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.NEG }, + RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg }, RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 35 }, new TestAllTypes.Types.NestedMessage { Bb = 10 } }, RepeatedPublicImportMessage = { new PublicImportMessage { E = 54 }, new PublicImportMessage { E = -1 } }, RepeatedSfixed32 = { -123, 123 }, @@ -92,8 +92,8 @@ namespace Google.Protobuf RepeatedString = { "foo", "bar" }, RepeatedUint32 = { UInt32.MaxValue, UInt32.MinValue }, RepeatedUint64 = { UInt64.MaxValue, UInt32.MinValue }, - OneofString = "Oneof string" + OneofString = "Oneof string" }; } } -} +}
\ No newline at end of file diff --git a/csharp/src/Google.Protobuf.Test/TestCornerCases.cs b/csharp/src/Google.Protobuf.Test/TestCornerCases.cs index 03fa1855..248f5fa9 100644 --- a/csharp/src/Google.Protobuf.Test/TestCornerCases.cs +++ b/csharp/src/Google.Protobuf.Test/TestCornerCases.cs @@ -43,8 +43,8 @@ namespace Google.Protobuf NegativeEnumMessage msg = new NegativeEnumMessage
{
Value = NegativeEnum.MinusOne,
- Values = { NegativeEnum.NEGATIVE_ENUM_ZERO, NegativeEnum.MinusOne, NegativeEnum.FiveBelow },
- PackedValues = { NegativeEnum.NEGATIVE_ENUM_ZERO, NegativeEnum.MinusOne, NegativeEnum.FiveBelow }
+ Values = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow },
+ PackedValues = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow }
};
Assert.AreEqual(58, msg.CalculateSize());
diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/ForeignMessagePartial.cs b/csharp/src/Google.Protobuf.Test/TestProtos/ForeignMessagePartial.cs new file mode 100644 index 00000000..5663a699 --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/TestProtos/ForeignMessagePartial.cs @@ -0,0 +1,45 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2016 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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 + +namespace Google.Protobuf.TestProtos +{ + /// <summary> + /// A message with custom diagnostics (to test that they work). + /// </summary> + public partial class ForeignMessage : ICustomDiagnosticMessage + { + public string ToDiagnosticString() + { + return $"{{ \"c\": {C}, \"@cInHex\": \"{C:x}\" }}"; + } + } +} diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs index e3991bc8..3ba4a2b6 100644 --- a/csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs +++ b/csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs @@ -11,7 +11,7 @@ namespace Google.Protobuf.TestProtos { /// <summary>Holder for reflection information generated from google/protobuf/map_unittest_proto3.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public static partial class MapUnittestProto3 { + public static partial class MapUnittestProto3Reflection { #region Descriptor /// <summary>File descriptor for google/protobuf/map_unittest_proto3.proto</summary> @@ -20,7 +20,7 @@ namespace Google.Protobuf.TestProtos { } private static pbr::FileDescriptor descriptor; - static MapUnittestProto3() { + static MapUnittestProto3Reflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cilnb29nbGUvcHJvdG9idWYvbWFwX3VuaXR0ZXN0X3Byb3RvMy5wcm90bxIR", @@ -147,16 +147,16 @@ namespace Google.Protobuf.TestProtos { "dmFsdWUYAiABKAU6AjgBKj8KB01hcEVudW0SEAoMTUFQX0VOVU1fRk9PEAAS", "EAoMTUFQX0VOVU1fQkFSEAESEAoMTUFQX0VOVU1fQkFaEAJCIPgBAaoCGkdv", "b2dsZS5Qcm90b2J1Zi5UZXN0UHJvdG9zYgZwcm90bzM=")); - descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, - new pbr::FileDescriptor[] { global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor, }, - new pbr::GeneratedCodeInfo(new[] {typeof(global::Google.Protobuf.TestProtos.MapEnum), }, new pbr::GeneratedCodeInfo[] { - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestMap), new[]{ "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapStringString", "MapInt32Bytes", "MapInt32Enum", "MapInt32ForeignMessage" }, null, null, new pbr::GeneratedCodeInfo[] { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestMapSubmessage), new[]{ "TestMap" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestMessageMap), new[]{ "MapInt32Message" }, null, null, new pbr::GeneratedCodeInfo[] { null, }), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestSameTypeMap), new[]{ "Map1", "Map2" }, null, null, new pbr::GeneratedCodeInfo[] { null, null, }), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestArenaMap), new[]{ "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapInt32Enum", "MapInt32ForeignMessage" }, null, null, new pbr::GeneratedCodeInfo[] { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType), new[]{ "Type" }, null, new[]{ typeof(global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType.Types.Type) }, new pbr::GeneratedCodeInfo[] { null, }), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.MessageContainingMapCalledEntry), new[]{ "Entry" }, null, null, new pbr::GeneratedCodeInfo[] { null, }) + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Protobuf.TestProtos.MapEnum), }, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestMap), global::Google.Protobuf.TestProtos.TestMap.Parser, new[]{ "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapStringString", "MapInt32Bytes", "MapInt32Enum", "MapInt32ForeignMessage" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestMapSubmessage), global::Google.Protobuf.TestProtos.TestMapSubmessage.Parser, new[]{ "TestMap" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestMessageMap), global::Google.Protobuf.TestProtos.TestMessageMap.Parser, new[]{ "MapInt32Message" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, }), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestSameTypeMap), global::Google.Protobuf.TestProtos.TestSameTypeMap.Parser, new[]{ "Map1", "Map2" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, null, }), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestArenaMap), global::Google.Protobuf.TestProtos.TestArenaMap.Parser, new[]{ "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapInt32Enum", "MapInt32ForeignMessage" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType), global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType.Parser, new[]{ "Type" }, null, new[]{ typeof(global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType.Types.Type) }, new pbr::GeneratedClrTypeInfo[] { null, }), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.MessageContainingMapCalledEntry), global::Google.Protobuf.TestProtos.MessageContainingMapCalledEntry.Parser, new[]{ "Entry" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, }) })); } #endregion @@ -164,9 +164,9 @@ namespace Google.Protobuf.TestProtos { } #region Enums public enum MapEnum { - MAP_ENUM_FOO = 0, - MAP_ENUM_BAR = 1, - MAP_ENUM_BAZ = 2, + [pbr::OriginalName("MAP_ENUM_FOO")] Foo = 0, + [pbr::OriginalName("MAP_ENUM_BAR")] Bar = 1, + [pbr::OriginalName("MAP_ENUM_BAZ")] Baz = 2, } #endregion @@ -181,7 +181,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestMap> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.MapUnittestProto3.Descriptor.MessageTypes[0]; } + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -425,7 +425,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -580,7 +580,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestMapSubmessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.MapUnittestProto3.Descriptor.MessageTypes[1]; } + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -633,7 +633,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -689,7 +689,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestMessageMap> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.MapUnittestProto3.Descriptor.MessageTypes[2]; } + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -741,7 +741,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -787,7 +787,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestSameTypeMap> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.MapUnittestProto3.Descriptor.MessageTypes[3]; } + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[3]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -851,7 +851,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -901,7 +901,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestArenaMap> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.MapUnittestProto3.Descriptor.MessageTypes[4]; } + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[4]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -1121,7 +1121,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -1266,7 +1266,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<MessageContainingEnumCalledType> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.MapUnittestProto3.Descriptor.MessageTypes[5]; } + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[5]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -1318,7 +1318,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -1358,7 +1358,7 @@ namespace Google.Protobuf.TestProtos { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { public enum Type { - TYPE_FOO = 0, + [pbr::OriginalName("TYPE_FOO")] Foo = 0, } } @@ -1375,7 +1375,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<MessageContainingMapCalledEntry> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.MapUnittestProto3.Descriptor.MessageTypes[6]; } + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[6]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -1427,7 +1427,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportProto3.cs index a55c66e0..263e17c0 100644 --- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportProto3.cs +++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportProto3.cs @@ -11,7 +11,7 @@ namespace Google.Protobuf.TestProtos { /// <summary>Holder for reflection information generated from google/protobuf/unittest_import_proto3.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public static partial class UnittestImportProto3 { + public static partial class UnittestImportProto3Reflection { #region Descriptor /// <summary>File descriptor for google/protobuf/unittest_import_proto3.proto</summary> @@ -20,7 +20,7 @@ namespace Google.Protobuf.TestProtos { } private static pbr::FileDescriptor descriptor; - static UnittestImportProto3() { + static UnittestImportProto3Reflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cixnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0X3Byb3RvMy5wcm90", @@ -31,10 +31,10 @@ namespace Google.Protobuf.TestProtos { "UhAIEg4KCklNUE9SVF9CQVoQCUI8Chhjb20uZ29vZ2xlLnByb3RvYnVmLnRl", "c3RIAfgBAaoCGkdvb2dsZS5Qcm90b2J1Zi5UZXN0UHJvdG9zUABiBnByb3Rv", "Mw==")); - descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, - new pbr::FileDescriptor[] { global::Google.Protobuf.TestProtos.UnittestImportPublicProto3.Descriptor, }, - new pbr::GeneratedCodeInfo(new[] {typeof(global::Google.Protobuf.TestProtos.ImportEnum), }, new pbr::GeneratedCodeInfo[] { - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.ImportMessage), new[]{ "D" }, null, null, null) + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::Google.Protobuf.TestProtos.UnittestImportPublicProto3Reflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Protobuf.TestProtos.ImportEnum), }, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.ImportMessage), global::Google.Protobuf.TestProtos.ImportMessage.Parser, new[]{ "D" }, null, null, null) })); } #endregion @@ -42,10 +42,10 @@ namespace Google.Protobuf.TestProtos { } #region Enums public enum ImportEnum { - IMPORT_ENUM_UNSPECIFIED = 0, - IMPORT_FOO = 7, - IMPORT_BAR = 8, - IMPORT_BAZ = 9, + [pbr::OriginalName("IMPORT_ENUM_UNSPECIFIED")] Unspecified = 0, + [pbr::OriginalName("IMPORT_FOO")] ImportFoo = 7, + [pbr::OriginalName("IMPORT_BAR")] ImportBar = 8, + [pbr::OriginalName("IMPORT_BAZ")] ImportBaz = 9, } #endregion @@ -57,7 +57,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<ImportMessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestImportProto3.Descriptor.MessageTypes[0]; } + get { return global::Google.Protobuf.TestProtos.UnittestImportProto3Reflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -110,7 +110,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportPublicProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportPublicProto3.cs index 81696d70..b471a8cf 100644 --- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportPublicProto3.cs +++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportPublicProto3.cs @@ -11,7 +11,7 @@ namespace Google.Protobuf.TestProtos { /// <summary>Holder for reflection information generated from google/protobuf/unittest_import_public_proto3.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public static partial class UnittestImportPublicProto3 { + public static partial class UnittestImportPublicProto3Reflection { #region Descriptor /// <summary>File descriptor for google/protobuf/unittest_import_public_proto3.proto</summary> @@ -20,17 +20,17 @@ namespace Google.Protobuf.TestProtos { } private static pbr::FileDescriptor descriptor; - static UnittestImportPublicProto3() { + static UnittestImportPublicProto3Reflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjNnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0X3B1YmxpY19wcm90", "bzMucHJvdG8SGHByb3RvYnVmX3VuaXR0ZXN0X2ltcG9ydCIgChNQdWJsaWNJ", "bXBvcnRNZXNzYWdlEgkKAWUYASABKAVCNwoYY29tLmdvb2dsZS5wcm90b2J1", "Zi50ZXN0qgIaR29vZ2xlLlByb3RvYnVmLlRlc3RQcm90b3NiBnByb3RvMw==")); - descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, - new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.PublicImportMessage), new[]{ "E" }, null, null, null) + new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.PublicImportMessage), global::Google.Protobuf.TestProtos.PublicImportMessage.Parser, new[]{ "E" }, null, null, null) })); } #endregion @@ -43,7 +43,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<PublicImportMessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestImportPublicProto3.Descriptor.MessageTypes[0]; } + get { return global::Google.Protobuf.TestProtos.UnittestImportPublicProto3Reflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -96,7 +96,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs index addec057..7d4451b0 100644 --- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs +++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs @@ -11,7 +11,7 @@ namespace UnitTest.Issues.TestProtos { /// <summary>Holder for reflection information generated from unittest_issues.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public static partial class UnittestIssues { + public static partial class UnittestIssuesReflection { #region Descriptor /// <summary>File descriptor for unittest_issues.proto</summary> @@ -20,7 +20,7 @@ namespace UnitTest.Issues.TestProtos { } private static pbr::FileDescriptor descriptor; - static UnittestIssues() { + static UnittestIssuesReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChV1bml0dGVzdF9pc3N1ZXMucHJvdG8SD3VuaXR0ZXN0X2lzc3VlcyInCghJ", @@ -42,20 +42,23 @@ namespace UnitTest.Issues.TestProtos { "CgtwbGFpbl9pbnQzMhgEIAEoBRITCglvMV9zdHJpbmcYAiABKAlIABISCghv", "MV9pbnQzMhgFIAEoBUgAEhQKDHBsYWluX3N0cmluZxgBIAEoCRISCghvMl9p", "bnQzMhgGIAEoBUgBEhMKCW8yX3N0cmluZxgDIAEoCUgBQgQKAm8xQgQKAm8y", - "KlUKDE5lZ2F0aXZlRW51bRIWChJORUdBVElWRV9FTlVNX1pFUk8QABIWCglG", - "aXZlQmVsb3cQ+///////////ARIVCghNaW51c09uZRD///////////8BKi4K", - "DkRlcHJlY2F0ZWRFbnVtEhMKD0RFUFJFQ0FURURfWkVSTxAAEgcKA29uZRAB", - "Qh9IAaoCGlVuaXRUZXN0Lklzc3Vlcy5UZXN0UHJvdG9zYgZwcm90bzM=")); - descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + "IksKDFRlc3RKc29uTmFtZRIMCgRuYW1lGAEgASgJEhkKC2Rlc2NyaXB0aW9u", + "GAIgASgJUgRkZXNjEhIKBGd1aWQYAyABKAlSBGV4aWQqVQoMTmVnYXRpdmVF", + "bnVtEhYKEk5FR0FUSVZFX0VOVU1fWkVSTxAAEhYKCUZpdmVCZWxvdxD7////", + "//////8BEhUKCE1pbnVzT25lEP///////////wEqLgoORGVwcmVjYXRlZEVu", + "dW0SEwoPREVQUkVDQVRFRF9aRVJPEAASBwoDb25lEAFCH0gBqgIaVW5pdFRl", + "c3QuSXNzdWVzLlRlc3RQcm90b3NiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, - new pbr::GeneratedCodeInfo(new[] {typeof(global::UnitTest.Issues.TestProtos.NegativeEnum), typeof(global::UnitTest.Issues.TestProtos.DeprecatedEnum), }, new pbr::GeneratedCodeInfo[] { - new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307), null, null, null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce), null, null, null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Types.NestedTwice), null, null, null, null)})}), - new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.NegativeEnumMessage), new[]{ "Value", "Values", "PackedValues" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.DeprecatedChild), null, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.DeprecatedFieldsMessage), new[]{ "PrimitiveValue", "PrimitiveArray", "MessageValue", "MessageArray", "EnumValue", "EnumArray" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.ItemField), new[]{ "Item" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.ReservedNames), new[]{ "Types_", "Descriptor_" }, null, null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.ReservedNames.Types.SomeNestedType), null, null, null, null)}), - new pbr::GeneratedCodeInfo(typeof(global::UnitTest.Issues.TestProtos.TestJsonFieldOrdering), new[]{ "PlainInt32", "O1String", "O1Int32", "PlainString", "O2Int32", "O2String" }, new[]{ "O1", "O2" }, null, null) + new pbr::GeneratedClrTypeInfo(new[] {typeof(global::UnitTest.Issues.TestProtos.NegativeEnum), typeof(global::UnitTest.Issues.TestProtos.DeprecatedEnum), }, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307), global::UnitTest.Issues.TestProtos.Issue307.Parser, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce), global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Parser, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Types.NestedTwice), global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Types.NestedTwice.Parser, null, null, null, null)})}), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.NegativeEnumMessage), global::UnitTest.Issues.TestProtos.NegativeEnumMessage.Parser, new[]{ "Value", "Values", "PackedValues" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.DeprecatedChild), global::UnitTest.Issues.TestProtos.DeprecatedChild.Parser, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.DeprecatedFieldsMessage), global::UnitTest.Issues.TestProtos.DeprecatedFieldsMessage.Parser, new[]{ "PrimitiveValue", "PrimitiveArray", "MessageValue", "MessageArray", "EnumValue", "EnumArray" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ItemField), global::UnitTest.Issues.TestProtos.ItemField.Parser, new[]{ "Item" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ReservedNames), global::UnitTest.Issues.TestProtos.ReservedNames.Parser, new[]{ "Types_", "Descriptor_" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ReservedNames.Types.SomeNestedType), global::UnitTest.Issues.TestProtos.ReservedNames.Types.SomeNestedType.Parser, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.TestJsonFieldOrdering), global::UnitTest.Issues.TestProtos.TestJsonFieldOrdering.Parser, new[]{ "PlainInt32", "O1String", "O1Int32", "PlainString", "O2Int32", "O2String" }, new[]{ "O1", "O2" }, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.TestJsonName), global::UnitTest.Issues.TestProtos.TestJsonName.Parser, new[]{ "Name", "Description", "Guid" }, null, null, null) })); } #endregion @@ -63,14 +66,14 @@ namespace UnitTest.Issues.TestProtos { } #region Enums public enum NegativeEnum { - NEGATIVE_ENUM_ZERO = 0, - FiveBelow = -5, - MinusOne = -1, + [pbr::OriginalName("NEGATIVE_ENUM_ZERO")] Zero = 0, + [pbr::OriginalName("FiveBelow")] FiveBelow = -5, + [pbr::OriginalName("MinusOne")] MinusOne = -1, } public enum DeprecatedEnum { - DEPRECATED_ZERO = 0, - one = 1, + [pbr::OriginalName("DEPRECATED_ZERO")] DeprecatedZero = 0, + [pbr::OriginalName("one")] One = 1, } #endregion @@ -86,7 +89,7 @@ namespace UnitTest.Issues.TestProtos { public static pb::MessageParser<Issue307> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::UnitTest.Issues.TestProtos.UnittestIssues.Descriptor.MessageTypes[0]; } + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -126,7 +129,7 @@ namespace UnitTest.Issues.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -204,7 +207,7 @@ namespace UnitTest.Issues.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -282,7 +285,7 @@ namespace UnitTest.Issues.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -328,7 +331,7 @@ namespace UnitTest.Issues.TestProtos { public static pb::MessageParser<NegativeEnumMessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::UnitTest.Issues.TestProtos.UnittestIssues.Descriptor.MessageTypes[1]; } + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -353,7 +356,7 @@ namespace UnitTest.Issues.TestProtos { /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 1; - private global::UnitTest.Issues.TestProtos.NegativeEnum value_ = global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO; + private global::UnitTest.Issues.TestProtos.NegativeEnum value_ = 0; public global::UnitTest.Issues.TestProtos.NegativeEnum Value { get { return value_; } set { @@ -398,18 +401,18 @@ namespace UnitTest.Issues.TestProtos { public override int GetHashCode() { int hash = 1; - if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO) hash ^= Value.GetHashCode(); + if (Value != 0) hash ^= Value.GetHashCode(); hash ^= values_.GetHashCode(); hash ^= packedValues_.GetHashCode(); return hash; } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { - if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO) { + if (Value != 0) { output.WriteRawTag(8); output.WriteEnum((int) Value); } @@ -419,7 +422,7 @@ namespace UnitTest.Issues.TestProtos { public int CalculateSize() { int size = 0; - if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO) { + if (Value != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Value); } size += values_.CalculateSize(_repeated_values_codec); @@ -431,7 +434,7 @@ namespace UnitTest.Issues.TestProtos { if (other == null) { return; } - if (other.Value != global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO) { + if (other.Value != 0) { Value = other.Value; } values_.Add(other.values_); @@ -471,7 +474,7 @@ namespace UnitTest.Issues.TestProtos { public static pb::MessageParser<DeprecatedChild> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::UnitTest.Issues.TestProtos.UnittestIssues.Descriptor.MessageTypes[2]; } + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -511,7 +514,7 @@ namespace UnitTest.Issues.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -547,7 +550,7 @@ namespace UnitTest.Issues.TestProtos { public static pb::MessageParser<DeprecatedFieldsMessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::UnitTest.Issues.TestProtos.UnittestIssues.Descriptor.MessageTypes[3]; } + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[3]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -617,7 +620,7 @@ namespace UnitTest.Issues.TestProtos { /// <summary>Field number for the "EnumValue" field.</summary> public const int EnumValueFieldNumber = 5; - private global::UnitTest.Issues.TestProtos.DeprecatedEnum enumValue_ = global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO; + private global::UnitTest.Issues.TestProtos.DeprecatedEnum enumValue_ = 0; [global::System.ObsoleteAttribute()] public global::UnitTest.Issues.TestProtos.DeprecatedEnum EnumValue { get { return enumValue_; } @@ -662,13 +665,13 @@ namespace UnitTest.Issues.TestProtos { hash ^= primitiveArray_.GetHashCode(); if (messageValue_ != null) hash ^= MessageValue.GetHashCode(); hash ^= messageArray_.GetHashCode(); - if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO) hash ^= EnumValue.GetHashCode(); + if (EnumValue != 0) hash ^= EnumValue.GetHashCode(); hash ^= enumArray_.GetHashCode(); return hash; } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -682,7 +685,7 @@ namespace UnitTest.Issues.TestProtos { output.WriteMessage(MessageValue); } messageArray_.WriteTo(output, _repeated_messageArray_codec); - if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO) { + if (EnumValue != 0) { output.WriteRawTag(40); output.WriteEnum((int) EnumValue); } @@ -699,7 +702,7 @@ namespace UnitTest.Issues.TestProtos { size += 1 + pb::CodedOutputStream.ComputeMessageSize(MessageValue); } size += messageArray_.CalculateSize(_repeated_messageArray_codec); - if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO) { + if (EnumValue != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) EnumValue); } size += enumArray_.CalculateSize(_repeated_enumArray_codec); @@ -721,7 +724,7 @@ namespace UnitTest.Issues.TestProtos { MessageValue.MergeFrom(other.MessageValue); } messageArray_.Add(other.messageArray_); - if (other.EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO) { + if (other.EnumValue != 0) { EnumValue = other.EnumValue; } enumArray_.Add(other.enumArray_); @@ -778,7 +781,7 @@ namespace UnitTest.Issues.TestProtos { public static pb::MessageParser<ItemField> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::UnitTest.Issues.TestProtos.UnittestIssues.Descriptor.MessageTypes[4]; } + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[4]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -831,7 +834,7 @@ namespace UnitTest.Issues.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -881,7 +884,7 @@ namespace UnitTest.Issues.TestProtos { public static pb::MessageParser<ReservedNames> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::UnitTest.Issues.TestProtos.UnittestIssues.Descriptor.MessageTypes[5]; } + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[5]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -947,7 +950,7 @@ namespace UnitTest.Issues.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -1056,7 +1059,7 @@ namespace UnitTest.Issues.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -1109,7 +1112,7 @@ namespace UnitTest.Issues.TestProtos { public static pb::MessageParser<TestJsonFieldOrdering> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::UnitTest.Issues.TestProtos.UnittestIssues.Descriptor.MessageTypes[6]; } + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[6]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -1164,7 +1167,7 @@ namespace UnitTest.Issues.TestProtos { public string O1String { get { return o1Case_ == O1OneofCase.O1String ? (string) o1_ : ""; } set { - o1_ = pb::Preconditions.CheckNotNull(value, "value"); + o1_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); o1Case_ = O1OneofCase.O1String; } } @@ -1185,7 +1188,7 @@ namespace UnitTest.Issues.TestProtos { public string PlainString { get { return plainString_; } set { - plainString_ = pb::Preconditions.CheckNotNull(value, "value"); + plainString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } @@ -1204,7 +1207,7 @@ namespace UnitTest.Issues.TestProtos { public string O2String { get { return o2Case_ == O2OneofCase.O2String ? (string) o2_ : ""; } set { - o2_ = pb::Preconditions.CheckNotNull(value, "value"); + o2_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); o2Case_ = O2OneofCase.O2String; } } @@ -1260,6 +1263,8 @@ namespace UnitTest.Issues.TestProtos { if (PlainString != other.PlainString) return false; if (O2Int32 != other.O2Int32) return false; if (O2String != other.O2String) return false; + if (O1Case != other.O1Case) return false; + if (O2Case != other.O2Case) return false; return true; } @@ -1271,11 +1276,13 @@ namespace UnitTest.Issues.TestProtos { if (PlainString.Length != 0) hash ^= PlainString.GetHashCode(); if (o2Case_ == O2OneofCase.O2Int32) hash ^= O2Int32.GetHashCode(); if (o2Case_ == O2OneofCase.O2String) hash ^= O2String.GetHashCode(); + hash ^= (int) o1Case_; + hash ^= (int) o2Case_; return hash; } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -1395,6 +1402,166 @@ namespace UnitTest.Issues.TestProtos { } + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class TestJsonName : pb::IMessage<TestJsonName> { + private static readonly pb::MessageParser<TestJsonName> _parser = new pb::MessageParser<TestJsonName>(() => new TestJsonName()); + public static pb::MessageParser<TestJsonName> Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[7]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public TestJsonName() { + OnConstruction(); + } + + partial void OnConstruction(); + + public TestJsonName(TestJsonName other) : this() { + name_ = other.name_; + description_ = other.description_; + guid_ = other.guid_; + } + + public TestJsonName Clone() { + return new TestJsonName(this); + } + + /// <summary>Field number for the "name" field.</summary> + public const int NameFieldNumber = 1; + private string name_ = ""; + /// <summary> + /// Message for testing the effects for of the json_name option + /// </summary> + public string Name { + get { return name_; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// <summary>Field number for the "description" field.</summary> + public const int DescriptionFieldNumber = 2; + private string description_ = ""; + public string Description { + get { return description_; } + set { + description_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// <summary>Field number for the "guid" field.</summary> + public const int GuidFieldNumber = 3; + private string guid_ = ""; + public string Guid { + get { return guid_; } + set { + guid_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + public override bool Equals(object other) { + return Equals(other as TestJsonName); + } + + public bool Equals(TestJsonName other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (Description != other.Description) return false; + if (Guid != other.Guid) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (Description.Length != 0) hash ^= Description.GetHashCode(); + if (Guid.Length != 0) hash ^= Guid.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (Description.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Description); + } + if (Guid.Length != 0) { + output.WriteRawTag(26); + output.WriteString(Guid); + } + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (Description.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Description); + } + if (Guid.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Guid); + } + return size; + } + + public void MergeFrom(TestJsonName other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + if (other.Description.Length != 0) { + Description = other.Description; + } + if (other.Guid.Length != 0) { + Guid = other.Guid; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + Description = input.ReadString(); + break; + } + case 26: { + Guid = input.ReadString(); + break; + } + } + } + } + + } + #endregion } diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs index 0c7b5279..b8d159bb 100644 --- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs +++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs @@ -11,7 +11,7 @@ namespace Google.Protobuf.TestProtos { /// <summary>Holder for reflection information generated from google/protobuf/unittest_proto3.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public static partial class UnittestProto3 { + public static partial class UnittestProto3Reflection { #region Descriptor /// <summary>File descriptor for google/protobuf/unittest_proto3.proto</summary> @@ -20,7 +20,7 @@ namespace Google.Protobuf.TestProtos { } private static pbr::FileDescriptor descriptor; - static UnittestProto3() { + static UnittestProto3Reflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiVnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfcHJvdG8zLnByb3RvEhFwcm90", @@ -150,42 +150,42 @@ namespace Google.Protobuf.TestProtos { "HS5wcm90b2J1Zl91bml0dGVzdC5CYXJSZXF1ZXN0Gh4ucHJvdG9idWZfdW5p", "dHRlc3QuQmFyUmVzcG9uc2VCOkINVW5pdHRlc3RQcm90b0gBgAEBiAEBkAEB", "+AEBqgIaR29vZ2xlLlByb3RvYnVmLlRlc3RQcm90b3NiBnByb3RvMw==")); - descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, - new pbr::FileDescriptor[] { global::Google.Protobuf.TestProtos.UnittestImportProto3.Descriptor, }, - new pbr::GeneratedCodeInfo(new[] {typeof(global::Google.Protobuf.TestProtos.ForeignEnum), typeof(global::Google.Protobuf.TestProtos.TestEnumWithDupValue), typeof(global::Google.Protobuf.TestProtos.TestSparseEnum), }, new pbr::GeneratedCodeInfo[] { - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestAllTypes), new[]{ "SingleInt32", "SingleInt64", "SingleUint32", "SingleUint64", "SingleSint32", "SingleSint64", "SingleFixed32", "SingleFixed64", "SingleSfixed32", "SingleSfixed64", "SingleFloat", "SingleDouble", "SingleBool", "SingleString", "SingleBytes", "SingleNestedMessage", "SingleForeignMessage", "SingleImportMessage", "SingleNestedEnum", "SingleForeignEnum", "SingleImportEnum", "SinglePublicImportMessage", "RepeatedInt32", "RepeatedInt64", "RepeatedUint32", "RepeatedUint64", "RepeatedSint32", "RepeatedSint64", "RepeatedFixed32", "RepeatedFixed64", "RepeatedSfixed32", "RepeatedSfixed64", "RepeatedFloat", "RepeatedDouble", "RepeatedBool", "RepeatedString", "RepeatedBytes", "RepeatedNestedMessage", "RepeatedForeignMessage", "RepeatedImportMessage", "RepeatedNestedEnum", "RepeatedForeignEnum", "RepeatedImportEnum", "RepeatedPublicImportMessage", "OneofUint32", "OneofNestedMessage", "OneofString", "OneofBytes" }, new[]{ "OneofField" }, new[]{ typeof(global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum) }, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedMessage), new[]{ "Bb" }, null, null, null)}), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.NestedTestAllTypes), new[]{ "Child", "Payload", "RepeatedChild" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestDeprecatedFields), new[]{ "DeprecatedInt32" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.ForeignMessage), new[]{ "C" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestReservedFields), null, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestForeignNested), new[]{ "ForeignNested" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestReallyLargeTagNumber), new[]{ "A", "Bb" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestRecursiveMessage), new[]{ "A", "I" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestMutualRecursionA), new[]{ "Bb" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestMutualRecursionB), new[]{ "A", "OptionalInt32" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestCamelCaseFieldNames), new[]{ "PrimitiveField", "StringField", "EnumField", "MessageField", "RepeatedPrimitiveField", "RepeatedStringField", "RepeatedEnumField", "RepeatedMessageField" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestFieldOrderings), new[]{ "MyString", "MyInt", "MyFloat", "SingleNestedMessage" }, null, null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestFieldOrderings.Types.NestedMessage), new[]{ "Oo", "Bb" }, null, null, null)}), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.SparseEnumMessage), new[]{ "SparseEnum" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.OneString), new[]{ "Data" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.MoreString), new[]{ "Data" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.OneBytes), new[]{ "Data" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.MoreBytes), new[]{ "Data" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.Int32Message), new[]{ "Data" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.Uint32Message), new[]{ "Data" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.Int64Message), new[]{ "Data" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.Uint64Message), new[]{ "Data" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.BoolMessage), new[]{ "Data" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestOneof), new[]{ "FooInt", "FooString", "FooMessage" }, new[]{ "Foo" }, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestPackedTypes), new[]{ "PackedInt32", "PackedInt64", "PackedUint32", "PackedUint64", "PackedSint32", "PackedSint64", "PackedFixed32", "PackedFixed64", "PackedSfixed32", "PackedSfixed64", "PackedFloat", "PackedDouble", "PackedBool", "PackedEnum" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestUnpackedTypes), new[]{ "UnpackedInt32", "UnpackedInt64", "UnpackedUint32", "UnpackedUint64", "UnpackedSint32", "UnpackedSint64", "UnpackedFixed32", "UnpackedFixed64", "UnpackedSfixed32", "UnpackedSfixed64", "UnpackedFloat", "UnpackedDouble", "UnpackedBool", "UnpackedEnum" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestRepeatedScalarDifferentTagSizes), new[]{ "RepeatedFixed32", "RepeatedInt32", "RepeatedFixed64", "RepeatedInt64", "RepeatedFloat", "RepeatedUint64" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestCommentInjectionMessage), new[]{ "A" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.FooRequest), null, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.FooResponse), null, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.FooClientMessage), null, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.FooServerMessage), null, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.BarRequest), null, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.BarResponse), null, null, null, null) + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::Google.Protobuf.TestProtos.UnittestImportProto3Reflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Protobuf.TestProtos.ForeignEnum), typeof(global::Google.Protobuf.TestProtos.TestEnumWithDupValue), typeof(global::Google.Protobuf.TestProtos.TestSparseEnum), }, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestAllTypes), global::Google.Protobuf.TestProtos.TestAllTypes.Parser, new[]{ "SingleInt32", "SingleInt64", "SingleUint32", "SingleUint64", "SingleSint32", "SingleSint64", "SingleFixed32", "SingleFixed64", "SingleSfixed32", "SingleSfixed64", "SingleFloat", "SingleDouble", "SingleBool", "SingleString", "SingleBytes", "SingleNestedMessage", "SingleForeignMessage", "SingleImportMessage", "SingleNestedEnum", "SingleForeignEnum", "SingleImportEnum", "SinglePublicImportMessage", "RepeatedInt32", "RepeatedInt64", "RepeatedUint32", "RepeatedUint64", "RepeatedSint32", "RepeatedSint64", "RepeatedFixed32", "RepeatedFixed64", "RepeatedSfixed32", "RepeatedSfixed64", "RepeatedFloat", "RepeatedDouble", "RepeatedBool", "RepeatedString", "RepeatedBytes", "RepeatedNestedMessage", "RepeatedForeignMessage", "RepeatedImportMessage", "RepeatedNestedEnum", "RepeatedForeignEnum", "RepeatedImportEnum", "RepeatedPublicImportMessage", "OneofUint32", "OneofNestedMessage", "OneofString", "OneofBytes" }, new[]{ "OneofField" }, new[]{ typeof(global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum) }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedMessage), global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedMessage.Parser, new[]{ "Bb" }, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.NestedTestAllTypes), global::Google.Protobuf.TestProtos.NestedTestAllTypes.Parser, new[]{ "Child", "Payload", "RepeatedChild" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestDeprecatedFields), global::Google.Protobuf.TestProtos.TestDeprecatedFields.Parser, new[]{ "DeprecatedInt32" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.ForeignMessage), global::Google.Protobuf.TestProtos.ForeignMessage.Parser, new[]{ "C" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestReservedFields), global::Google.Protobuf.TestProtos.TestReservedFields.Parser, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestForeignNested), global::Google.Protobuf.TestProtos.TestForeignNested.Parser, new[]{ "ForeignNested" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestReallyLargeTagNumber), global::Google.Protobuf.TestProtos.TestReallyLargeTagNumber.Parser, new[]{ "A", "Bb" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestRecursiveMessage), global::Google.Protobuf.TestProtos.TestRecursiveMessage.Parser, new[]{ "A", "I" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestMutualRecursionA), global::Google.Protobuf.TestProtos.TestMutualRecursionA.Parser, new[]{ "Bb" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestMutualRecursionB), global::Google.Protobuf.TestProtos.TestMutualRecursionB.Parser, new[]{ "A", "OptionalInt32" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestCamelCaseFieldNames), global::Google.Protobuf.TestProtos.TestCamelCaseFieldNames.Parser, new[]{ "PrimitiveField", "StringField", "EnumField", "MessageField", "RepeatedPrimitiveField", "RepeatedStringField", "RepeatedEnumField", "RepeatedMessageField" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestFieldOrderings), global::Google.Protobuf.TestProtos.TestFieldOrderings.Parser, new[]{ "MyString", "MyInt", "MyFloat", "SingleNestedMessage" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestFieldOrderings.Types.NestedMessage), global::Google.Protobuf.TestProtos.TestFieldOrderings.Types.NestedMessage.Parser, new[]{ "Oo", "Bb" }, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.SparseEnumMessage), global::Google.Protobuf.TestProtos.SparseEnumMessage.Parser, new[]{ "SparseEnum" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.OneString), global::Google.Protobuf.TestProtos.OneString.Parser, new[]{ "Data" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.MoreString), global::Google.Protobuf.TestProtos.MoreString.Parser, new[]{ "Data" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.OneBytes), global::Google.Protobuf.TestProtos.OneBytes.Parser, new[]{ "Data" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.MoreBytes), global::Google.Protobuf.TestProtos.MoreBytes.Parser, new[]{ "Data" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Int32Message), global::Google.Protobuf.TestProtos.Int32Message.Parser, new[]{ "Data" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Uint32Message), global::Google.Protobuf.TestProtos.Uint32Message.Parser, new[]{ "Data" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Int64Message), global::Google.Protobuf.TestProtos.Int64Message.Parser, new[]{ "Data" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Uint64Message), global::Google.Protobuf.TestProtos.Uint64Message.Parser, new[]{ "Data" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.BoolMessage), global::Google.Protobuf.TestProtos.BoolMessage.Parser, new[]{ "Data" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestOneof), global::Google.Protobuf.TestProtos.TestOneof.Parser, new[]{ "FooInt", "FooString", "FooMessage" }, new[]{ "Foo" }, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestPackedTypes), global::Google.Protobuf.TestProtos.TestPackedTypes.Parser, new[]{ "PackedInt32", "PackedInt64", "PackedUint32", "PackedUint64", "PackedSint32", "PackedSint64", "PackedFixed32", "PackedFixed64", "PackedSfixed32", "PackedSfixed64", "PackedFloat", "PackedDouble", "PackedBool", "PackedEnum" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestUnpackedTypes), global::Google.Protobuf.TestProtos.TestUnpackedTypes.Parser, new[]{ "UnpackedInt32", "UnpackedInt64", "UnpackedUint32", "UnpackedUint64", "UnpackedSint32", "UnpackedSint64", "UnpackedFixed32", "UnpackedFixed64", "UnpackedSfixed32", "UnpackedSfixed64", "UnpackedFloat", "UnpackedDouble", "UnpackedBool", "UnpackedEnum" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestRepeatedScalarDifferentTagSizes), global::Google.Protobuf.TestProtos.TestRepeatedScalarDifferentTagSizes.Parser, new[]{ "RepeatedFixed32", "RepeatedInt32", "RepeatedFixed64", "RepeatedInt64", "RepeatedFloat", "RepeatedUint64" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestCommentInjectionMessage), global::Google.Protobuf.TestProtos.TestCommentInjectionMessage.Parser, new[]{ "A" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.FooRequest), global::Google.Protobuf.TestProtos.FooRequest.Parser, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.FooResponse), global::Google.Protobuf.TestProtos.FooResponse.Parser, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.FooClientMessage), global::Google.Protobuf.TestProtos.FooClientMessage.Parser, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.FooServerMessage), global::Google.Protobuf.TestProtos.FooServerMessage.Parser, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.BarRequest), global::Google.Protobuf.TestProtos.BarRequest.Parser, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.BarResponse), global::Google.Protobuf.TestProtos.BarResponse.Parser, null, null, null, null) })); } #endregion @@ -193,39 +193,39 @@ namespace Google.Protobuf.TestProtos { } #region Enums public enum ForeignEnum { - FOREIGN_UNSPECIFIED = 0, - FOREIGN_FOO = 4, - FOREIGN_BAR = 5, - FOREIGN_BAZ = 6, + [pbr::OriginalName("FOREIGN_UNSPECIFIED")] ForeignUnspecified = 0, + [pbr::OriginalName("FOREIGN_FOO")] ForeignFoo = 4, + [pbr::OriginalName("FOREIGN_BAR")] ForeignBar = 5, + [pbr::OriginalName("FOREIGN_BAZ")] ForeignBaz = 6, } /// <summary> /// Test an enum that has multiple values with the same number. /// </summary> public enum TestEnumWithDupValue { - TEST_ENUM_WITH_DUP_VALUE_UNSPECIFIED = 0, - FOO1 = 1, - BAR1 = 2, - BAZ = 3, - FOO2 = 1, - BAR2 = 2, + [pbr::OriginalName("TEST_ENUM_WITH_DUP_VALUE_UNSPECIFIED")] Unspecified = 0, + [pbr::OriginalName("FOO1")] Foo1 = 1, + [pbr::OriginalName("BAR1")] Bar1 = 2, + [pbr::OriginalName("BAZ")] Baz = 3, + [pbr::OriginalName("FOO2")] Foo2 = 1, + [pbr::OriginalName("BAR2")] Bar2 = 2, } /// <summary> /// Test an enum with large, unordered values. /// </summary> public enum TestSparseEnum { - TEST_SPARSE_ENUM_UNSPECIFIED = 0, - SPARSE_A = 123, - SPARSE_B = 62374, - SPARSE_C = 12589234, - SPARSE_D = -15, - SPARSE_E = -53452, + [pbr::OriginalName("TEST_SPARSE_ENUM_UNSPECIFIED")] Unspecified = 0, + [pbr::OriginalName("SPARSE_A")] SparseA = 123, + [pbr::OriginalName("SPARSE_B")] SparseB = 62374, + [pbr::OriginalName("SPARSE_C")] SparseC = 12589234, + [pbr::OriginalName("SPARSE_D")] SparseD = -15, + [pbr::OriginalName("SPARSE_E")] SparseE = -53452, /// <summary> /// In proto3, value 0 must be the first one specified /// SPARSE_F = 0; /// </summary> - SPARSE_G = 2, + [pbr::OriginalName("SPARSE_G")] SparseG = 2, } #endregion @@ -241,7 +241,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestAllTypes> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[0]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -459,7 +459,7 @@ namespace Google.Protobuf.TestProtos { public string SingleString { get { return singleString_; } set { - singleString_ = pb::Preconditions.CheckNotNull(value, "value"); + singleString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } @@ -469,7 +469,7 @@ namespace Google.Protobuf.TestProtos { public pb::ByteString SingleBytes { get { return singleBytes_; } set { - singleBytes_ = pb::Preconditions.CheckNotNull(value, "value"); + singleBytes_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } @@ -505,7 +505,7 @@ namespace Google.Protobuf.TestProtos { /// <summary>Field number for the "single_nested_enum" field.</summary> public const int SingleNestedEnumFieldNumber = 21; - private global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum singleNestedEnum_ = global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED; + private global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum singleNestedEnum_ = 0; public global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum SingleNestedEnum { get { return singleNestedEnum_; } set { @@ -515,7 +515,7 @@ namespace Google.Protobuf.TestProtos { /// <summary>Field number for the "single_foreign_enum" field.</summary> public const int SingleForeignEnumFieldNumber = 22; - private global::Google.Protobuf.TestProtos.ForeignEnum singleForeignEnum_ = global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED; + private global::Google.Protobuf.TestProtos.ForeignEnum singleForeignEnum_ = 0; public global::Google.Protobuf.TestProtos.ForeignEnum SingleForeignEnum { get { return singleForeignEnum_; } set { @@ -525,7 +525,7 @@ namespace Google.Protobuf.TestProtos { /// <summary>Field number for the "single_import_enum" field.</summary> public const int SingleImportEnumFieldNumber = 23; - private global::Google.Protobuf.TestProtos.ImportEnum singleImportEnum_ = global::Google.Protobuf.TestProtos.ImportEnum.IMPORT_ENUM_UNSPECIFIED; + private global::Google.Protobuf.TestProtos.ImportEnum singleImportEnum_ = 0; public global::Google.Protobuf.TestProtos.ImportEnum SingleImportEnum { get { return singleImportEnum_; } set { @@ -775,7 +775,7 @@ namespace Google.Protobuf.TestProtos { public string OneofString { get { return oneofFieldCase_ == OneofFieldOneofCase.OneofString ? (string) oneofField_ : ""; } set { - oneofField_ = pb::Preconditions.CheckNotNull(value, "value"); + oneofField_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); oneofFieldCase_ = OneofFieldOneofCase.OneofString; } } @@ -785,7 +785,7 @@ namespace Google.Protobuf.TestProtos { public pb::ByteString OneofBytes { get { return oneofFieldCase_ == OneofFieldOneofCase.OneofBytes ? (pb::ByteString) oneofField_ : pb::ByteString.Empty; } set { - oneofField_ = pb::Preconditions.CheckNotNull(value, "value"); + oneofField_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); oneofFieldCase_ = OneofFieldOneofCase.OneofBytes; } } @@ -868,6 +868,7 @@ namespace Google.Protobuf.TestProtos { if (!object.Equals(OneofNestedMessage, other.OneofNestedMessage)) return false; if (OneofString != other.OneofString) return false; if (OneofBytes != other.OneofBytes) return false; + if (OneofFieldCase != other.OneofFieldCase) return false; return true; } @@ -891,9 +892,9 @@ namespace Google.Protobuf.TestProtos { if (singleNestedMessage_ != null) hash ^= SingleNestedMessage.GetHashCode(); if (singleForeignMessage_ != null) hash ^= SingleForeignMessage.GetHashCode(); if (singleImportMessage_ != null) hash ^= SingleImportMessage.GetHashCode(); - if (SingleNestedEnum != global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED) hash ^= SingleNestedEnum.GetHashCode(); - if (SingleForeignEnum != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) hash ^= SingleForeignEnum.GetHashCode(); - if (SingleImportEnum != global::Google.Protobuf.TestProtos.ImportEnum.IMPORT_ENUM_UNSPECIFIED) hash ^= SingleImportEnum.GetHashCode(); + if (SingleNestedEnum != 0) hash ^= SingleNestedEnum.GetHashCode(); + if (SingleForeignEnum != 0) hash ^= SingleForeignEnum.GetHashCode(); + if (SingleImportEnum != 0) hash ^= SingleImportEnum.GetHashCode(); if (singlePublicImportMessage_ != null) hash ^= SinglePublicImportMessage.GetHashCode(); hash ^= repeatedInt32_.GetHashCode(); hash ^= repeatedInt64_.GetHashCode(); @@ -921,11 +922,12 @@ namespace Google.Protobuf.TestProtos { if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) hash ^= OneofNestedMessage.GetHashCode(); if (oneofFieldCase_ == OneofFieldOneofCase.OneofString) hash ^= OneofString.GetHashCode(); if (oneofFieldCase_ == OneofFieldOneofCase.OneofBytes) hash ^= OneofBytes.GetHashCode(); + hash ^= (int) oneofFieldCase_; return hash; } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -1001,15 +1003,15 @@ namespace Google.Protobuf.TestProtos { output.WriteRawTag(162, 1); output.WriteMessage(SingleImportMessage); } - if (SingleNestedEnum != global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED) { + if (SingleNestedEnum != 0) { output.WriteRawTag(168, 1); output.WriteEnum((int) SingleNestedEnum); } - if (SingleForeignEnum != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { + if (SingleForeignEnum != 0) { output.WriteRawTag(176, 1); output.WriteEnum((int) SingleForeignEnum); } - if (SingleImportEnum != global::Google.Protobuf.TestProtos.ImportEnum.IMPORT_ENUM_UNSPECIFIED) { + if (SingleImportEnum != 0) { output.WriteRawTag(184, 1); output.WriteEnum((int) SingleImportEnum); } @@ -1113,13 +1115,13 @@ namespace Google.Protobuf.TestProtos { if (singleImportMessage_ != null) { size += 2 + pb::CodedOutputStream.ComputeMessageSize(SingleImportMessage); } - if (SingleNestedEnum != global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED) { + if (SingleNestedEnum != 0) { size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) SingleNestedEnum); } - if (SingleForeignEnum != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { + if (SingleForeignEnum != 0) { size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) SingleForeignEnum); } - if (SingleImportEnum != global::Google.Protobuf.TestProtos.ImportEnum.IMPORT_ENUM_UNSPECIFIED) { + if (SingleImportEnum != 0) { size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) SingleImportEnum); } if (singlePublicImportMessage_ != null) { @@ -1229,13 +1231,13 @@ namespace Google.Protobuf.TestProtos { } SingleImportMessage.MergeFrom(other.SingleImportMessage); } - if (other.SingleNestedEnum != global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED) { + if (other.SingleNestedEnum != 0) { SingleNestedEnum = other.SingleNestedEnum; } - if (other.SingleForeignEnum != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { + if (other.SingleForeignEnum != 0) { SingleForeignEnum = other.SingleForeignEnum; } - if (other.SingleImportEnum != global::Google.Protobuf.TestProtos.ImportEnum.IMPORT_ENUM_UNSPECIFIED) { + if (other.SingleImportEnum != 0) { SingleImportEnum = other.SingleImportEnum; } if (other.singlePublicImportMessage_ != null) { @@ -1524,14 +1526,14 @@ namespace Google.Protobuf.TestProtos { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { public enum NestedEnum { - NESTED_ENUM_UNSPECIFIED = 0, - FOO = 1, - BAR = 2, - BAZ = 3, + [pbr::OriginalName("NESTED_ENUM_UNSPECIFIED")] Unspecified = 0, + [pbr::OriginalName("FOO")] Foo = 1, + [pbr::OriginalName("BAR")] Bar = 2, + [pbr::OriginalName("BAZ")] Baz = 3, /// <summary> /// Intentionally negative. /// </summary> - NEG = -1, + [pbr::OriginalName("NEG")] Neg = -1, } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] @@ -1598,7 +1600,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -1656,7 +1658,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<NestedTestAllTypes> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[1]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -1734,7 +1736,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -1817,7 +1819,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestDeprecatedFields> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[2]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -1871,7 +1873,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -1925,7 +1927,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<ForeignMessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[3]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[3]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -1978,7 +1980,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -2028,7 +2030,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestReservedFields> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[4]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[4]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -2068,7 +2070,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -2107,7 +2109,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestForeignNested> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[5]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[5]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -2160,7 +2162,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -2219,7 +2221,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestReallyLargeTagNumber> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[6]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[6]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -2289,7 +2291,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -2353,7 +2355,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestRecursiveMessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[7]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[7]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -2419,7 +2421,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -2492,7 +2494,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestMutualRecursionA> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[8]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[8]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -2545,7 +2547,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -2601,7 +2603,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestMutualRecursionB> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[9]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[9]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -2667,7 +2669,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -2741,7 +2743,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestCamelCaseFieldNames> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[10]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[10]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -2785,13 +2787,13 @@ namespace Google.Protobuf.TestProtos { public string StringField { get { return stringField_; } set { - stringField_ = pb::Preconditions.CheckNotNull(value, "value"); + stringField_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "EnumField" field.</summary> public const int EnumFieldFieldNumber = 3; - private global::Google.Protobuf.TestProtos.ForeignEnum enumField_ = global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED; + private global::Google.Protobuf.TestProtos.ForeignEnum enumField_ = 0; public global::Google.Protobuf.TestProtos.ForeignEnum EnumField { get { return enumField_; } set { @@ -2871,7 +2873,7 @@ namespace Google.Protobuf.TestProtos { int hash = 1; if (PrimitiveField != 0) hash ^= PrimitiveField.GetHashCode(); if (StringField.Length != 0) hash ^= StringField.GetHashCode(); - if (EnumField != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) hash ^= EnumField.GetHashCode(); + if (EnumField != 0) hash ^= EnumField.GetHashCode(); if (messageField_ != null) hash ^= MessageField.GetHashCode(); hash ^= repeatedPrimitiveField_.GetHashCode(); hash ^= repeatedStringField_.GetHashCode(); @@ -2881,7 +2883,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -2893,7 +2895,7 @@ namespace Google.Protobuf.TestProtos { output.WriteRawTag(18); output.WriteString(StringField); } - if (EnumField != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { + if (EnumField != 0) { output.WriteRawTag(24); output.WriteEnum((int) EnumField); } @@ -2915,7 +2917,7 @@ namespace Google.Protobuf.TestProtos { if (StringField.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(StringField); } - if (EnumField != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { + if (EnumField != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) EnumField); } if (messageField_ != null) { @@ -2938,7 +2940,7 @@ namespace Google.Protobuf.TestProtos { if (other.StringField.Length != 0) { StringField = other.StringField; } - if (other.EnumField != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { + if (other.EnumField != 0) { EnumField = other.EnumField; } if (other.messageField_ != null) { @@ -3013,7 +3015,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestFieldOrderings> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[11]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[11]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -3043,7 +3045,7 @@ namespace Google.Protobuf.TestProtos { public string MyString { get { return myString_; } set { - myString_ = pb::Preconditions.CheckNotNull(value, "value"); + myString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } @@ -3105,7 +3107,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -3276,7 +3278,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -3345,7 +3347,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<SparseEnumMessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[12]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[12]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -3368,7 +3370,7 @@ namespace Google.Protobuf.TestProtos { /// <summary>Field number for the "sparse_enum" field.</summary> public const int SparseEnumFieldNumber = 1; - private global::Google.Protobuf.TestProtos.TestSparseEnum sparseEnum_ = global::Google.Protobuf.TestProtos.TestSparseEnum.TEST_SPARSE_ENUM_UNSPECIFIED; + private global::Google.Protobuf.TestProtos.TestSparseEnum sparseEnum_ = 0; public global::Google.Protobuf.TestProtos.TestSparseEnum SparseEnum { get { return sparseEnum_; } set { @@ -3393,16 +3395,16 @@ namespace Google.Protobuf.TestProtos { public override int GetHashCode() { int hash = 1; - if (SparseEnum != global::Google.Protobuf.TestProtos.TestSparseEnum.TEST_SPARSE_ENUM_UNSPECIFIED) hash ^= SparseEnum.GetHashCode(); + if (SparseEnum != 0) hash ^= SparseEnum.GetHashCode(); return hash; } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { - if (SparseEnum != global::Google.Protobuf.TestProtos.TestSparseEnum.TEST_SPARSE_ENUM_UNSPECIFIED) { + if (SparseEnum != 0) { output.WriteRawTag(8); output.WriteEnum((int) SparseEnum); } @@ -3410,7 +3412,7 @@ namespace Google.Protobuf.TestProtos { public int CalculateSize() { int size = 0; - if (SparseEnum != global::Google.Protobuf.TestProtos.TestSparseEnum.TEST_SPARSE_ENUM_UNSPECIFIED) { + if (SparseEnum != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) SparseEnum); } return size; @@ -3420,7 +3422,7 @@ namespace Google.Protobuf.TestProtos { if (other == null) { return; } - if (other.SparseEnum != global::Google.Protobuf.TestProtos.TestSparseEnum.TEST_SPARSE_ENUM_UNSPECIFIED) { + if (other.SparseEnum != 0) { SparseEnum = other.SparseEnum; } } @@ -3451,7 +3453,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<OneString> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[13]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[13]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -3478,7 +3480,7 @@ namespace Google.Protobuf.TestProtos { public string Data { get { return data_; } set { - data_ = pb::Preconditions.CheckNotNull(value, "value"); + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } @@ -3504,7 +3506,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -3554,7 +3556,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<MoreString> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[14]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[14]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -3606,7 +3608,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -3649,7 +3651,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<OneBytes> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[15]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[15]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -3676,7 +3678,7 @@ namespace Google.Protobuf.TestProtos { public pb::ByteString Data { get { return data_; } set { - data_ = pb::Preconditions.CheckNotNull(value, "value"); + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } @@ -3702,7 +3704,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -3752,7 +3754,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<MoreBytes> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[16]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[16]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -3779,7 +3781,7 @@ namespace Google.Protobuf.TestProtos { public pb::ByteString Data { get { return data_; } set { - data_ = pb::Preconditions.CheckNotNull(value, "value"); + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } @@ -3805,7 +3807,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -3858,7 +3860,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<Int32Message> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[17]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[17]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -3911,7 +3913,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -3961,7 +3963,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<Uint32Message> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[18]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[18]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -4014,7 +4016,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -4064,7 +4066,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<Int64Message> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[19]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[19]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -4117,7 +4119,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -4167,7 +4169,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<Uint64Message> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[20]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[20]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -4220,7 +4222,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -4270,7 +4272,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<BoolMessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[21]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[21]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -4323,7 +4325,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -4376,7 +4378,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestOneof> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[22]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[22]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -4423,7 +4425,7 @@ namespace Google.Protobuf.TestProtos { public string FooString { get { return fooCase_ == FooOneofCase.FooString ? (string) foo_ : ""; } set { - foo_ = pb::Preconditions.CheckNotNull(value, "value"); + foo_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); fooCase_ = FooOneofCase.FooString; } } @@ -4470,6 +4472,7 @@ namespace Google.Protobuf.TestProtos { if (FooInt != other.FooInt) return false; if (FooString != other.FooString) return false; if (!object.Equals(FooMessage, other.FooMessage)) return false; + if (FooCase != other.FooCase) return false; return true; } @@ -4478,11 +4481,12 @@ namespace Google.Protobuf.TestProtos { if (fooCase_ == FooOneofCase.FooInt) hash ^= FooInt.GetHashCode(); if (fooCase_ == FooOneofCase.FooString) hash ^= FooString.GetHashCode(); if (fooCase_ == FooOneofCase.FooMessage) hash ^= FooMessage.GetHashCode(); + hash ^= (int) fooCase_; return hash; } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -4568,7 +4572,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestPackedTypes> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[23]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[23]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -4776,7 +4780,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -4928,7 +4932,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestUnpackedTypes> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[24]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[24]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -5136,7 +5140,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -5284,7 +5288,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestRepeatedScalarDifferentTagSizes> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[25]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[25]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -5410,7 +5414,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -5494,7 +5498,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestCommentInjectionMessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[26]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[26]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -5524,7 +5528,7 @@ namespace Google.Protobuf.TestProtos { public string A { get { return a_; } set { - a_ = pb::Preconditions.CheckNotNull(value, "value"); + a_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } @@ -5550,7 +5554,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -5603,7 +5607,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<FooRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[27]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[27]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -5643,7 +5647,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -5679,7 +5683,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<FooResponse> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[28]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[28]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -5719,7 +5723,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -5755,7 +5759,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<FooClientMessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[29]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[29]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -5795,7 +5799,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -5831,7 +5835,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<FooServerMessage> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[30]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[30]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -5871,7 +5875,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -5907,7 +5911,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<BarRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[31]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[31]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -5947,7 +5951,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -5983,7 +5987,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<BarResponse> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestProto3.Descriptor.MessageTypes[32]; } + get { return global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor.MessageTypes[32]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -6023,7 +6027,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { diff --git a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs index bd90ddd8..ae12f4a4 100644 --- a/csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs +++ b/csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs @@ -11,7 +11,7 @@ namespace Google.Protobuf.TestProtos { /// <summary>Holder for reflection information generated from google/protobuf/unittest_well_known_types.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public static partial class UnittestWellKnownTypes { + public static partial class UnittestWellKnownTypesReflection { #region Descriptor /// <summary>File descriptor for google/protobuf/unittest_well_known_types.proto</summary> @@ -20,7 +20,7 @@ namespace Google.Protobuf.TestProtos { } private static pbr::FileDescriptor descriptor; - static UnittestWellKnownTypes() { + static UnittestWellKnownTypesReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci9nb29nbGUvcHJvdG9idWYvdW5pdHRlc3Rfd2VsbF9rbm93bl90eXBlcy5w", @@ -31,7 +31,7 @@ namespace Google.Protobuf.TestProtos { "L3Byb3RvYnVmL3NvdXJjZV9jb250ZXh0LnByb3RvGhxnb29nbGUvcHJvdG9i", "dWYvc3RydWN0LnByb3RvGh9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnBy", "b3RvGhpnb29nbGUvcHJvdG9idWYvdHlwZS5wcm90bxoeZ29vZ2xlL3Byb3Rv", - "YnVmL3dyYXBwZXJzLnByb3RvIpEHChJUZXN0V2VsbEtub3duVHlwZXMSJwoJ", + "YnVmL3dyYXBwZXJzLnByb3RvIr4HChJUZXN0V2VsbEtub3duVHlwZXMSJwoJ", "YW55X2ZpZWxkGAEgASgLMhQuZ29vZ2xlLnByb3RvYnVmLkFueRInCglhcGlf", "ZmllbGQYAiABKAsyFC5nb29nbGUucHJvdG9idWYuQXBpEjEKDmR1cmF0aW9u", "X2ZpZWxkGAMgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uEisKC2Vt", @@ -51,7 +51,8 @@ namespace Google.Protobuf.TestProtos { "cm90b2J1Zi5VSW50MzJWYWx1ZRIuCgpib29sX2ZpZWxkGBAgASgLMhouZ29v", "Z2xlLnByb3RvYnVmLkJvb2xWYWx1ZRIyCgxzdHJpbmdfZmllbGQYESABKAsy", "HC5nb29nbGUucHJvdG9idWYuU3RyaW5nVmFsdWUSMAoLYnl0ZXNfZmllbGQY", - "EiABKAsyGy5nb29nbGUucHJvdG9idWYuQnl0ZXNWYWx1ZSKVBwoWUmVwZWF0", + "EiABKAsyGy5nb29nbGUucHJvdG9idWYuQnl0ZXNWYWx1ZRIrCgt2YWx1ZV9m", + "aWVsZBgTIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZSKVBwoWUmVwZWF0", "ZWRXZWxsS25vd25UeXBlcxInCglhbnlfZmllbGQYASADKAsyFC5nb29nbGUu", "cHJvdG9idWYuQW55EicKCWFwaV9maWVsZBgCIAMoCzIULmdvb2dsZS5wcm90", "b2J1Zi5BcGkSMQoOZHVyYXRpb25fZmllbGQYAyADKAsyGS5nb29nbGUucHJv", @@ -159,13 +160,13 @@ namespace Google.Protobuf.TestProtos { "AiABKAsyGy5nb29nbGUucHJvdG9idWYuQnl0ZXNWYWx1ZToCOAFCOQoYY29t", "Lmdvb2dsZS5wcm90b2J1Zi50ZXN0UAGqAhpHb29nbGUuUHJvdG9idWYuVGVz", "dFByb3Rvc2IGcHJvdG8z")); - descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, - new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.Proto.Any.Descriptor, global::Google.Protobuf.WellKnownTypes.Proto.Api.Descriptor, global::Google.Protobuf.WellKnownTypes.Proto.Duration.Descriptor, global::Google.Protobuf.WellKnownTypes.Proto.Empty.Descriptor, global::Google.Protobuf.WellKnownTypes.Proto.FieldMask.Descriptor, global::Google.Protobuf.WellKnownTypes.Proto.SourceContext.Descriptor, global::Google.Protobuf.WellKnownTypes.Proto.Struct.Descriptor, global::Google.Protobuf.WellKnownTypes.Proto.Timestamp.Descriptor, global::Google.Protobuf.WellKnownTypes.Proto.Type.Descriptor, global::Google.Protobuf.WellKnownTypes.Wrappers.Descriptor, }, - new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.TestWellKnownTypes), new[]{ "AnyField", "ApiField", "DurationField", "EmptyField", "FieldMaskField", "SourceContextField", "StructField", "TimestampField", "TypeField", "DoubleField", "FloatField", "Int64Field", "Uint64Field", "Int32Field", "Uint32Field", "BoolField", "StringField", "BytesField" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.RepeatedWellKnownTypes), new[]{ "AnyField", "ApiField", "DurationField", "EmptyField", "FieldMaskField", "SourceContextField", "StructField", "TimestampField", "TypeField", "DoubleField", "FloatField", "Int64Field", "Uint64Field", "Int32Field", "Uint32Field", "BoolField", "StringField", "BytesField" }, null, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.OneofWellKnownTypes), new[]{ "AnyField", "ApiField", "DurationField", "EmptyField", "FieldMaskField", "SourceContextField", "StructField", "TimestampField", "TypeField", "DoubleField", "FloatField", "Int64Field", "Uint64Field", "Int32Field", "Uint32Field", "BoolField", "StringField", "BytesField" }, new[]{ "OneofField" }, null, null), - new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.TestProtos.MapWellKnownTypes), new[]{ "AnyField", "ApiField", "DurationField", "EmptyField", "FieldMaskField", "SourceContextField", "StructField", "TimestampField", "TypeField", "DoubleField", "FloatField", "Int64Field", "Uint64Field", "Int32Field", "Uint32Field", "BoolField", "StringField", "BytesField" }, null, null, new pbr::GeneratedCodeInfo[] { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }) + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.ApiReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.FieldMaskReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.SourceContextReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TypeReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestWellKnownTypes), global::Google.Protobuf.TestProtos.TestWellKnownTypes.Parser, new[]{ "AnyField", "ApiField", "DurationField", "EmptyField", "FieldMaskField", "SourceContextField", "StructField", "TimestampField", "TypeField", "DoubleField", "FloatField", "Int64Field", "Uint64Field", "Int32Field", "Uint32Field", "BoolField", "StringField", "BytesField", "ValueField" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.RepeatedWellKnownTypes), global::Google.Protobuf.TestProtos.RepeatedWellKnownTypes.Parser, new[]{ "AnyField", "ApiField", "DurationField", "EmptyField", "FieldMaskField", "SourceContextField", "StructField", "TimestampField", "TypeField", "DoubleField", "FloatField", "Int64Field", "Uint64Field", "Int32Field", "Uint32Field", "BoolField", "StringField", "BytesField" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.OneofWellKnownTypes), global::Google.Protobuf.TestProtos.OneofWellKnownTypes.Parser, new[]{ "AnyField", "ApiField", "DurationField", "EmptyField", "FieldMaskField", "SourceContextField", "StructField", "TimestampField", "TypeField", "DoubleField", "FloatField", "Int64Field", "Uint64Field", "Int32Field", "Uint32Field", "BoolField", "StringField", "BytesField" }, new[]{ "OneofField" }, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.MapWellKnownTypes), global::Google.Protobuf.TestProtos.MapWellKnownTypes.Parser, new[]{ "AnyField", "ApiField", "DurationField", "EmptyField", "FieldMaskField", "SourceContextField", "StructField", "TimestampField", "TypeField", "DoubleField", "FloatField", "Int64Field", "Uint64Field", "Int32Field", "Uint32Field", "BoolField", "StringField", "BytesField" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }) })); } #endregion @@ -183,7 +184,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<TestWellKnownTypes> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestWellKnownTypes.Descriptor.MessageTypes[0]; } + get { return global::Google.Protobuf.TestProtos.UnittestWellKnownTypesReflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -215,6 +216,7 @@ namespace Google.Protobuf.TestProtos { BoolField = other.BoolField; StringField = other.StringField; BytesField = other.BytesField; + ValueField = other.valueField_ != null ? other.ValueField.Clone() : null; } public TestWellKnownTypes Clone() { @@ -410,6 +412,19 @@ namespace Google.Protobuf.TestProtos { } } + /// <summary>Field number for the "value_field" field.</summary> + public const int ValueFieldFieldNumber = 19; + private global::Google.Protobuf.WellKnownTypes.Value valueField_; + /// <summary> + /// Part of struct, but useful to be able to test separately + /// </summary> + public global::Google.Protobuf.WellKnownTypes.Value ValueField { + get { return valueField_; } + set { + valueField_ = value; + } + } + public override bool Equals(object other) { return Equals(other as TestWellKnownTypes); } @@ -439,6 +454,7 @@ namespace Google.Protobuf.TestProtos { if (BoolField != other.BoolField) return false; if (StringField != other.StringField) return false; if (BytesField != other.BytesField) return false; + if (!object.Equals(ValueField, other.ValueField)) return false; return true; } @@ -462,11 +478,12 @@ namespace Google.Protobuf.TestProtos { if (boolField_ != null) hash ^= BoolField.GetHashCode(); if (stringField_ != null) hash ^= StringField.GetHashCode(); if (bytesField_ != null) hash ^= BytesField.GetHashCode(); + if (valueField_ != null) hash ^= ValueField.GetHashCode(); return hash; } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -533,6 +550,10 @@ namespace Google.Protobuf.TestProtos { if (bytesField_ != null) { _single_bytesField_codec.WriteTagAndValue(output, BytesField); } + if (valueField_ != null) { + output.WriteRawTag(154, 1); + output.WriteMessage(ValueField); + } } public int CalculateSize() { @@ -591,6 +612,9 @@ namespace Google.Protobuf.TestProtos { if (bytesField_ != null) { size += _single_bytesField_codec.CalculateSizeWithTag(BytesField); } + if (valueField_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(ValueField); + } return size; } @@ -697,6 +721,12 @@ namespace Google.Protobuf.TestProtos { BytesField = other.BytesField; } } + if (other.valueField_ != null) { + if (valueField_ == null) { + valueField_ = new global::Google.Protobuf.WellKnownTypes.Value(); + } + ValueField.MergeFrom(other.ValueField); + } } public void MergeFrom(pb::CodedInputStream input) { @@ -832,6 +862,13 @@ namespace Google.Protobuf.TestProtos { } break; } + case 154: { + if (valueField_ == null) { + valueField_ = new global::Google.Protobuf.WellKnownTypes.Value(); + } + input.ReadMessage(valueField_); + break; + } } } } @@ -847,7 +884,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<RepeatedWellKnownTypes> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestWellKnownTypes.Descriptor.MessageTypes[1]; } + get { return global::Google.Protobuf.TestProtos.UnittestWellKnownTypesReflection.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -1106,7 +1143,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -1268,7 +1305,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<OneofWellKnownTypes> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestWellKnownTypes.Descriptor.MessageTypes[2]; } + get { return global::Google.Protobuf.TestProtos.UnittestWellKnownTypesReflection.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -1596,6 +1633,7 @@ namespace Google.Protobuf.TestProtos { if (BoolField != other.BoolField) return false; if (StringField != other.StringField) return false; if (BytesField != other.BytesField) return false; + if (OneofFieldCase != other.OneofFieldCase) return false; return true; } @@ -1619,11 +1657,12 @@ namespace Google.Protobuf.TestProtos { if (oneofFieldCase_ == OneofFieldOneofCase.BoolField) hash ^= BoolField.GetHashCode(); if (oneofFieldCase_ == OneofFieldOneofCase.StringField) hash ^= StringField.GetHashCode(); if (oneofFieldCase_ == OneofFieldOneofCase.BytesField) hash ^= BytesField.GetHashCode(); + hash ^= (int) oneofFieldCase_; return hash; } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { @@ -1955,7 +1994,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser<MapWellKnownTypes> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { - get { return global::Google.Protobuf.TestProtos.UnittestWellKnownTypes.Descriptor.MessageTypes[3]; } + get { return global::Google.Protobuf.TestProtos.UnittestWellKnownTypesReflection.Descriptor.MessageTypes[3]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { @@ -2078,7 +2117,7 @@ namespace Google.Protobuf.TestProtos { public const int DoubleFieldFieldNumber = 10; private static readonly pbc::MapField<int, double?>.Codec _map_doubleField_codec = new pbc::MapField<int, double?>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForStructWrapper<double>(18), 82); - private readonly pbc::MapField<int, double?> doubleField_ = new pbc::MapField<int, double?>(true); + private readonly pbc::MapField<int, double?> doubleField_ = new pbc::MapField<int, double?>(); public pbc::MapField<int, double?> DoubleField { get { return doubleField_; } } @@ -2087,7 +2126,7 @@ namespace Google.Protobuf.TestProtos { public const int FloatFieldFieldNumber = 11; private static readonly pbc::MapField<int, float?>.Codec _map_floatField_codec = new pbc::MapField<int, float?>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForStructWrapper<float>(18), 90); - private readonly pbc::MapField<int, float?> floatField_ = new pbc::MapField<int, float?>(true); + private readonly pbc::MapField<int, float?> floatField_ = new pbc::MapField<int, float?>(); public pbc::MapField<int, float?> FloatField { get { return floatField_; } } @@ -2096,7 +2135,7 @@ namespace Google.Protobuf.TestProtos { public const int Int64FieldFieldNumber = 12; private static readonly pbc::MapField<int, long?>.Codec _map_int64Field_codec = new pbc::MapField<int, long?>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForStructWrapper<long>(18), 98); - private readonly pbc::MapField<int, long?> int64Field_ = new pbc::MapField<int, long?>(true); + private readonly pbc::MapField<int, long?> int64Field_ = new pbc::MapField<int, long?>(); public pbc::MapField<int, long?> Int64Field { get { return int64Field_; } } @@ -2105,7 +2144,7 @@ namespace Google.Protobuf.TestProtos { public const int Uint64FieldFieldNumber = 13; private static readonly pbc::MapField<int, ulong?>.Codec _map_uint64Field_codec = new pbc::MapField<int, ulong?>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForStructWrapper<ulong>(18), 106); - private readonly pbc::MapField<int, ulong?> uint64Field_ = new pbc::MapField<int, ulong?>(true); + private readonly pbc::MapField<int, ulong?> uint64Field_ = new pbc::MapField<int, ulong?>(); public pbc::MapField<int, ulong?> Uint64Field { get { return uint64Field_; } } @@ -2114,7 +2153,7 @@ namespace Google.Protobuf.TestProtos { public const int Int32FieldFieldNumber = 14; private static readonly pbc::MapField<int, int?>.Codec _map_int32Field_codec = new pbc::MapField<int, int?>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForStructWrapper<int>(18), 114); - private readonly pbc::MapField<int, int?> int32Field_ = new pbc::MapField<int, int?>(true); + private readonly pbc::MapField<int, int?> int32Field_ = new pbc::MapField<int, int?>(); public pbc::MapField<int, int?> Int32Field { get { return int32Field_; } } @@ -2123,7 +2162,7 @@ namespace Google.Protobuf.TestProtos { public const int Uint32FieldFieldNumber = 15; private static readonly pbc::MapField<int, uint?>.Codec _map_uint32Field_codec = new pbc::MapField<int, uint?>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForStructWrapper<uint>(18), 122); - private readonly pbc::MapField<int, uint?> uint32Field_ = new pbc::MapField<int, uint?>(true); + private readonly pbc::MapField<int, uint?> uint32Field_ = new pbc::MapField<int, uint?>(); public pbc::MapField<int, uint?> Uint32Field { get { return uint32Field_; } } @@ -2132,7 +2171,7 @@ namespace Google.Protobuf.TestProtos { public const int BoolFieldFieldNumber = 16; private static readonly pbc::MapField<int, bool?>.Codec _map_boolField_codec = new pbc::MapField<int, bool?>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForStructWrapper<bool>(18), 130); - private readonly pbc::MapField<int, bool?> boolField_ = new pbc::MapField<int, bool?>(true); + private readonly pbc::MapField<int, bool?> boolField_ = new pbc::MapField<int, bool?>(); public pbc::MapField<int, bool?> BoolField { get { return boolField_; } } @@ -2141,7 +2180,7 @@ namespace Google.Protobuf.TestProtos { public const int StringFieldFieldNumber = 17; private static readonly pbc::MapField<int, string>.Codec _map_stringField_codec = new pbc::MapField<int, string>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForClassWrapper<string>(18), 138); - private readonly pbc::MapField<int, string> stringField_ = new pbc::MapField<int, string>(true); + private readonly pbc::MapField<int, string> stringField_ = new pbc::MapField<int, string>(); public pbc::MapField<int, string> StringField { get { return stringField_; } } @@ -2150,7 +2189,7 @@ namespace Google.Protobuf.TestProtos { public const int BytesFieldFieldNumber = 18; private static readonly pbc::MapField<int, pb::ByteString>.Codec _map_bytesField_codec = new pbc::MapField<int, pb::ByteString>.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForClassWrapper<pb::ByteString>(18), 146); - private readonly pbc::MapField<int, pb::ByteString> bytesField_ = new pbc::MapField<int, pb::ByteString>(true); + private readonly pbc::MapField<int, pb::ByteString> bytesField_ = new pbc::MapField<int, pb::ByteString>(); public pbc::MapField<int, pb::ByteString> BytesField { get { return bytesField_; } } @@ -2211,7 +2250,7 @@ namespace Google.Protobuf.TestProtos { } public override string ToString() { - return pb::JsonFormatter.Default.Format(this); + return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { diff --git a/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs b/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs index 0a2b8b32..f21be7d9 100644 --- a/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs +++ b/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs @@ -47,6 +47,24 @@ namespace Google.Protobuf.WellKnownTypes } [Test] + public void Pack_WithCustomPrefix() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var any = Any.Pack(message, "foo.bar/baz"); + Assert.AreEqual("foo.bar/baz/protobuf_unittest.TestAllTypes", any.TypeUrl); + Assert.AreEqual(message.CalculateSize(), any.Value.Length); + } + + [Test] + public void Pack_WithCustomPrefixTrailingSlash() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var any = Any.Pack(message, "foo.bar/baz/"); + Assert.AreEqual("foo.bar/baz/protobuf_unittest.TestAllTypes", any.TypeUrl); + Assert.AreEqual(message.CalculateSize(), any.Value.Length); + } + + [Test] public void Unpack_WrongType() { var message = SampleMessages.CreateFullTestAllTypes(); @@ -62,5 +80,37 @@ namespace Google.Protobuf.WellKnownTypes var unpacked = any.Unpack<TestAllTypes>(); Assert.AreEqual(message, unpacked); } + + [Test] + public void Unpack_CustomPrefix_Success() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var any = Any.Pack(message, "foo.bar/baz"); + var unpacked = any.Unpack<TestAllTypes>(); + Assert.AreEqual(message, unpacked); + } + + [Test] + public void ToString_WithValues() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var any = Any.Pack(message); + var text = any.ToString(); + Assert.That(text, Is.StringContaining("\"@value\": \"" + message.ToByteString().ToBase64() + "\"")); + } + + [Test] + public void ToString_Empty() + { + var any = new Any(); + Assert.AreEqual("{ \"@type\": \"\", \"@value\": \"\" }", any.ToString()); + } + + [Test] + public void ToString_MessageContainingAny() + { + var message = new TestWellKnownTypes { AnyField = new Any() }; + Assert.AreEqual("{ \"anyField\": { \"@type\": \"\", \"@value\": \"\" } }", message.ToString()); + } } } diff --git a/csharp/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs b/csharp/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs index 36012e63..141faf80 100644 --- a/csharp/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs +++ b/csharp/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs @@ -50,11 +50,6 @@ namespace Google.Protobuf.WellKnownTypes // Rounding is towards 0 Assert.AreEqual(TimeSpan.FromTicks(2), new Duration { Nanos = 250 }.ToTimeSpan()); Assert.AreEqual(TimeSpan.FromTicks(-2), new Duration { Nanos = -250 }.ToTimeSpan()); - - // Non-normalized durations - Assert.AreEqual(TimeSpan.FromSeconds(3), new Duration { Seconds = 1, Nanos = 2 * Duration.NanosecondsPerSecond }.ToTimeSpan()); - Assert.AreEqual(TimeSpan.FromSeconds(1), new Duration { Seconds = 3, Nanos = -2 * Duration.NanosecondsPerSecond }.ToTimeSpan()); - Assert.AreEqual(TimeSpan.FromSeconds(-1), new Duration { Seconds = 1, Nanos = -2 * Duration.NanosecondsPerSecond }.ToTimeSpan()); } [Test] @@ -100,5 +95,38 @@ namespace Google.Protobuf.WellKnownTypes Assert.AreEqual(new Duration { Seconds = 1 }, Duration.FromTimeSpan(TimeSpan.FromSeconds(1))); Assert.AreEqual(new Duration { Nanos = Duration.NanosecondsPerTick }, Duration.FromTimeSpan(TimeSpan.FromTicks(1))); } + + [Test] + [TestCase(0, Duration.MaxNanoseconds + 1)] + [TestCase(0, Duration.MinNanoseconds - 1)] + [TestCase(Duration.MinSeconds - 1, 0)] + [TestCase(Duration.MaxSeconds + 1, 0)] + [TestCase(1, -1)] + [TestCase(-1, 1)] + public void ToTimeSpan_Invalid(long seconds, int nanoseconds) + { + var duration = new Duration { Seconds = seconds, Nanos = nanoseconds }; + Assert.Throws<InvalidOperationException>(() => duration.ToTimeSpan()); + } + + [Test] + [TestCase(0, Duration.MaxNanoseconds)] + [TestCase(0, Duration.MinNanoseconds)] + [TestCase(Duration.MinSeconds, Duration.MinNanoseconds)] + [TestCase(Duration.MaxSeconds, Duration.MaxNanoseconds)] + public void ToTimeSpan_Valid(long seconds, int nanoseconds) + { + // Only testing that these values don't throw, unlike their similar tests in ToTimeSpan_Invalid + var duration = new Duration { Seconds = seconds, Nanos = nanoseconds }; + duration.ToTimeSpan(); + } + + [Test] + public void ToString_NonNormalized() + { + // Just a single example should be sufficient... + var duration = new Duration { Seconds = 1, Nanos = -1 }; + Assert.AreEqual("{ \"@warning\": \"Invalid Duration\", \"seconds\": \"1\", \"nanos\": -1 }", duration.ToString()); + } } } diff --git a/csharp/src/Google.Protobuf.Test/WellKnownTypes/FieldMaskTest.cs b/csharp/src/Google.Protobuf.Test/WellKnownTypes/FieldMaskTest.cs new file mode 100644 index 00000000..89bc8275 --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/WellKnownTypes/FieldMaskTest.cs @@ -0,0 +1,62 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2016 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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.Protobuf.WellKnownTypes +{ + public class FieldMaskTest + { + [Test] + [TestCase("foo__bar")] + [TestCase("foo_3_ar")] + [TestCase("fooBar")] + public void ToString_Invalid(string input) + { + var mask = new FieldMask { Paths = { input } }; + var text = mask.ToString(); + // More specific test below + Assert.That(text, Is.StringContaining("@warning")); + Assert.That(text, Is.StringContaining(input)); + } + + [Test] + public void ToString_Invalid_Precise() + { + var mask = new FieldMask { Paths = { "x", "foo__bar", @"x\y" } }; + Assert.AreEqual( + "{ \"@warning\": \"Invalid FieldMask\", \"paths\": [ \"x\", \"foo__bar\", \"x\\\\y\" ] }", + mask.ToString()); + } + } +} diff --git a/csharp/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs b/csharp/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs index 597539eb..9ecd24c6 100644 --- a/csharp/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs +++ b/csharp/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs @@ -61,6 +61,29 @@ namespace Google.Protobuf.WellKnownTypes Assert.AreEqual(new DateTime(1969, 12, 31, 23, 59, 59).AddMilliseconds(1), t2.ToDateTime()); } + [Test] + [TestCase(Timestamp.UnixSecondsAtBclMinValue - 1, Timestamp.MaxNanos)] + [TestCase(Timestamp.UnixSecondsAtBclMaxValue + 1, 0)] + [TestCase(0, -1)] + [TestCase(0, Timestamp.MaxNanos + 1)] + public void ToDateTime_OutOfRange(long seconds, int nanoseconds) + { + var value = new Timestamp { Seconds = seconds, Nanos = nanoseconds }; + Assert.Throws<InvalidOperationException>(() => value.ToDateTime()); + } + + // 1ns larger or smaller than the above values + [Test] + [TestCase(Timestamp.UnixSecondsAtBclMinValue, 0)] + [TestCase(Timestamp.UnixSecondsAtBclMaxValue, Timestamp.MaxNanos)] + [TestCase(0, 0)] + [TestCase(0, Timestamp.MaxNanos)] + public void ToDateTime_ValidBoundaries(long seconds, int nanoseconds) + { + var value = new Timestamp { Seconds = seconds, Nanos = nanoseconds }; + value.ToDateTime(); + } + private static void AssertRoundtrip(Timestamp timestamp, DateTime dateTime) { Assert.AreEqual(timestamp, Timestamp.FromDateTime(dateTime)); @@ -80,5 +103,13 @@ namespace Google.Protobuf.WellKnownTypes Assert.AreEqual(t1, t2 + difference); Assert.AreEqual(t2, t1 - difference); } + + [Test] + public void ToString_NonNormalized() + { + // Just a single example should be sufficient... + var duration = new Timestamp { Seconds = 1, Nanos = -1 }; + Assert.AreEqual("{ \"@warning\": \"Invalid Timestamp\", \"seconds\": \"1\", \"nanos\": -1 }", duration.ToString()); + } } } diff --git a/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs b/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs index fbc0ff07..5b7185dc 100644 --- a/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs +++ b/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs @@ -149,8 +149,34 @@ namespace Google.Protobuf.WellKnownTypes } [Test] + public void RepeatedWrappersBinaryFormat() + { + // At one point we accidentally used a packed format for repeated wrappers, which is wrong (and weird). + // This test is just to prove that we use the right format. + + var rawOutput = new MemoryStream(); + var output = new CodedOutputStream(rawOutput); + // Write a value of 5 + output.WriteTag(RepeatedWellKnownTypes.Int32FieldFieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(2); + output.WriteTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint); + output.WriteInt32(5); + // Write a value of 0 (empty message) + output.WriteTag(RepeatedWellKnownTypes.Int32FieldFieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(0); + output.Flush(); + var expectedBytes = rawOutput.ToArray(); + + var message = new RepeatedWellKnownTypes { Int32Field = { 5, 0 } }; + var actualBytes = message.ToByteArray(); + Assert.AreEqual(expectedBytes, actualBytes); + } + + [Test] public void MapWrappersSerializeDeserialize() { + // Note: no null values here, as they are prohibited in map fields + // (despite being representable). var message = new MapWellKnownTypes { BoolField = { { 10, false }, { 20, true } }, @@ -158,13 +184,12 @@ namespace Google.Protobuf.WellKnownTypes { -1, ByteString.CopyFrom(1, 2, 3) }, { 10, ByteString.CopyFrom(4, 5, 6) }, { 1000, ByteString.Empty }, - { 10000, null } }, DoubleField = { { 1, 12.5 }, { 10, -1.5 }, { 20, 0d } }, FloatField = { { 2, 123.25f }, { 3, -20f }, { 4, 0f } }, Int32Field = { { 5, int.MaxValue }, { 6, int.MinValue }, { 7, 0 } }, Int64Field = { { 8, long.MaxValue }, { 9, long.MinValue }, { 10, 0L } }, - StringField = { { 11, "First" }, { 12, "Second" }, { 13, "" }, { 14, null } }, + StringField = { { 11, "First" }, { 12, "Second" }, { 13, "" } }, Uint32Field = { { 15, uint.MaxValue }, { 16, uint.MinValue }, { 17, 0U } }, Uint64Field = { { 18, ulong.MaxValue }, { 19, ulong.MinValue }, { 20, 0UL } }, }; @@ -224,13 +249,11 @@ namespace Google.Protobuf.WellKnownTypes [Test] public void Reflection_MapFields() { - // Just a single example... note that we can't have a null value here - var message = new MapWellKnownTypes { Int32Field = { { 1, 2 }, { 3, null } } }; + // Just a single example... note that we can't have a null value here despite the value type being int? + var message = new MapWellKnownTypes { Int32Field = { { 1, 2 } } }; var fields = MapWellKnownTypes.Descriptor.Fields; var dictionary = (IDictionary) fields[MapWellKnownTypes.Int32FieldFieldNumber].Accessor.GetValue(message); Assert.AreEqual(2, dictionary[1]); - Assert.IsNull(dictionary[3]); - Assert.IsTrue(dictionary.Contains(3)); } [Test] @@ -296,9 +319,10 @@ namespace Google.Protobuf.WellKnownTypes // Merging is odd with wrapper types, due to the way that default values aren't emitted in // the binary stream. In fact we cheat a little bit - a message with an explicitly present default - // value will have that default value ignored. + // value will have that default value ignored. See issue 615. Fixing this would require significant upheaval to + // the FieldCodec side of things. [Test] - public void MergingCornerCase() + public void MergingStreamExplicitValue() { var message = new TestWellKnownTypes { Int32Field = 5 }; @@ -320,9 +344,47 @@ namespace Google.Protobuf.WellKnownTypes message.MergeFrom(bytes); // A normal implementation would have 0 now, as the explicit default would have been overwritten the 5. + // With the FieldCodec for Nullable<int>, we can't tell the difference between an implicit 0 and an explicit 0. + Assert.AreEqual(5, message.Int32Field); + } + + [Test] + public void MergingStreamNoValue() + { + var message = new TestWellKnownTypes { Int32Field = 5 }; + + // Create a byte array which an Int32 field, but with no value. + var bytes = new TestWellKnownTypes { Int32Field = 0 }.ToByteArray(); + Assert.AreEqual(2, bytes.Length); // The tag for Int32Field is a single byte, then a byte indicating a 0-length message. + message.MergeFrom(bytes); + + // The "implicit" 0 did *not* overwrite the value. + // (This is the correct behaviour.) Assert.AreEqual(5, message.Int32Field); } + // All permutations of origin/merging value being null, zero (default) or non-default. + // As this is the in-memory version, we don't need to worry about the difference between implicit and explicit 0. + [Test] + [TestCase(null, null, null)] + [TestCase(null, 0, 0)] + [TestCase(null, 5, 5)] + [TestCase(0, null, 0)] + [TestCase(0, 0, 0)] + [TestCase(0, 5, 5)] + [TestCase(5, null, 5)] + [TestCase(5, 0, 5)] + [TestCase(5, 10, 10)] + public void MergingMessageWithZero(int? originValue, int? mergingValue, int? expectedResult) + { + // This differs from the MergingStreamCornerCase because when we merge message *objects*, + // we ignore default values from the "source". + var message1 = new TestWellKnownTypes { Int32Field = originValue }; + var message2 = new TestWellKnownTypes { Int32Field = mergingValue }; + message1.MergeFrom(message2); + Assert.AreEqual(expectedResult, message1.Int32Field); + } + [Test] public void UnknownFieldInWrapper() { @@ -345,5 +407,15 @@ namespace Google.Protobuf.WellKnownTypes var message = TestWellKnownTypes.Parser.ParseFrom(stream); Assert.AreEqual(6, message.Int32Field); } + + [Test] + public void ClearWithReflection() + { + // String and Bytes are the tricky ones here, as the CLR type of the property + // is the same between the wrapper and non-wrapper types. + var message = new TestWellKnownTypes { StringField = "foo" }; + TestWellKnownTypes.Descriptor.Fields[TestWellKnownTypes.StringFieldFieldNumber].Accessor.Clear(message); + Assert.IsNull(message.StringField); + } } } |