JsonFormatterTest.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using System;
  33. using System.Collections.Generic;
  34. using System.Linq;
  35. using System.Text;
  36. using System.Threading.Tasks;
  37. using Google.Protobuf.TestProtos;
  38. using NUnit.Framework;
  39. using UnitTest.Issues.TestProtos;
  40. namespace Google.Protobuf
  41. {
  42. public class JsonFormatterTest
  43. {
  44. [Test]
  45. public void DefaultValues_WhenOmitted()
  46. {
  47. var formatter = new JsonFormatter(new JsonFormatter.Settings(formatDefaultValues: false));
  48. Assert.AreEqual("{ }", formatter.Format(new ForeignMessage()));
  49. Assert.AreEqual("{ }", formatter.Format(new TestAllTypes()));
  50. Assert.AreEqual("{ }", formatter.Format(new TestMap()));
  51. }
  52. [Test]
  53. public void DefaultValues_WhenIncluded()
  54. {
  55. var formatter = new JsonFormatter(new JsonFormatter.Settings(formatDefaultValues: true));
  56. Assert.AreEqual("{ \"c\": 0 }", formatter.Format(new ForeignMessage()));
  57. }
  58. [Test]
  59. public void AllSingleFields()
  60. {
  61. var message = new TestAllTypes
  62. {
  63. SingleBool = true,
  64. SingleBytes = ByteString.CopyFrom(1, 2, 3, 4),
  65. SingleDouble = 23.5,
  66. SingleFixed32 = 23,
  67. SingleFixed64 = 1234567890123,
  68. SingleFloat = 12.25f,
  69. SingleForeignEnum = ForeignEnum.FOREIGN_BAR,
  70. SingleForeignMessage = new ForeignMessage { C = 10 },
  71. SingleImportEnum = ImportEnum.IMPORT_BAZ,
  72. SingleImportMessage = new ImportMessage { D = 20 },
  73. SingleInt32 = 100,
  74. SingleInt64 = 3210987654321,
  75. SingleNestedEnum = TestAllTypes.Types.NestedEnum.FOO,
  76. SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 },
  77. SinglePublicImportMessage = new PublicImportMessage { E = 54 },
  78. SingleSfixed32 = -123,
  79. SingleSfixed64 = -12345678901234,
  80. SingleSint32 = -456,
  81. SingleSint64 = -12345678901235,
  82. SingleString = "test\twith\ttabs",
  83. SingleUint32 = uint.MaxValue,
  84. SingleUint64 = ulong.MaxValue,
  85. };
  86. var actualText = JsonFormatter.Default.Format(message);
  87. // Fields in declaration order, which matches numeric order.
  88. var expectedText = "{ " +
  89. "\"singleInt32\": 100, " +
  90. "\"singleInt64\": \"3210987654321\", " +
  91. "\"singleUint32\": 4294967295, " +
  92. "\"singleUint64\": \"18446744073709551615\", " +
  93. "\"singleSint32\": -456, " +
  94. "\"singleSint64\": \"-12345678901235\", " +
  95. "\"singleFixed32\": 23, " +
  96. "\"singleFixed64\": \"1234567890123\", " +
  97. "\"singleSfixed32\": -123, " +
  98. "\"singleSfixed64\": \"-12345678901234\", " +
  99. "\"singleFloat\": 12.25, " +
  100. "\"singleDouble\": 23.5, " +
  101. "\"singleBool\": true, " +
  102. "\"singleString\": \"test\\twith\\ttabs\", " +
  103. "\"singleBytes\": \"AQIDBA==\", " +
  104. "\"singleNestedMessage\": { \"bb\": 35 }, " +
  105. "\"singleForeignMessage\": { \"c\": 10 }, " +
  106. "\"singleImportMessage\": { \"d\": 20 }, " +
  107. "\"singleNestedEnum\": \"FOO\", " +
  108. "\"singleForeignEnum\": \"FOREIGN_BAR\", " +
  109. "\"singleImportEnum\": \"IMPORT_BAZ\", " +
  110. "\"singlePublicImportMessage\": { \"e\": 54 }" +
  111. " }";
  112. Assert.AreEqual(expectedText, actualText);
  113. }
  114. [Test]
  115. public void RepeatedField()
  116. {
  117. Assert.AreEqual("{ \"repeatedInt32\": [ 1, 2, 3, 4, 5 ] }",
  118. JsonFormatter.Default.Format(new TestAllTypes { RepeatedInt32 = { 1, 2, 3, 4, 5 } }));
  119. }
  120. [Test]
  121. public void MapField_StringString()
  122. {
  123. Assert.AreEqual("{ \"mapStringString\": { \"with spaces\": \"bar\", \"a\": \"b\" } }",
  124. JsonFormatter.Default.Format(new TestMap { MapStringString = { { "with spaces", "bar" }, { "a", "b" } } }));
  125. }
  126. [Test]
  127. public void MapField_Int32Int32()
  128. {
  129. // The keys are quoted, but the values aren't.
  130. Assert.AreEqual("{ \"mapInt32Int32\": { \"0\": 1, \"2\": 3 } }",
  131. JsonFormatter.Default.Format(new TestMap { MapInt32Int32 = { { 0, 1 }, { 2, 3 } } }));
  132. }
  133. [Test]
  134. public void MapField_BoolBool()
  135. {
  136. // The keys are quoted, but the values aren't.
  137. Assert.AreEqual("{ \"mapBoolBool\": { \"false\": true, \"true\": false } }",
  138. JsonFormatter.Default.Format(new TestMap { MapBoolBool = { { false, true }, { true, false } } }));
  139. }
  140. [TestCase(1.0, "1")]
  141. [TestCase(double.NaN, "\"NaN\"")]
  142. [TestCase(double.PositiveInfinity, "\"Infinity\"")]
  143. [TestCase(double.NegativeInfinity, "\"-Infinity\"")]
  144. public void DoubleRepresentations(double value, string expectedValueText)
  145. {
  146. var message = new TestAllTypes { SingleDouble = value };
  147. string actualText = JsonFormatter.Default.Format(message);
  148. string expectedText = "{ \"singleDouble\": " + expectedValueText + " }";
  149. Assert.AreEqual(expectedText, actualText);
  150. }
  151. [Test]
  152. public void UnknownEnumValueOmitted_SingleField()
  153. {
  154. var message = new TestAllTypes { SingleForeignEnum = (ForeignEnum) 100 };
  155. Assert.AreEqual("{ }", JsonFormatter.Default.Format(message));
  156. }
  157. [Test]
  158. public void UnknownEnumValueOmitted_RepeatedField()
  159. {
  160. var message = new TestAllTypes { RepeatedForeignEnum = { ForeignEnum.FOREIGN_BAZ, (ForeignEnum) 100, ForeignEnum.FOREIGN_FOO } };
  161. Assert.AreEqual("{ \"repeatedForeignEnum\": [ \"FOREIGN_BAZ\", \"FOREIGN_FOO\" ] }", JsonFormatter.Default.Format(message));
  162. }
  163. [Test]
  164. public void UnknownEnumValueOmitted_MapField()
  165. {
  166. // This matches the C++ behaviour.
  167. var message = new TestMap { MapInt32Enum = { { 1, MapEnum.MAP_ENUM_FOO }, { 2, (MapEnum) 100 }, { 3, MapEnum.MAP_ENUM_BAR } } };
  168. Assert.AreEqual("{ \"mapInt32Enum\": { \"1\": \"MAP_ENUM_FOO\", \"3\": \"MAP_ENUM_BAR\" } }", JsonFormatter.Default.Format(message));
  169. }
  170. [Test]
  171. public void UnknownEnumValueOmitted_RepeatedField_AllEntriesUnknown()
  172. {
  173. // *Maybe* we should hold off on writing the "[" until we find that we've got at least one value to write...
  174. // but this is what happens at the moment, and it doesn't seem too awful.
  175. var message = new TestAllTypes { RepeatedForeignEnum = { (ForeignEnum) 200, (ForeignEnum) 100 } };
  176. Assert.AreEqual("{ \"repeatedForeignEnum\": [ ] }", JsonFormatter.Default.Format(message));
  177. }
  178. [Test]
  179. public void NullValueForMessage()
  180. {
  181. var message = new TestMap { MapInt32ForeignMessage = { { 10, null } } };
  182. Assert.AreEqual("{ \"mapInt32ForeignMessage\": { \"10\": null } }", JsonFormatter.Default.Format(message));
  183. }
  184. [Test]
  185. [TestCase("a\u17b4b", "a\\u17b4b")] // Explicit
  186. [TestCase("a\u0601b", "a\\u0601b")] // Ranged
  187. [TestCase("a\u0605b", "a\u0605b")] // Passthrough (note lack of double backslash...)
  188. public void SimpleNonAscii(string text, string encoded)
  189. {
  190. var message = new TestAllTypes { SingleString = text };
  191. Assert.AreEqual("{ \"singleString\": \"" + encoded + "\" }", JsonFormatter.Default.Format(message));
  192. }
  193. [Test]
  194. public void SurrogatePairEscaping()
  195. {
  196. var message = new TestAllTypes { SingleString = "a\uD801\uDC01b" };
  197. Assert.AreEqual("{ \"singleString\": \"a\\ud801\\udc01b\" }", JsonFormatter.Default.Format(message));
  198. }
  199. [Test]
  200. public void InvalidSurrogatePairsFail()
  201. {
  202. // Note: don't use TestCase for these, as the strings can't be reliably represented
  203. // See http://codeblog.jonskeet.uk/2014/11/07/when-is-a-string-not-a-string/
  204. // Lone low surrogate
  205. var message = new TestAllTypes { SingleString = "a\uDC01b" };
  206. Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message));
  207. // Lone high surrogate
  208. message = new TestAllTypes { SingleString = "a\uD801b" };
  209. Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message));
  210. }
  211. [Test]
  212. [TestCase("foo_bar", "fooBar")]
  213. [TestCase("bananaBanana", "bananaBanana")]
  214. [TestCase("BANANABanana", "bananaBanana")]
  215. public void ToCamelCase(string original, string expected)
  216. {
  217. Assert.AreEqual(expected, JsonFormatter.ToCamelCase(original));
  218. }
  219. [Test]
  220. [TestCase(null, "{ }")]
  221. [TestCase("x", "{ \"fooString\": \"x\" }")]
  222. [TestCase("", "{ \"fooString\": \"\" }")]
  223. [TestCase(null, "{ }")]
  224. public void Oneof(string fooStringValue, string expectedJson)
  225. {
  226. var message = new TestOneof();
  227. if (fooStringValue != null)
  228. {
  229. message.FooString = fooStringValue;
  230. }
  231. // We should get the same result both with and without "format default values".
  232. var formatter = new JsonFormatter(new JsonFormatter.Settings(false));
  233. Assert.AreEqual(expectedJson, formatter.Format(message));
  234. formatter = new JsonFormatter(new JsonFormatter.Settings(true));
  235. Assert.AreEqual(expectedJson, formatter.Format(message));
  236. }
  237. [Test]
  238. public void WrapperFormatting_Single()
  239. {
  240. // Just a few examples, handling both classes and value types, and
  241. // default vs non-default values
  242. var message = new TestWellKnownTypes
  243. {
  244. Int64Field = 10,
  245. Int32Field = 0,
  246. BytesField = ByteString.FromBase64("ABCD"),
  247. StringField = ""
  248. };
  249. var expectedJson = "{ \"int64Field\": \"10\", \"int32Field\": 0, \"stringField\": \"\", \"bytesField\": \"ABCD\" }";
  250. Assert.AreEqual(expectedJson, JsonFormatter.Default.Format(message));
  251. }
  252. [Test]
  253. public void WrapperFormatting_IncludeNull()
  254. {
  255. // The actual JSON here is very large because there are lots of fields. Just test a couple of them.
  256. var message = new TestWellKnownTypes { Int32Field = 10 };
  257. var formatter = new JsonFormatter(new JsonFormatter.Settings(true));
  258. var actualJson = formatter.Format(message);
  259. Assert.IsTrue(actualJson.Contains("\"int64Field\": null"));
  260. Assert.IsFalse(actualJson.Contains("\"int32Field\": null"));
  261. }
  262. [Test]
  263. public void OutputIsInNumericFieldOrder_NoDefaults()
  264. {
  265. var formatter = new JsonFormatter(new JsonFormatter.Settings(false));
  266. var message = new TestJsonFieldOrdering { PlainString = "p1", PlainInt32 = 2 };
  267. Assert.AreEqual("{ \"plainString\": \"p1\", \"plainInt32\": 2 }", formatter.Format(message));
  268. message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" };
  269. Assert.AreEqual("{ \"plainString\": \"plain\", \"o2String\": \"o2\", \"plainInt32\": 10, \"o1Int32\": 5 }", formatter.Format(message));
  270. message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" };
  271. Assert.AreEqual("{ \"plainString\": \"plain\", \"o1String\": \"\", \"plainInt32\": 10, \"o2Int32\": 0 }", formatter.Format(message));
  272. }
  273. [Test]
  274. public void OutputIsInNumericFieldOrder_WithDefaults()
  275. {
  276. var formatter = new JsonFormatter(new JsonFormatter.Settings(true));
  277. var message = new TestJsonFieldOrdering();
  278. Assert.AreEqual("{ \"plainString\": \"\", \"plainInt32\": 0 }", formatter.Format(message));
  279. message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" };
  280. Assert.AreEqual("{ \"plainString\": \"plain\", \"o2String\": \"o2\", \"plainInt32\": 10, \"o1Int32\": 5 }", formatter.Format(message));
  281. message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" };
  282. Assert.AreEqual("{ \"plainString\": \"plain\", \"o1String\": \"\", \"plainInt32\": 10, \"o2Int32\": 0 }", formatter.Format(message));
  283. }
  284. }
  285. }