Commit e38294a6 authored by Jon Skeet's avatar Jon Skeet

First pass at the mutable API. Quite a bit more to do - in particular, it's pretty slow right now.

parent f5242682
syntax = "proto2";
syntax = "proto3";
// These proto descriptors have at one time been reported as an issue or defect.
// They are kept here to replicate the issue, and continue to verify the fix.
......@@ -9,65 +9,6 @@ option csharp_namespace = "UnitTest.Issues.TestProtos";
package unittest_issues;
option optimize_for = SPEED;
// The following is a representative set of features
/*
enum EnumOptions {
ONE = 0;
TWO = 1;
THREE = 2;
}
message TestBasicChild
{
repeated EnumOptions options = 3;
optional bytes binary = 4;
}
message TestBasicNoFields {
}
message TestBasicRescursive {
optional TestBasicRescursive child = 1;
}
message TestBasicMessage {
optional int64 number = 6;
repeated int32 numbers = 2;
optional string text = 3;
repeated string textlines = 700;
optional bool valid = 5;
optional TestBasicChild child = 1;
repeated group Children = 401
{
repeated EnumOptions options = 3;
optional bytes binary = 4;
}
extensions 100 to 199;
}
message TestBasicExtension {
required int32 number = 1;
}
extend TestBasicMessage {
optional EnumOptions extension_enum = 101;
optional string extension_text = 102;
repeated int32 extension_number = 103 [packed = true];
optional TestBasicExtension extension_message = 199;
}
// Issue for non-qualified type reference in new services generation
option (google.protobuf.csharp_file_options).service_generator_type = IRPCDISPATCH;
service TestGenericService {
rpc Foo(TestBasicNoFields) returns (TestBasicMessage);
rpc Bar(TestBasicNoFields) returns (TestBasicMessage);
}
*/
// Old issue 13: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=13
// New issue 309: https://github.com/google/protobuf/issues/309
......@@ -90,27 +31,17 @@ service TestGenericService {
// optional int32 _01 = 1;
// }
// Issue 28: Circular message dependencies result in null defaults for DefaultInstance
message MyMessageAReferenceB {
required MyMessageBReferenceA value = 1;
}
message MyMessageBReferenceA {
required MyMessageAReferenceB value = 1;
}
// issue 19 - negative enum values
enum NegativeEnum {
NEGATIVE_ENUM_ZERO = 0;
FiveBelow = -5;
MinusOne = -1;
Zero = 0;
}
message NegativeEnumMessage {
optional NegativeEnum value = 1;
repeated NegativeEnum values = 2;
NegativeEnum value = 1;
repeated NegativeEnum values = 2 [packed = false];
repeated NegativeEnum packed_values = 3 [packed=true];
}
......@@ -121,21 +52,22 @@ message DeprecatedChild {
}
enum DeprecatedEnum {
DEPRECATED_ZERO = 0;
one = 1;
}
message DeprecatedFieldsMessage {
optional int32 PrimitiveValue = 1 [deprecated = true];
int32 PrimitiveValue = 1 [deprecated = true];
repeated int32 PrimitiveArray = 2 [deprecated = true];
optional DeprecatedChild MessageValue = 3 [deprecated = true];
DeprecatedChild MessageValue = 3 [deprecated = true];
repeated DeprecatedChild MessageArray = 4 [deprecated = true];
optional DeprecatedEnum EnumValue = 5 [deprecated = true];
DeprecatedEnum EnumValue = 5 [deprecated = true];
repeated DeprecatedEnum EnumArray = 6 [deprecated = true];
}
// Issue 45: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=45
message ItemField {
optional int32 item = 1;
int32 item = 1;
}
This diff is collapsed.
......@@ -38,7 +38,7 @@ using System;
using System.Text;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
public class ByteStringTest
{
......
......@@ -37,11 +37,12 @@
using System;
using System.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.TestProtos;
using Google.Protobuf.Collections;
using Google.Protobuf.Descriptors;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
public class CodedInputStreamTest
{
......@@ -231,7 +232,7 @@ namespace Google.ProtocolBuffers
Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
}
/*
[Test]
public void ReadWholeMessage()
{
......@@ -273,7 +274,7 @@ namespace Google.ProtocolBuffers
unknownFields.MergeFieldFrom(tag, input1);
input2.SkipField();
}
}
}*/
/// <summary>
/// Test that a bug in SkipRawBytes has been fixed: if the skip
......@@ -290,7 +291,7 @@ namespace Google.ProtocolBuffers
input.PopLimit(limit);
Assert.AreEqual(2, input.ReadRawByte());
}
/*
public void ReadHugeBlob()
{
// Allocate and initialize a 1MB blob.
......@@ -318,7 +319,7 @@ namespace Google.ProtocolBuffers
.SetOptionalBytes(TestUtil.GetAllSet().OptionalBytes)
.Build();
TestUtil.AssertAllFieldsSet(message3);
}
}*/
[Test]
public void ReadMaliciouslyLargeBlob()
......@@ -348,12 +349,11 @@ namespace Google.ProtocolBuffers
{
if (depth == 0)
{
return TestRecursiveMessage.CreateBuilder().SetI(5).Build();
return new TestRecursiveMessage { I = 5 };
}
else
{
return TestRecursiveMessage.CreateBuilder()
.SetA(MakeRecursiveMessage(depth - 1)).Build();
return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) };
}
}
......@@ -361,12 +361,12 @@ namespace Google.ProtocolBuffers
{
if (depth == 0)
{
Assert.IsFalse(message.HasA);
Assert.IsNull(message.A);
Assert.AreEqual(5, message.I);
}
else
{
Assert.IsTrue(message.HasA);
Assert.IsNotNull(message.A);
AssertMessageDepth(message.A, depth - 1);
}
}
......@@ -377,15 +377,16 @@ namespace Google.ProtocolBuffers
ByteString data64 = MakeRecursiveMessage(64).ToByteString();
ByteString data65 = MakeRecursiveMessage(65).ToByteString();
AssertMessageDepth(TestRecursiveMessage.ParseFrom(data64), 64);
AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(data64), 64);
Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.ParseFrom(data65));
Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(data65));
CodedInputStream input = data64.CreateCodedInput();
input.SetRecursionLimit(8);
Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.ParseFrom(input));
Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input));
}
/*
[Test]
public void SizeLimit()
{
......@@ -396,7 +397,7 @@ namespace Google.ProtocolBuffers
input.SetSizeLimit(16);
Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.ParseFrom(input));
}
}*/
[Test]
public void ResetSizeCounter()
......@@ -465,17 +466,16 @@ namespace Google.ProtocolBuffers
}
}
enum TestNegEnum { None = 0, Value = -2 }
enum TestNegEnum : long { None = 0, Value = -2 }
[Test]
public void TestNegativeEnum()
{
byte[] bytes = new byte[10] { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
CodedInputStream input = CodedInputStream.CreateInstance(bytes);
object unk;
TestNegEnum val = TestNegEnum.None;
Assert.IsTrue(input.ReadEnum(ref val, out unk));
Assert.IsTrue(input.ReadEnum(ref val));
Assert.IsTrue(input.IsAtEnd);
Assert.AreEqual(TestNegEnum.Value, val);
}
......@@ -487,7 +487,7 @@ namespace Google.ProtocolBuffers
int msgSize = 1 + 1 + arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WritePackedInt32Array(8, "", arraySize, new int[] { 0, -1, -2, -3, -4, -5 });
output.WritePackedInt32Array(8, "", new RepeatedField<int> { 0, -1, -2, -3, -4, -5 });
Assert.AreEqual(0, output.SpaceLeft);
......@@ -497,15 +497,12 @@ namespace Google.ProtocolBuffers
Assert.IsTrue(input.ReadTag(out tag, out name));
List<TestNegEnum> values = new List<TestNegEnum>();
ICollection<object> unk;
input.ReadEnumArray(tag, name, values, out unk);
input.ReadEnumArray(tag, name, values);
Assert.AreEqual(2, values.Count);
Assert.AreEqual(6, values.Count);
Assert.AreEqual(TestNegEnum.None, values[0]);
Assert.AreEqual(TestNegEnum.Value, values[1]);
Assert.NotNull(unk);
Assert.AreEqual(4, unk.Count);
Assert.AreEqual(TestNegEnum.Value, values[2]);
// TODO(jonskeet): Test unknown value preservation
}
[Test]
......@@ -515,7 +512,7 @@ namespace Google.ProtocolBuffers
int msgSize = arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteInt32Array(8, "", new int[] { 0, -1, -2, -3, -4, -5 });
output.WriteInt32Array(8, "", new RepeatedField<int> { 0, -1, -2, -3, -4, -5 });
Assert.AreEqual(0, output.SpaceLeft);
......@@ -525,15 +522,12 @@ namespace Google.ProtocolBuffers
Assert.IsTrue(input.ReadTag(out tag, out name));
List<TestNegEnum> values = new List<TestNegEnum>();
ICollection<object> unk;
input.ReadEnumArray(tag, name, values, out unk);
input.ReadEnumArray(tag, name, values);
Assert.AreEqual(2, values.Count);
Assert.AreEqual(6, values.Count);
Assert.AreEqual(TestNegEnum.None, values[0]);
Assert.AreEqual(TestNegEnum.Value, values[1]);
Assert.NotNull(unk);
Assert.AreEqual(4, unk.Count);
Assert.AreEqual(TestNegEnum.Value, values[2]);
// TODO(jonskeet): Test unknown value preservation
}
//Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily
......
......@@ -37,10 +37,10 @@
using System;
using System.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.TestProtos;
using Google.Protobuf.Collections;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
public class CodedOutputStreamTest
{
......@@ -195,6 +195,7 @@ namespace Google.ProtocolBuffers
0x9abcdef012345678UL);
}
/*
[Test]
public void WriteWholeMessage()
{
......@@ -228,6 +229,7 @@ namespace Google.ProtocolBuffers
TestUtil.AssertEqualBytes(TestUtil.GetGoldenPackedFieldsMessage().ToByteArray(),
rawBytes);
}
*/
[Test]
public void EncodeZigZag32()
......@@ -294,25 +296,27 @@ namespace Google.ProtocolBuffers
public void TestNegativeEnumNoTag()
{
Assert.AreEqual(10, CodedOutputStream.ComputeInt32SizeNoTag(-2));
Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag(-2));
Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag(TestNegEnum.Value));
byte[] bytes = new byte[10];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteEnumNoTag(-2);
output.WriteEnumNoTag(TestNegEnum.Value);
Assert.AreEqual(0, output.SpaceLeft);
Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes));
}
enum TestNegEnum : long { None = 0, Value = -2 }
[Test]
public void TestNegativeEnumWithTag()
{
Assert.AreEqual(11, CodedOutputStream.ComputeInt32Size(8, -2));
Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, -2));
Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, TestNegEnum.Value));
byte[] bytes = new byte[11];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteEnum(8, "", -2, -2);
output.WriteEnum(8, "", TestNegEnum.Value);
Assert.AreEqual(0, output.SpaceLeft);
//fyi, 0x40 == 0x08 << 3 + 0, field num + wire format shift
......@@ -326,7 +330,8 @@ namespace Google.ProtocolBuffers
int msgSize = 1 + 1 + arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WritePackedEnumArray(8, "", arraySize, new int[] { 0, -1, -2, -3, -4, -5 });
output.WritePackedEnumArray(8, "", new RepeatedField<TestNegEnum> {
0, (TestNegEnum) (-1), TestNegEnum.Value, (TestNegEnum) (-3), (TestNegEnum) (-4), (TestNegEnum) (-5) });
Assert.AreEqual(0, output.SpaceLeft);
......@@ -350,8 +355,8 @@ namespace Google.ProtocolBuffers
int msgSize = arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteEnumArray(8, "", new int[] { 0, -1, -2, -3, -4, -5 });
output.WriteEnumArray(8, "", new RepeatedField<TestNegEnum> {
0, (TestNegEnum) (-1), TestNegEnum.Value, (TestNegEnum) (-3), (TestNegEnum) (-4), (TestNegEnum) (-5) });
Assert.AreEqual(0, output.SpaceLeft);
CodedInputStream input = CodedInputStream.CreateInstance(bytes);
......
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace Google.ProtocolBuffers.Collections
{
public class PopsicleListTest
{
[Test]
public void MutatingOperationsOnFrozenList()
{
PopsicleList<string> list = new PopsicleList<string>();
list.MakeReadOnly();
Assert.Throws<NotSupportedException>(() => list.Add(""));
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, ""));
Assert.Throws<NotSupportedException>(() => list.Remove(""));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => list.Add(new[] { "", "" }));
}
[Test]
public void NonMutatingOperationsOnFrozenList()
{
PopsicleList<string> list = new PopsicleList<string>();
list.MakeReadOnly();
Assert.IsFalse(list.Contains(""));
Assert.AreEqual(0, list.Count);
list.CopyTo(new string[5], 0);
list.GetEnumerator();
Assert.AreEqual(-1, list.IndexOf(""));
Assert.IsTrue(list.IsReadOnly);
}
[Test]
public void MutatingOperationsOnFluidList()
{
PopsicleList<string> list = new PopsicleList<string>();
list.Add("");
list.Clear();
list.Insert(0, "");
list.Remove("");
list.Add("x"); // Just to make the next call valid
list.RemoveAt(0);
}
[Test]
public void NonMutatingOperationsOnFluidList()
{
PopsicleList<string> list = new PopsicleList<string>();
Assert.IsFalse(list.Contains(""));
Assert.AreEqual(0, list.Count);
list.CopyTo(new string[5], 0);
list.GetEnumerator();
Assert.AreEqual(-1, list.IndexOf(""));
Assert.IsFalse(list.IsReadOnly);
}
[Test]
public void DoesNotAddNullEnumerable()
{
PopsicleList<string> list = new PopsicleList<string>();
Assert.Throws<ArgumentNullException>(() => list.Add((IEnumerable<string>) null));
}
[Test]
public void DoesNotAddRangeWithNull()
{
PopsicleList<string> list = new PopsicleList<string>();
// TODO(jonskeet): Change to ArgumentException? The argument isn't null...
Assert.Throws<ArgumentNullException>(() => list.Add(new[] {"a", "b", null}));
}
[Test]
public void DoesNotAddNull()
{
PopsicleList<string> list = new PopsicleList<string>();
Assert.Throws<ArgumentNullException>(() => list.Add((string) null));
}
[Test]
public void DoesNotSetNull()
{
PopsicleList<string> list = new PopsicleList<string>();
list.Add("a");
Assert.Throws<ArgumentNullException>(() => list[0] = null);
}
}
}
\ No newline at end of file
using System;
namespace Google.ProtocolBuffers.Compatibility
{
public class BinaryCompatibilityTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
byte[] bresult = message.ToByteArray();
return Convert.ToBase64String(bresult);
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
return builder.MergeFrom((byte[])Convert.FromBase64String((string)message), registry);
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.Serialization;
using NUnit.Framework;
namespace Google.ProtocolBuffers.Compatibility
{
[TestFixture]
public class DictionaryCompatibilityTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
DictionaryWriter writer = new DictionaryWriter();
writer.WriteMessage(message);
return writer.ToDictionary();
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
new DictionaryReader((IDictionary<string, object>)message).Merge(builder);
return builder;
}
protected override void AssertOutputEquals(object lhs, object rhs)
{
IDictionary<string, object> left = (IDictionary<string, object>)lhs;
IDictionary<string, object> right = (IDictionary<string, object>)rhs;
Assert.AreEqual(
String.Join(",", new List<string>(left.Keys).ToArray()),
String.Join(",", new List<string>(right.Keys).ToArray())
);
}
}
}
\ No newline at end of file
using System.IO;
using Google.ProtocolBuffers.Serialization;
using NUnit.Framework;
namespace Google.ProtocolBuffers.Compatibility
{
[TestFixture]
public class JsonCompatibilityTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
StringWriter sw = new StringWriter();
JsonFormatWriter.CreateInstance(sw)
.WriteMessage(message);
return sw.ToString();
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
JsonFormatReader.CreateInstance((string)message).Merge(builder);
return builder;
}
}
[TestFixture]
public class JsonCompatibilityFormattedTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
StringWriter sw = new StringWriter();
JsonFormatWriter.CreateInstance(sw)
.Formatted()
.WriteMessage(message);
return sw.ToString();
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
JsonFormatReader.CreateInstance((string)message).Merge(builder);
return builder;
}
}
}
\ No newline at end of file
using System.IO;
using NUnit.Framework;
namespace Google.ProtocolBuffers.Compatibility
{
static class TestResources
{
public static byte[] google_message1
{
get
{
Stream resource = typeof(TestResources).Assembly.GetManifestResourceStream(
typeof(TestResources).Namespace + ".google_message1.dat");
Assert.NotNull(resource);
byte[] bytes = new byte[resource.Length];
int amtRead = resource.Read(bytes, 0, bytes.Length);
Assert.AreEqual(bytes.Length, amtRead);
return bytes;
}
}
public static byte[] google_message2
{
get
{
Stream resource = typeof(TestResources).Assembly.GetManifestResourceStream(
typeof(TestResources).Namespace + ".google_message2.dat");
Assert.NotNull(resource);
byte[] bytes = new byte[resource.Length];
int amtRead = resource.Read(bytes, 0, bytes.Length);
Assert.AreEqual(bytes.Length, amtRead);
return bytes;
}
}
}
}
using System.IO;
using NUnit.Framework;
namespace Google.ProtocolBuffers.Compatibility
{
[TestFixture]
public class TextCompatibilityTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
StringWriter text = new StringWriter();
message.PrintTo(text);
return text.ToString();
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
TextFormat.Merge(new StringReader((string)message), registry, (IBuilder)builder);
return builder;
}
//This test can take a very long time to run.
[Test]
public override void RoundTripMessage2OptimizeSize()
{
//base.RoundTripMessage2OptimizeSize();
}
//This test can take a very long time to run.
[Test]
public override void RoundTripMessage2OptimizeSpeed()
{
//base.RoundTripMessage2OptimizeSpeed();
}
}
}
\ No newline at end of file
using System.IO;
using System.Xml;
using Google.ProtocolBuffers.Serialization;
using NUnit.Framework;
namespace Google.ProtocolBuffers.Compatibility
{
[TestFixture]
public class XmlCompatibilityTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
StringWriter text = new StringWriter();
XmlFormatWriter writer = XmlFormatWriter.CreateInstance(text);
writer.WriteMessage("root", message);
return text.ToString();
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
XmlFormatReader reader = XmlFormatReader.CreateInstance((string)message);
return reader.Merge("root", builder, registry);
}
}
[TestFixture]
public class XmlCompatibilityFormattedTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
StringWriter text = new StringWriter();
XmlWriter xwtr = XmlWriter.Create(text, new XmlWriterSettings { Indent = true, IndentChars = " " });
XmlFormatWriter writer = XmlFormatWriter.CreateInstance(xwtr).SetOptions(XmlWriterOptions.OutputNestedArrays);
writer.WriteMessage("root", message);
return text.ToString();
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
XmlFormatReader reader = XmlFormatReader.CreateInstance((string)message).SetOptions(XmlReaderOptions.ReadNestedArrays);
return reader.Merge("root", builder, registry);
}
}
}
\ No newline at end of file
using System;
using System.Reflection;
using UnitTest.Issues.TestProtos;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
public class DeprecatedMemberTest
{
......@@ -16,84 +16,8 @@ namespace Google.ProtocolBuffers
[Test]
public void TestDepreatedPrimitiveValue()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasPrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasPrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearPrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetPrimitiveValue"));
}
[Test]
public void TestDepreatedPrimitiveArray()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetPrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetPrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetPrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddPrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangePrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearPrimitiveArray"));
}
[Test]
public void TestDepreatedMessageValue()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasMessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasMessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("MergeMessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearMessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageValue", new[] { typeof(DeprecatedChild) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageValue", new[] { typeof(DeprecatedChild.Builder) }));
}
[Test]
public void TestDepreatedMessageArray()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetMessageArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetMessageArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageArray", new[] { typeof(int), typeof(DeprecatedChild) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageArray", new[] { typeof(int), typeof(DeprecatedChild.Builder) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddMessageArray", new[] { typeof(DeprecatedChild) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddMessageArray", new[] { typeof(DeprecatedChild.Builder) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangeMessageArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearMessageArray"));
}
[Test]
public void TestDepreatedEnumValue()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasEnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasEnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearEnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetEnumValue"));
AssertIsDeprecated(typeof(TestDeprecatedFields).GetProperty("DeprecatedInt32"));
}
[Test]
public void TestDepreatedEnumArray()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangeEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearEnumArray"));
}
}
}
This diff is collapsed.
This diff is collapsed.
using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class GeneratedBuilderTest
{
class OneTimeEnumerator<T> : IEnumerable<T>
{
readonly T _item;
bool _enumerated;
public OneTimeEnumerator(T item)
{
_item = item;
}
public IEnumerator<T> GetEnumerator()
{
Assert.IsFalse(_enumerated);
_enumerated = true;
yield return _item;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
[Test]
public void DoesNotEnumerateTwiceForMessageList()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRangeRepeatedForeignMessage(new OneTimeEnumerator<ForeignMessage>(ForeignMessage.DefaultInstance));
}
[Test]
public void DoesNotEnumerateTwiceForPrimitiveList()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRangeRepeatedInt32(new OneTimeEnumerator<int>(1));
}
[Test]
public void DoesNotEnumerateTwiceForStringList()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRangeRepeatedString(new OneTimeEnumerator<string>("test"));
}
[Test]
public void DoesNotEnumerateTwiceForEnumList()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRangeRepeatedForeignEnum(new OneTimeEnumerator<ForeignEnum>(ForeignEnum.FOREIGN_BAR));
}
[Test]
public void DoesNotAddNullToMessageListByAddRange()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
Assert.Throws<ArgumentNullException>(() => b.AddRangeRepeatedForeignMessage(new ForeignMessage[] { null }));
}
[Test]
public void DoesNotAddNullToMessageListByAdd()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
Assert.Throws<ArgumentNullException>(() => b.AddRepeatedForeignMessage((ForeignMessage)null));
}
[Test]
public void DoesNotAddNullToMessageListBySet()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRepeatedForeignMessage(ForeignMessage.DefaultInstance);
Assert.Throws<ArgumentNullException>(() => b.SetRepeatedForeignMessage(0, (ForeignMessage)null));
}
[Test]
public void DoesNotAddNullToStringListByAddRange()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
Assert.Throws<ArgumentNullException>(() => b.AddRangeRepeatedString(new String[] { null }));
}
[Test]
public void DoesNotAddNullToStringListByAdd()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
Assert.Throws<ArgumentNullException>(() => b.AddRepeatedString(null));
}
[Test]
public void DoesNotAddNullToStringListBySet()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRepeatedString("one");
Assert.Throws<ArgumentNullException>(() => b.SetRepeatedString(0, null));
}
}
}
......@@ -34,13 +34,12 @@
#endregion
using Google.ProtocolBuffers.Descriptors;
using Google.Protobuf.Descriptors;
using UnitTest.Issues.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
/// <summary>
/// Tests for issues which aren't easily compartmentalized into other unit tests.
......@@ -51,10 +50,11 @@ namespace Google.ProtocolBuffers
[Test]
public void FieldCalledItem()
{
ItemField message = new ItemField.Builder { Item = 3 }.Build();
ItemField message = new ItemField { Item = 3 };
FieldDescriptor field = ItemField.Descriptor.FindFieldByName("item");
Assert.NotNull(field);
Assert.AreEqual(3, (int)message[field]);
// TODO(jonskeet): Reflection...
// Assert.AreEqual(3, (int)message[field]);
}
}
}
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
using NestedMessage = Google.ProtocolBuffers.TestProtos.TestAllTypes.Types.NestedMessage;
namespace Google.ProtocolBuffers
{
public class MessageStreamIteratorTest
{
[Test]
public void ThreeMessagesInMemory()
{
MemoryStream stream = new MemoryStream(MessageStreamWriterTest.ThreeMessageData);
IEnumerable<NestedMessage> iterator = MessageStreamIterator<NestedMessage>.FromStreamProvider(() => stream);
List<NestedMessage> messages = new List<NestedMessage>(iterator);
Assert.AreEqual(3, messages.Count);
Assert.AreEqual(5, messages[0].Bb);
Assert.AreEqual(1500, messages[1].Bb);
Assert.IsFalse(messages[2].HasBb);
}
[Test]
public void ManyMessagesShouldNotTriggerSizeAlert()
{
int messageSize = TestUtil.GetAllSet().SerializedSize;
// Enough messages to trigger the alert unless we've reset the size
// Note that currently we need to make this big enough to copy two whole buffers,
// as otherwise when we refill the buffer the second type, the alert triggers instantly.
int correctCount = (CodedInputStream.BufferSize*2)/messageSize + 1;
using (MemoryStream stream = new MemoryStream())
{
MessageStreamWriter<TestAllTypes> writer = new MessageStreamWriter<TestAllTypes>(stream);
for (int i = 0; i < correctCount; i++)
{
writer.Write(TestUtil.GetAllSet());
}
writer.Flush();
stream.Position = 0;
int count = 0;
foreach (var message in MessageStreamIterator<TestAllTypes>.FromStreamProvider(() => stream)
.WithSizeLimit(CodedInputStream.BufferSize*2))
{
count++;
TestUtil.AssertAllFieldsSet(message);
}
Assert.AreEqual(correctCount, count);
}
}
}
}
\ No newline at end of file
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System.IO;
using NUnit.Framework;
using NestedMessage = Google.ProtocolBuffers.TestProtos.TestAllTypes.Types.NestedMessage;
namespace Google.ProtocolBuffers
{
public class MessageStreamWriterTest
{
internal static readonly byte[] ThreeMessageData = new byte[]
{
(1 << 3) | 2, 2,
// Field 1, 2 bytes long (first message)
(1 << 3) | 0, 5, // Field 1, value 5
(1 << 3) | 2, 3,
// Field 1, 3 bytes long (second message)
(1 << 3) | 0, (1500 & 0x7f) | 0x80, 1500 >> 7,
// Field 1, value 1500
(1 << 3) | 2, 0, // Field 1, no data (third message)
};
[Test]
public void ThreeMessages()
{
NestedMessage message1 = new NestedMessage.Builder {Bb = 5}.Build();
NestedMessage message2 = new NestedMessage.Builder {Bb = 1500}.Build();
NestedMessage message3 = new NestedMessage.Builder().Build();
byte[] data;
using (MemoryStream stream = new MemoryStream())
{
MessageStreamWriter<NestedMessage> writer = new MessageStreamWriter<NestedMessage>(stream);
writer.Write(message1);
writer.Write(message2);
writer.Write(message3);
writer.Flush();
data = stream.ToArray();
}
TestUtil.AssertEqualBytes(ThreeMessageData, data);
}
}
}
\ No newline at end of file
This diff is collapsed.
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class MessageUtilTest
{
[Test]
public void NullTypeName()
{
Assert.Throws<ArgumentNullException>(() => MessageUtil.GetDefaultMessage((string) null));
}
[Test]
public void InvalidTypeName()
{
Assert.Throws<ArgumentException>(() => MessageUtil.GetDefaultMessage("invalidtypename"));
}
[Test]
public void ValidTypeName()
{
Assert.AreSame(TestAllTypes.DefaultInstance,
MessageUtil.GetDefaultMessage(typeof(TestAllTypes).AssemblyQualifiedName));
}
[Test]
public void NullType()
{
Assert.Throws<ArgumentNullException>(() => MessageUtil.GetDefaultMessage((Type)null));
}
[Test]
public void NonMessageType()
{
Assert.Throws<ArgumentException>(() => MessageUtil.GetDefaultMessage(typeof(string)));
}
[Test]
public void ValidType()
{
Assert.AreSame(TestAllTypes.DefaultInstance, MessageUtil.GetDefaultMessage(typeof(TestAllTypes)));
}
}
}
\ No newline at end of file
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class NameHelpersTest
{
[Test]
public void UnderscoresToPascalCase()
{
Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("Foo_bar"));
Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("foo_bar"));
Assert.AreEqual("Foo0Bar", NameHelpers.UnderscoresToPascalCase("Foo0bar"));
Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("Foo_+_Bar"));
Assert.AreEqual("Bar", NameHelpers.UnderscoresToPascalCase("__+bar"));
Assert.AreEqual("Bar", NameHelpers.UnderscoresToPascalCase("bar_"));
Assert.AreEqual("_0Bar", NameHelpers.UnderscoresToPascalCase("_0bar"));
Assert.AreEqual("_1Bar", NameHelpers.UnderscoresToPascalCase("_1_bar"));
}
[Test]
public void UnderscoresToCamelCase()
{
Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("Foo_bar"));
Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("foo_bar"));
Assert.AreEqual("foo0Bar", NameHelpers.UnderscoresToCamelCase("Foo0bar"));
Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("Foo_+_Bar"));
Assert.AreEqual("bar", NameHelpers.UnderscoresToCamelCase("__+bar"));
Assert.AreEqual("bar", NameHelpers.UnderscoresToCamelCase("bar_"));
Assert.AreEqual("_0Bar", NameHelpers.UnderscoresToCamelCase("_0bar"));
Assert.AreEqual("_1Bar", NameHelpers.UnderscoresToCamelCase("_1_bar"));
}
[Test]
public void StripSuffix()
{
string text = "FooBar";
Assert.IsFalse(NameHelpers.StripSuffix(ref text, "Foo"));
Assert.AreEqual("FooBar", text);
Assert.IsTrue(NameHelpers.StripSuffix(ref text, "Bar"));
Assert.AreEqual("Foo", text);
}
}
}
\ No newline at end of file
......@@ -8,8 +8,8 @@
<ProjectGuid>{DD01ED24-3750-4567-9A23-1DB676A15610}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers</RootNamespace>
<AssemblyName>Google.ProtocolBuffers.Test</AssemblyName>
<RootNamespace>Google.Protobuf</RootNamespace>
<AssemblyName>Google.Protobuf.Test</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SignAssembly>true</SignAssembly>
......@@ -71,79 +71,37 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AbstractMessageTest.cs" />
<Compile Include="ByteStringTest.cs" />
<Compile Include="FieldPresenceTest.cs" />
<Compile Include="CodedInputStreamTest.cs" />
<Compile Include="CodedOutputStreamTest.cs" />
<Compile Include="Collections\PopsicleListTest.cs" />
<Compile Include="Compatibility\BinaryCompatibilityTests.cs" />
<Compile Include="Compatibility\CompatibilityTests.cs" />
<Compile Include="Compatibility\DictionaryCompatibilityTests.cs" />
<Compile Include="Compatibility\JsonCompatibilityTests.cs" />
<Compile Include="Compatibility\TestResources.cs" />
<Compile Include="Compatibility\TextCompatibilityTests.cs" />
<Compile Include="Compatibility\XmlCompatibilityTests.cs" />
<Compile Include="TestProtos\GoogleSize.cs" />
<Compile Include="TestProtos\GoogleSpeed.cs" />
<Compile Include="TestProtos\Unittest.cs" />
<Compile Include="TestProtos\UnittestCustomOptions.cs" />
<Compile Include="TestProtos\UnittestDropUnknownFields.cs" />
<Compile Include="TestProtos\UnittestEnormousDescriptor.cs" />
<Compile Include="TestProtos\UnittestExtrasXmltest.cs" />
<Compile Include="TestProtos\UnittestImport.cs" />
<Compile Include="TestProtos\UnittestImportPublic.cs" />
<Compile Include="GeneratedMessageTest.cs" />
<Compile Include="RepeatedFieldTest.cs" />
<Compile Include="TestProtos\UnittestImportProto3.cs" />
<Compile Include="TestProtos\UnittestImportPublicProto3.cs" />
<Compile Include="TestProtos\UnittestIssues.cs" />
<Compile Include="TestProtos\UnittestMset.cs" />
<Compile Include="TestProtos\UnittestNoFieldPresence.cs" />
<Compile Include="TestProtos\UnittestOptimizeFor.cs" />
<Compile Include="TestProtos\UnknownEnumTest.cs" />
<Compile Include="TestResources.cs" />
<Compile Include="TestReaderForUrlEncoded.cs" />
<Compile Include="TestProtos\UnittestProto3.cs" />
<Compile Include="DeprecatedMemberTest.cs" />
<Compile Include="DescriptorsTest.cs" />
<Compile Include="DynamicMessageTest.cs" />
<Compile Include="ExtendableMessageTest.cs" />
<Compile Include="GeneratedBuilderTest.cs" />
<Compile Include="GeneratedMessageTest.cs" />
<Compile Include="IssuesTest.cs" />
<Compile Include="MessageStreamIteratorTest.cs" />
<Compile Include="MessageStreamWriterTest.cs" />
<Compile Include="MessageTest.cs" />
<Compile Include="MessageUtilTest.cs" />
<Compile Include="NameHelpersTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ReflectionTester.cs" />
<Compile Include="ReusableBuilderTest.cs" />
<Compile Include="TestCornerCases.cs" />
<Compile Include="TestMimeMessageFormats.cs" />
<Compile Include="TestUtil.cs" />
<Compile Include="TestWriterFormatJson.cs" />
<Compile Include="TestWriterFormatXml.cs" />
<Compile Include="TextFormatTest.cs" />
<Compile Include="UnknownFieldSetTest.cs" />
<Compile Include="WireFormatTest.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ProtocolBuffers.Serialization\ProtocolBuffers.Serialization.csproj">
<Project>{231391AF-449C-4a39-986C-AD7F270F4750}</Project>
<Name>ProtocolBuffers.Serialization</Name>
</ProjectReference>
<ProjectReference Include="..\ProtocolBuffers\ProtocolBuffers.csproj">
<Project>{6908BDCE-D925-43F3-94AC-A531E6DF2591}</Project>
<Name>ProtocolBuffers</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Compatibility\google_message1.dat" />
<EmbeddedResource Include="Compatibility\google_message2.dat" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<ItemGroup>
<Folder Include="Collections\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
......
This diff is collapsed.
using System;
using System.Collections.Generic;
using Google.Protobuf.Collections;
using NUnit.Framework;
namespace Google.Protobuf
{
public class RepeatedFieldTest
{
[Test]
public void NullValuesRejected()
{
var list = new RepeatedField<string>();
Assert.Throws<ArgumentNullException>(() => list.Add((string) null));
Assert.Throws<ArgumentNullException>(() => list.Add((IEnumerable<string>) null));
Assert.Throws<ArgumentNullException>(() => list.Add((RepeatedField<string>)null));
Assert.Throws<ArgumentNullException>(() => list.Contains(null));
Assert.Throws<ArgumentNullException>(() => list.IndexOf(null));
}
[Test]
public void Add_SingleItem()
{
var list = new RepeatedField<string>();
list.Add("foo");
Assert.AreEqual(1, list.Count);
Assert.AreEqual("foo", list[0]);
}
[Test]
public void Add_Sequence()
{
var list = new RepeatedField<string>();
list.Add(new[] { "foo", "bar" });
Assert.AreEqual(2, list.Count);
Assert.AreEqual("foo", list[0]);
Assert.AreEqual("bar", list[1]);
}
[Test]
public void Add_RepeatedField()
{
var list = new RepeatedField<string>();
list.Add(new RepeatedField<string> { "foo", "bar" });
Assert.AreEqual(2, list.Count);
Assert.AreEqual("foo", list[0]);
Assert.AreEqual("bar", list[1]);
}
}
}
using System;
using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.TestProtos;
using UnitTest.Issues.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class ReusableBuilderTest
{
//Issue 28: Circular message dependencies result in null defaults for DefaultInstance
[Test]
public void EnsureStaticCicularReference()
{
MyMessageAReferenceB ab = MyMessageAReferenceB.DefaultInstance;
Assert.NotNull(ab);
Assert.NotNull(ab.Value);
MyMessageBReferenceA ba = MyMessageBReferenceA.DefaultInstance;
Assert.NotNull(ba);
Assert.NotNull(ba.Value);
}
[Test]
public void TestModifyDefaultInstance()
{
//verify that the default instance has correctly been marked as read-only
Assert.AreEqual(typeof(PopsicleList<bool>), TestAllTypes.DefaultInstance.RepeatedBoolList.GetType());
PopsicleList<bool> list = (PopsicleList<bool>)TestAllTypes.DefaultInstance.RepeatedBoolList;
Assert.IsTrue(list.IsReadOnly);
}
[Test]
public void TestUnmodifiedDefaultInstance()
{
//Simply calling ToBuilder().Build() no longer creates a copy of the message
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void BuildMultipleWithoutChange()
{
//Calling Build() or BuildPartial() does not require a copy of the message
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
builder.SetDefaultBool(true);
TestAllTypes first = builder.BuildPartial();
//Still the same instance?
Assert.IsTrue(ReferenceEquals(first, builder.Build()));
//Still the same instance?
Assert.IsTrue(ReferenceEquals(first, builder.BuildPartial().ToBuilder().Build()));
}
[Test]
public void MergeFromDefaultInstance()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.MergeFrom(TestAllTypes.DefaultInstance);
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void BuildNewBuilderIsDefaultInstance()
{
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, new TestAllTypes.Builder().Build()));
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, TestAllTypes.CreateBuilder().Build()));
//last test, if you clear a builder it reverts to default instance
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance,
TestAllTypes.CreateBuilder().SetOptionalBool(true).Build().ToBuilder().Clear().Build()));
}
[Test]
public void BuildModifyAndRebuild()
{
TestAllTypes.Builder b1 = new TestAllTypes.Builder();
b1.SetDefaultInt32(1);
b1.AddRepeatedInt32(2);
b1.SetOptionalForeignMessage(ForeignMessage.DefaultInstance);
TestAllTypes m1 = b1.Build();
b1.SetDefaultInt32(5);
b1.AddRepeatedInt32(6);
b1.SetOptionalForeignMessage(b1.OptionalForeignMessage.ToBuilder().SetC(7));
TestAllTypes m2 = b1.Build();
Assert.AreEqual("{\"optional_foreign_message\":{},\"repeated_int32\":[2],\"default_int32\":1}", Extensions.ToJson(m1));
Assert.AreEqual("{\"optional_foreign_message\":{\"c\":7},\"repeated_int32\":[2,6],\"default_int32\":5}", Extensions.ToJson(m2));
}
[Test]
public void CloneOnChangePrimitive()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.SetDefaultBool(true);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnAddRepeatedBool()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.AddRepeatedBool(true);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnGetRepeatedBoolList()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
GC.KeepAlive(builder.RepeatedBoolList);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnChangeMessage()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.SetOptionalForeignMessage(new ForeignMessage.Builder());
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnClearMessage()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.ClearOptionalForeignMessage();
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnGetRepeatedForeignMessageList()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
GC.KeepAlive(builder.RepeatedForeignMessageList);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnChangeEnumValue()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.SetOptionalForeignEnum(ForeignEnum.FOREIGN_BAR);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnGetRepeatedForeignEnumList()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
GC.KeepAlive(builder.RepeatedForeignEnumList);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
}
}
using UnitTest.Issues.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
public class TestCornerCases
{
[Test]
public void TestRoundTripNegativeEnums()
{
NegativeEnumMessage msg = NegativeEnumMessage.CreateBuilder()
.SetValue(NegativeEnum.MinusOne) //11
.AddValues(NegativeEnum.Zero) //2
.AddValues(NegativeEnum.MinusOne) //11
.AddValues(NegativeEnum.FiveBelow) //11
//2
.AddPackedValues(NegativeEnum.Zero) //1
.AddPackedValues(NegativeEnum.MinusOne) //10
.AddPackedValues(NegativeEnum.FiveBelow) //10
.Build();
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 }
};
Assert.AreEqual(58, msg.SerializedSize);
Assert.AreEqual(58, msg.CalculateSize());
byte[] bytes = new byte[58];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
......@@ -27,7 +23,7 @@ namespace Google.ProtocolBuffers
msg.WriteTo(output);
Assert.AreEqual(0, output.SpaceLeft);
NegativeEnumMessage copy = NegativeEnumMessage.ParseFrom(bytes);
NegativeEnumMessage copy = NegativeEnumMessage.Parser.ParseFrom(bytes);
Assert.AreEqual(msg, copy);
}
}
......
This diff is collapsed.
This diff is collapsed.
using System;
using System.IO;
using System.Text;
using Google.ProtocolBuffers.TestProtos;
using Google.ProtocolBuffers.Serialization.Http;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class TestReaderForUrlEncoded
{
[Test]
public void Example_FromQueryString()
{
Uri sampleUri = new Uri("http://sample.com/Path/File.ext?text=two+three%20four&valid=true&numbers=1&numbers=2", UriKind.Absolute);
ICodedInputStream input = FormUrlEncodedReader.CreateInstance(sampleUri.Query);
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
builder.MergeFrom(input);
TestXmlMessage message = builder.Build();
Assert.AreEqual(true, message.Valid);
Assert.AreEqual("two three four", message.Text);
Assert.AreEqual(2, message.NumbersCount);
Assert.AreEqual(1, message.NumbersList[0]);
Assert.AreEqual(2, message.NumbersList[1]);
}
[Test]
public void Example_FromFormData()
{
Stream rawPost = new MemoryStream(Encoding.UTF8.GetBytes("text=two+three%20four&valid=true&numbers=1&numbers=2"), false);
ICodedInputStream input = FormUrlEncodedReader.CreateInstance(rawPost);
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
builder.MergeFrom(input);
TestXmlMessage message = builder.Build();
Assert.AreEqual(true, message.Valid);
Assert.AreEqual("two three four", message.Text);
Assert.AreEqual(2, message.NumbersCount);
Assert.AreEqual(1, message.NumbersList[0]);
Assert.AreEqual(2, message.NumbersList[1]);
}
[Test]
public void TestEmptyValues()
{
ICodedInputStream input = FormUrlEncodedReader.CreateInstance("valid=true&text=&numbers=1");
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
builder.MergeFrom(input);
Assert.IsTrue(builder.Valid);
Assert.IsTrue(builder.HasText);
Assert.AreEqual("", builder.Text);
Assert.AreEqual(1, builder.NumbersCount);
Assert.AreEqual(1, builder.NumbersList[0]);
}
[Test]
public void TestNoValue()
{
ICodedInputStream input = FormUrlEncodedReader.CreateInstance("valid=true&text&numbers=1");
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
builder.MergeFrom(input);
Assert.IsTrue(builder.Valid);
Assert.IsTrue(builder.HasText);
Assert.AreEqual("", builder.Text);
Assert.AreEqual(1, builder.NumbersCount);
Assert.AreEqual(1, builder.NumbersList[0]);
}
[Test]
public void FormUrlEncodedReaderDoesNotSupportChildren()
{
ICodedInputStream input = FormUrlEncodedReader.CreateInstance("child=uh0");
Assert.Throws<NotSupportedException>(() => TestXmlMessage.CreateBuilder().MergeFrom(input));
}
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -36,7 +36,7 @@
using System;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
/// <summary>
/// Provides a utility routine to copy small arrays much more quickly than Buffer.BlockCopy
......
This diff is collapsed.
......@@ -33,7 +33,7 @@ using System;
using System.Collections;
using System.Collections.Generic;
namespace Google.ProtocolBuffers.Collections
namespace Google.Protobuf.Collections
{
/// <summary>
/// Utility class for dictionaries.
......
......@@ -32,7 +32,7 @@
using System;
using System.Collections;
namespace Google.ProtocolBuffers.Collections
namespace Google.Protobuf.Collections
{
/// <summary>
/// Utility class for IEnumerable (and potentially the generic version in the future).
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment