WireFormatTest.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // http://github.com/jskeet/dotnet-protobufs/
  5. // Original C++/Java/Python code:
  6. // http://code.google.com/p/protobuf/
  7. //
  8. // Redistribution and use in source and binary forms, with or without
  9. // modification, are permitted provided that the following conditions are
  10. // met:
  11. //
  12. // * Redistributions of source code must retain the above copyright
  13. // notice, this list of conditions and the following disclaimer.
  14. // * Redistributions in binary form must reproduce the above
  15. // copyright notice, this list of conditions and the following disclaimer
  16. // in the documentation and/or other materials provided with the
  17. // distribution.
  18. // * Neither the name of Google Inc. nor the names of its
  19. // contributors may be used to endorse or promote products derived from
  20. // this software without specific prior written permission.
  21. //
  22. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  25. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  26. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  27. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  28. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  30. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. #endregion
  34. using System.IO;
  35. using System.Reflection;
  36. using Google.ProtocolBuffers.Descriptors;
  37. using Google.ProtocolBuffers.TestProtos;
  38. using Microsoft.VisualStudio.TestTools.UnitTesting;
  39. namespace Google.ProtocolBuffers
  40. {
  41. [TestClass]
  42. public class WireFormatTest
  43. {
  44. /// <summary>
  45. /// Keeps the attributes on FieldType and the switch statement in WireFormat in sync.
  46. /// </summary>
  47. [TestMethod]
  48. public void FieldTypeToWireTypeMapping()
  49. {
  50. foreach (FieldInfo field in typeof(FieldType).GetFields(BindingFlags.Static | BindingFlags.Public))
  51. {
  52. FieldType fieldType = (FieldType) field.GetValue(null);
  53. FieldMappingAttribute mapping =
  54. (FieldMappingAttribute) field.GetCustomAttributes(typeof(FieldMappingAttribute), false)[0];
  55. Assert.AreEqual(mapping.WireType, WireFormat.GetWireType(fieldType));
  56. }
  57. }
  58. [TestMethod]
  59. public void Serialization()
  60. {
  61. TestAllTypes message = TestUtil.GetAllSet();
  62. ByteString rawBytes = message.ToByteString();
  63. Assert.AreEqual(rawBytes.Length, message.SerializedSize);
  64. TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
  65. TestUtil.AssertAllFieldsSet(message2);
  66. }
  67. [TestMethod]
  68. public void SerializationPacked()
  69. {
  70. TestPackedTypes message = TestUtil.GetPackedSet();
  71. ByteString rawBytes = message.ToByteString();
  72. Assert.AreEqual(rawBytes.Length, message.SerializedSize);
  73. TestPackedTypes message2 = TestPackedTypes.ParseFrom(rawBytes);
  74. TestUtil.AssertPackedFieldsSet(message2);
  75. }
  76. [TestMethod]
  77. public void SerializeExtensions()
  78. {
  79. // TestAllTypes and TestAllExtensions should have compatible wire formats,
  80. // so if we serialize a TestAllExtensions then parse it as TestAllTypes
  81. // it should work.
  82. TestAllExtensions message = TestUtil.GetAllExtensionsSet();
  83. ByteString rawBytes = message.ToByteString();
  84. Assert.AreEqual(rawBytes.Length, message.SerializedSize);
  85. TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
  86. TestUtil.AssertAllFieldsSet(message2);
  87. }
  88. [TestMethod]
  89. public void SerializePackedExtensions()
  90. {
  91. // TestPackedTypes and TestPackedExtensions should have compatible wire
  92. // formats; check that they serialize to the same string.
  93. TestPackedExtensions message = TestUtil.GetPackedExtensionsSet();
  94. ByteString rawBytes = message.ToByteString();
  95. TestPackedTypes message2 = TestUtil.GetPackedSet();
  96. ByteString rawBytes2 = message2.ToByteString();
  97. Assert.AreEqual(rawBytes, rawBytes2);
  98. }
  99. [TestMethod]
  100. public void SerializeDelimited()
  101. {
  102. MemoryStream stream = new MemoryStream();
  103. TestUtil.GetAllSet().WriteDelimitedTo(stream);
  104. stream.WriteByte(12);
  105. TestUtil.GetPackedSet().WriteDelimitedTo(stream);
  106. stream.WriteByte(34);
  107. stream.Position = 0;
  108. TestUtil.AssertAllFieldsSet(TestAllTypes.ParseDelimitedFrom(stream));
  109. Assert.AreEqual(12, stream.ReadByte());
  110. TestUtil.AssertPackedFieldsSet(TestPackedTypes.ParseDelimitedFrom(stream));
  111. Assert.AreEqual(34, stream.ReadByte());
  112. Assert.AreEqual(-1, stream.ReadByte());
  113. }
  114. [TestMethod]
  115. public void ParseExtensions()
  116. {
  117. // TestAllTypes and TestAllExtensions should have compatible wire formats,
  118. // so if we serealize a TestAllTypes then parse it as TestAllExtensions
  119. // it should work.
  120. TestAllTypes message = TestUtil.GetAllSet();
  121. ByteString rawBytes = message.ToByteString();
  122. ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
  123. TestUtil.RegisterAllExtensions(registry);
  124. registry = registry.AsReadOnly();
  125. TestAllExtensions message2 = TestAllExtensions.ParseFrom(rawBytes, registry);
  126. TestUtil.AssertAllExtensionsSet(message2);
  127. }
  128. [TestMethod]
  129. public void ParsePackedExtensions()
  130. {
  131. // Ensure that packed extensions can be properly parsed.
  132. TestPackedExtensions message = TestUtil.GetPackedExtensionsSet();
  133. ByteString rawBytes = message.ToByteString();
  134. ExtensionRegistry registry = TestUtil.CreateExtensionRegistry();
  135. TestPackedExtensions message2 = TestPackedExtensions.ParseFrom(rawBytes, registry);
  136. TestUtil.AssertPackedExtensionsSet(message2);
  137. }
  138. [TestMethod]
  139. public void ExtensionsSerializedSize()
  140. {
  141. Assert.AreEqual(TestUtil.GetAllSet().SerializedSize, TestUtil.GetAllExtensionsSet().SerializedSize);
  142. }
  143. private static void AssertFieldsInOrder(ByteString data)
  144. {
  145. CodedInputStream input = data.CreateCodedInput();
  146. uint previousTag = 0;
  147. uint tag;
  148. string name;
  149. while (input.ReadTag(out tag, out name))
  150. {
  151. Assert.IsTrue(tag > previousTag);
  152. previousTag = tag;
  153. input.SkipField();
  154. }
  155. }
  156. [TestMethod]
  157. public void InterleavedFieldsAndExtensions()
  158. {
  159. // Tests that fields are written in order even when extension ranges
  160. // are interleaved with field numbers.
  161. ByteString data =
  162. TestFieldOrderings.CreateBuilder()
  163. .SetMyInt(1)
  164. .SetMyString("foo")
  165. .SetMyFloat(1.0F)
  166. .SetExtension(UnitTestProtoFile.MyExtensionInt, 23)
  167. .SetExtension(UnitTestProtoFile.MyExtensionString, "bar")
  168. .Build().ToByteString();
  169. AssertFieldsInOrder(data);
  170. MessageDescriptor descriptor = TestFieldOrderings.Descriptor;
  171. ByteString dynamic_data =
  172. DynamicMessage.CreateBuilder(TestFieldOrderings.Descriptor)
  173. .SetField(descriptor.FindDescriptor<FieldDescriptor>("my_int"), 1L)
  174. .SetField(descriptor.FindDescriptor<FieldDescriptor>("my_string"), "foo")
  175. .SetField(descriptor.FindDescriptor<FieldDescriptor>("my_float"), 1.0F)
  176. .SetField(UnitTestProtoFile.MyExtensionInt.Descriptor, 23)
  177. .SetField(UnitTestProtoFile.MyExtensionString.Descriptor, "bar")
  178. .WeakBuild().ToByteString();
  179. AssertFieldsInOrder(dynamic_data);
  180. }
  181. private const int UnknownTypeId = 1550055;
  182. private static readonly int TypeId1 = TestMessageSetExtension1.Descriptor.Extensions[0].FieldNumber;
  183. private static readonly int TypeId2 = TestMessageSetExtension2.Descriptor.Extensions[0].FieldNumber;
  184. [TestMethod]
  185. public void SerializeMessageSet()
  186. {
  187. // Set up a TestMessageSet with two known messages and an unknown one.
  188. TestMessageSet messageSet =
  189. TestMessageSet.CreateBuilder()
  190. .SetExtension(
  191. TestMessageSetExtension1.MessageSetExtension,
  192. TestMessageSetExtension1.CreateBuilder().SetI(123).Build())
  193. .SetExtension(
  194. TestMessageSetExtension2.MessageSetExtension,
  195. TestMessageSetExtension2.CreateBuilder().SetStr("foo").Build())
  196. .SetUnknownFields(
  197. UnknownFieldSet.CreateBuilder()
  198. .AddField(UnknownTypeId,
  199. UnknownField.CreateBuilder()
  200. .AddLengthDelimited(ByteString.CopyFromUtf8("bar"))
  201. .Build())
  202. .Build())
  203. .Build();
  204. ByteString data = messageSet.ToByteString();
  205. // Parse back using RawMessageSet and check the contents.
  206. RawMessageSet raw = RawMessageSet.ParseFrom(data);
  207. Assert.AreEqual(0, raw.UnknownFields.FieldDictionary.Count);
  208. Assert.AreEqual(3, raw.ItemCount);
  209. Assert.AreEqual(TypeId1, raw.ItemList[0].TypeId);
  210. Assert.AreEqual(TypeId2, raw.ItemList[1].TypeId);
  211. Assert.AreEqual(UnknownTypeId, raw.ItemList[2].TypeId);
  212. TestMessageSetExtension1 message1 = TestMessageSetExtension1.ParseFrom(raw.GetItem(0).Message.ToByteArray());
  213. Assert.AreEqual(123, message1.I);
  214. TestMessageSetExtension2 message2 = TestMessageSetExtension2.ParseFrom(raw.GetItem(1).Message.ToByteArray());
  215. Assert.AreEqual("foo", message2.Str);
  216. Assert.AreEqual("bar", raw.GetItem(2).Message.ToStringUtf8());
  217. }
  218. [TestMethod]
  219. public void ParseMessageSet()
  220. {
  221. ExtensionRegistry extensionRegistry = ExtensionRegistry.CreateInstance();
  222. extensionRegistry.Add(TestMessageSetExtension1.MessageSetExtension);
  223. extensionRegistry.Add(TestMessageSetExtension2.MessageSetExtension);
  224. // Set up a RawMessageSet with two known messages and an unknown one.
  225. RawMessageSet raw =
  226. RawMessageSet.CreateBuilder()
  227. .AddItem(
  228. RawMessageSet.Types.Item.CreateBuilder()
  229. .SetTypeId(TypeId1)
  230. .SetMessage(
  231. TestMessageSetExtension1.CreateBuilder()
  232. .SetI(123)
  233. .Build().ToByteString())
  234. .Build())
  235. .AddItem(
  236. RawMessageSet.Types.Item.CreateBuilder()
  237. .SetTypeId(TypeId2)
  238. .SetMessage(
  239. TestMessageSetExtension2.CreateBuilder()
  240. .SetStr("foo")
  241. .Build().ToByteString())
  242. .Build())
  243. .AddItem(
  244. RawMessageSet.Types.Item.CreateBuilder()
  245. .SetTypeId(UnknownTypeId)
  246. .SetMessage(ByteString.CopyFromUtf8("bar"))
  247. .Build())
  248. .Build();
  249. ByteString data = raw.ToByteString();
  250. // Parse as a TestMessageSet and check the contents.
  251. TestMessageSet messageSet =
  252. TestMessageSet.ParseFrom(data, extensionRegistry);
  253. Assert.AreEqual(123, messageSet.GetExtension(TestMessageSetExtension1.MessageSetExtension).I);
  254. Assert.AreEqual("foo", messageSet.GetExtension(TestMessageSetExtension2.MessageSetExtension).Str);
  255. // Check for unknown field with type LENGTH_DELIMITED,
  256. // number UNKNOWN_TYPE_ID, and contents "bar".
  257. UnknownFieldSet unknownFields = messageSet.UnknownFields;
  258. Assert.AreEqual(1, unknownFields.FieldDictionary.Count);
  259. Assert.IsTrue(unknownFields.HasField(UnknownTypeId));
  260. UnknownField field = unknownFields[UnknownTypeId];
  261. Assert.AreEqual(1, field.LengthDelimitedList.Count);
  262. Assert.AreEqual("bar", field.LengthDelimitedList[0].ToStringUtf8());
  263. }
  264. }
  265. }